<?php
/**
* (c) itmedia.by <info@itmedia.by>
*/
namespace Submarine\PagesBundle\Entity\Type;
use Postroyka\AppBundle\Redis\RedisBaseProvider;
use Submarine\CoreBundle\Entity\SubmarineEntityInterface;
use Submarine\CoreBundle\Exception\InvalidArgumentException;
use Submarine\PagesBundle\Entity\Page;
use Doctrine\ORM\Mapping as ORM;
/**
* Class PageTypeValue
* @package Submarine\PagesBundle
*
* @ORM\Entity()
* @ORM\Table(name="submarine_pages_values")
*
* @ORM\HasLifecycleCallbacks()
*/
class PageValue implements SubmarineEntityInterface
{
/**
* ID
* @var int
*
* @ORM\Column(name="id", type="integer", nullable=false, unique=true)
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Page
*
* @ORM\ManyToOne(targetEntity="Submarine\PagesBundle\Entity\Page", inversedBy="fields")
* @ORM\JoinColumn(name="page_id", referencedColumnName="id")
*/
private $page;
/**
* Поле типа
* @var PageTypeField
*
* @ORM\ManyToOne(targetEntity="Submarine\PagesBundle\Entity\Type\PageTypeField", inversedBy="values")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="field_id", referencedColumnName="id"),
* @ORM\JoinColumn(name="type_id", referencedColumnName="type_id")
* })
*/
private $field;
/**
* Значение
* @var string
*
* @ORM\Column(name="value", type="text", nullable=true)
*/
private $value;
public function __construct($field, $page, $value = null)
{
$this->field = $field;
$this->page = $page;
$this->setValue($value);
}
/**
* Имя сущности
* @return string
*/
public static function entityName()
{
return __CLASS__;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
public function __toString()
{
return (string)$this->value;
}
/**
* @return Page
*/
public function getPage()
{
return $this->page;
}
/**
* @return PageTypeField
*/
public function getField()
{
return $this->field;
}
/**
* @return string
*/
public function getValue()
{
if ($this->getField()->getValueType() === PageTypeField::TYPE_ITEM) {
return is_array(json_decode($this->value)) ? json_decode($this->value) : [$this->value];
}
if ($this->getField()->getValueType() === PageTypeField::TYPE_CHECKBOX) {
return (bool)$this->value;
}
return $this->value;
}
/**
* @param PageTypeField $field
*/
public function setField($field)
{
$this->field = $field;
}
/**
* @param string|array|null $value
*
* @throws InvalidArgumentException
*/
public function setValue($value)
{
if ($value instanceof Page) {
$value = $value->getId();
}
if (is_array($value)) {
$value = json_encode($value);
}
if (!(is_scalar($value) || is_array($value) || empty($value))) {
throw new InvalidArgumentException('Page Field Value must be string or array');
}
$this->value = $value;
}
/**
* @ORM\PreUpdate()
*/
public function preUpdate()
{
RedisBaseProvider::clearKeysByPattern('*' . RedisBaseProvider::REDIS_HOMEPAGE_KEY);
RedisBaseProvider::clearKeysByPattern('*' . RedisBaseProvider::CATALOG_PAGE_REDIS_KEY . '*');
}
}