<?php
namespace App\Entity\Gos\Uniqskills\Landing;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class LandingModuleJson extends LandingModuleItem
{
private function validateJson($string)
{
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
public function getVariableValueDecoded()
{
return $this->sortByPosition();
}
private function isArrayAssociative(array $array)
{
if (array() === $array) return false;
return array_keys($array) !== range(0, count($array) - 1);
}
private static function sortExecute($a, $b)
{
if (!isset($a['position']) || !isset($b['position'])) return 0;
if ($a['position'] == $b['position']) return 0;
return ($a['position'] < $b['position']) ? -1 : 1;
}
private function sortByPosition()
{
//sort by position if isset
$decoded = json_decode($this->variableValue, true);
//handle associative and normal arrays
$this->isArrayAssociative($decoded) ? uasort($decoded, array($this, 'sortExecute'))
: usort($decoded, array($this, 'sortExecute'));
return $decoded;
}
/* ****************************** GETTERS & SETTERS ****************************** */
/**
* @param string $variableValue
*
* @return LandingModuleJson
* @throws \Exception
*/
public function setVariableValue($variableValue)
{
if(!$variableValue) {
$this->variableValue = json_encode([]);
return $this;
}
if ($this->validateJson($variableValue))
{
$this->variableValue = $variableValue;
return $this;
}
throw new \Exception('Invalid json value');
}
/**
* @return string|null
*/
public function getVariableValue()
{
return json_encode($this->sortByPosition());
}
/**
* @return string
*/
public function getVariableType()
{
return $this::VARIABLE_TYPE_JSON;
}
}