* initial commit
This commit is contained in:
48
src/DoctrineExpressiveModule/ConfigProvider.php
Normal file
48
src/DoctrineExpressiveModule/ConfigProvider.php
Normal file
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineExpressiveModule;
|
||||
|
||||
use Zend\EventManager\EventManager;
|
||||
|
||||
/**
|
||||
* The configuration provider for the DoctrineExpressiveModule module
|
||||
*
|
||||
* @see https://docs.zendframework.com/zend-component-installer/
|
||||
*/
|
||||
class ConfigProvider
|
||||
{
|
||||
/**
|
||||
* Returns the configuration array
|
||||
*
|
||||
* To add a bit of a structure, each section is defined in a separate
|
||||
* method which returns an array with its configuration.
|
||||
*
|
||||
*/
|
||||
public function __invoke() : array
|
||||
{
|
||||
return [
|
||||
'dependencies' => $this->getDependencies(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container dependencies
|
||||
*/
|
||||
public function getDependencies() : array
|
||||
{
|
||||
return [
|
||||
'aliases' => [
|
||||
'doctrine.hydrator' => Hydrator\DoctrineObject::class,
|
||||
'EventManager' => EventManager::class,
|
||||
],
|
||||
'invokables' => [
|
||||
EventManager::class => EventManager::class,
|
||||
],
|
||||
'factories' => [
|
||||
Hydrator\DoctrineObject::class => Hydrator\DoctrineObjectFactory::class,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element\Exception;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class InvalidRepositoryResultException extends InvalidArgumentException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\MultiCheckbox;
|
||||
use Zend\Form\Form;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
class ObjectMultiCheckbox extends MultiCheckbox
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
if ($value instanceof \Traversable) {
|
||||
$value = ArrayUtils::iteratorToArray($value);
|
||||
} elseif ($value == null) {
|
||||
return parent::setValue([]);
|
||||
} elseif (! is_array($value)) {
|
||||
$value = (array)$value;
|
||||
}
|
||||
|
||||
return parent::setValue(array_map([$this->getProxy(), 'getValue'], $value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
73
src/DoctrineExpressiveModule/Form/Element/ObjectRadio.php
Normal file
73
src/DoctrineExpressiveModule/Form/Element/ObjectRadio.php
Normal file
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineExpressiveModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\Radio as RadioElement;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class ObjectRadio extends RadioElement
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
return parent::setValue($this->getProxy()->getValue($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
88
src/DoctrineExpressiveModule/Form/Element/ObjectSelect.php
Normal file
88
src/DoctrineExpressiveModule/Form/Element/ObjectSelect.php
Normal file
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineExpressiveModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\Select as SelectElement;
|
||||
use Zend\Form\Form;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
class ObjectSelect extends SelectElement
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
$multiple = $this->getAttribute('multiple');
|
||||
|
||||
if (true === $multiple || 'multiple' === $multiple) {
|
||||
if ($value instanceof \Traversable) {
|
||||
$value = ArrayUtils::iteratorToArray($value);
|
||||
} elseif ($value == null) {
|
||||
return parent::setValue([]);
|
||||
} elseif (! is_array($value)) {
|
||||
$value = (array) $value;
|
||||
}
|
||||
|
||||
return parent::setValue(array_map([$this->getProxy(), 'getValue'], $value));
|
||||
}
|
||||
|
||||
return parent::setValue($this->getProxy()->getValue($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
653
src/DoctrineExpressiveModule/Form/Element/Proxy.php
Normal file
653
src/DoctrineExpressiveModule/Form/Element/Proxy.php
Normal file
@@ -0,0 +1,653 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use Traversable;
|
||||
use ReflectionMethod;
|
||||
use RuntimeException;
|
||||
use InvalidArgumentException;
|
||||
use Zend\Stdlib\Guard\ArrayOrTraversableGuardTrait;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Doctrine\Common\Util\Inflector;
|
||||
|
||||
class Proxy
|
||||
{
|
||||
use ArrayOrTraversableGuardTrait;
|
||||
|
||||
/**
|
||||
* @var array|Traversable
|
||||
*/
|
||||
protected $objects;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $targetClass;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $valueOptions = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $findMethod = [];
|
||||
|
||||
/**
|
||||
* @var
|
||||
*/
|
||||
protected $property;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $option_attributes = [];
|
||||
|
||||
/**
|
||||
* @var callable $labelGenerator A callable used to create a label based on an item in the collection an Entity
|
||||
*/
|
||||
protected $labelGenerator;
|
||||
|
||||
/**
|
||||
* @var bool|null
|
||||
*/
|
||||
protected $isMethod;
|
||||
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $displayEmptyItem = false;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $emptyItemLabel = '';
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $optgroupIdentifier;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $optgroupDefault;
|
||||
|
||||
public function setOptions($options)
|
||||
{
|
||||
if (isset($options['object_manager'])) {
|
||||
$this->setObjectManager($options['object_manager']);
|
||||
}
|
||||
|
||||
if (isset($options['target_class'])) {
|
||||
$this->setTargetClass($options['target_class']);
|
||||
}
|
||||
|
||||
if (isset($options['property'])) {
|
||||
$this->setProperty($options['property']);
|
||||
}
|
||||
|
||||
if (isset($options['label_generator'])) {
|
||||
$this->setLabelGenerator($options['label_generator']);
|
||||
}
|
||||
|
||||
if (isset($options['find_method'])) {
|
||||
$this->setFindMethod($options['find_method']);
|
||||
}
|
||||
|
||||
if (isset($options['is_method'])) {
|
||||
$this->setIsMethod($options['is_method']);
|
||||
}
|
||||
|
||||
if (isset($options['display_empty_item'])) {
|
||||
$this->setDisplayEmptyItem($options['display_empty_item']);
|
||||
}
|
||||
|
||||
if (isset($options['empty_item_label'])) {
|
||||
$this->setEmptyItemLabel($options['empty_item_label']);
|
||||
}
|
||||
|
||||
if (isset($options['option_attributes'])) {
|
||||
$this->setOptionAttributes($options['option_attributes']);
|
||||
}
|
||||
|
||||
if (isset($options['optgroup_identifier'])) {
|
||||
$this->setOptgroupIdentifier($options['optgroup_identifier']);
|
||||
}
|
||||
|
||||
if (isset($options['optgroup_default'])) {
|
||||
$this->setOptgroupDefault($options['optgroup_default']);
|
||||
}
|
||||
}
|
||||
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (empty($this->valueOptions)) {
|
||||
$this->loadValueOptions();
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|Traversable
|
||||
*/
|
||||
public function getObjects()
|
||||
{
|
||||
$this->loadObjects();
|
||||
|
||||
return $this->objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the label for the empty option
|
||||
*
|
||||
* @param string $emptyItemLabel
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setEmptyItemLabel($emptyItemLabel)
|
||||
{
|
||||
$this->emptyItemLabel = $emptyItemLabel;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getEmptyItemLabel()
|
||||
{
|
||||
return $this->emptyItemLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOptionAttributes()
|
||||
{
|
||||
return $this->option_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $option_attributes
|
||||
*/
|
||||
public function setOptionAttributes(array $option_attributes)
|
||||
{
|
||||
$this->option_attributes = $option_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a flag, whether to include the empty option at the beginning or not
|
||||
*
|
||||
* @param boolean $displayEmptyItem
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setDisplayEmptyItem($displayEmptyItem)
|
||||
{
|
||||
$this->displayEmptyItem = $displayEmptyItem;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function getDisplayEmptyItem()
|
||||
{
|
||||
return $this->displayEmptyItem;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the object manager
|
||||
*
|
||||
* @param ObjectManager $objectManager
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setObjectManager(ObjectManager $objectManager)
|
||||
{
|
||||
$this->objectManager = $objectManager;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the object manager
|
||||
*
|
||||
* @return ObjectManager
|
||||
*/
|
||||
public function getObjectManager()
|
||||
{
|
||||
return $this->objectManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the FQCN of the target object
|
||||
*
|
||||
* @param string $targetClass
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setTargetClass($targetClass)
|
||||
{
|
||||
$this->targetClass = $targetClass;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the target class
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getTargetClass()
|
||||
{
|
||||
return $this->targetClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the property to use as the label in the options
|
||||
*
|
||||
* @param string $property
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setProperty($property)
|
||||
{
|
||||
$this->property = $property;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getProperty()
|
||||
{
|
||||
return $this->property;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the label generator callable that is responsible for generating labels for the items in the collection
|
||||
*
|
||||
* @param callable $callable A callable used to create a label based off of an Entity
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setLabelGenerator($callable)
|
||||
{
|
||||
if (! is_callable($callable)) {
|
||||
throw new InvalidArgumentException(
|
||||
'Property "label_generator" needs to be a callable function or a \Closure'
|
||||
);
|
||||
}
|
||||
|
||||
$this->labelGenerator = $callable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return callable|null
|
||||
*/
|
||||
public function getLabelGenerator()
|
||||
{
|
||||
return $this->labelGenerator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOptgroupIdentifier()
|
||||
{
|
||||
return $this->optgroupIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $optgroupIdentifier
|
||||
*/
|
||||
public function setOptgroupIdentifier($optgroupIdentifier)
|
||||
{
|
||||
$this->optgroupIdentifier = (string) $optgroupIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOptgroupDefault()
|
||||
{
|
||||
return $this->optgroupDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $optgroupDefault
|
||||
*/
|
||||
public function setOptgroupDefault($optgroupDefault)
|
||||
{
|
||||
$this->optgroupDefault = (string) $optgroupDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set if the property is a method to use as the label in the options
|
||||
*
|
||||
* @param boolean $method
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setIsMethod($method)
|
||||
{
|
||||
$this->isMethod = (bool) $method;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getIsMethod()
|
||||
{
|
||||
return $this->isMethod;
|
||||
}
|
||||
|
||||
/** Set the findMethod property to specify the method to use on repository
|
||||
*
|
||||
* @param array $findMethod
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setFindMethod($findMethod)
|
||||
{
|
||||
$this->findMethod = $findMethod;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get findMethod definition
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getFindMethod()
|
||||
{
|
||||
return $this->findMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $targetEntity
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function generateLabel($targetEntity)
|
||||
{
|
||||
if (null === ($labelGenerator = $this->getLabelGenerator())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return call_user_func($labelGenerator, $targetEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
*
|
||||
* @return array|mixed|object
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function getValue($value)
|
||||
{
|
||||
if (! ($om = $this->getObjectManager())) {
|
||||
throw new RuntimeException('No object manager was set');
|
||||
}
|
||||
|
||||
if (! ($targetClass = $this->getTargetClass())) {
|
||||
throw new RuntimeException('No target class was set');
|
||||
}
|
||||
|
||||
$metadata = $om->getClassMetadata($targetClass);
|
||||
|
||||
if (is_object($value)) {
|
||||
if ($value instanceof Collection) {
|
||||
$data = [];
|
||||
|
||||
foreach ($value as $object) {
|
||||
$values = $metadata->getIdentifierValues($object);
|
||||
$data[] = array_shift($values);
|
||||
}
|
||||
|
||||
$value = $data;
|
||||
} else {
|
||||
$metadata = $om->getClassMetadata(get_class($value));
|
||||
$identifier = $metadata->getIdentifierFieldNames();
|
||||
|
||||
// TODO: handle composite (multiple) identifiers
|
||||
if (null !== $identifier && count($identifier) > 1) {
|
||||
//$value = $key;
|
||||
} else {
|
||||
$value = current($metadata->getIdentifierValues($value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load objects
|
||||
*
|
||||
* @throws RuntimeException
|
||||
* @throws Exception\InvalidRepositoryResultException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadObjects()
|
||||
{
|
||||
if (! empty($this->objects)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$findMethod = (array) $this->getFindMethod();
|
||||
|
||||
if (! $findMethod) {
|
||||
$findMethodName = 'findAll';
|
||||
$repository = $this->objectManager->getRepository($this->targetClass);
|
||||
$objects = $repository->findAll();
|
||||
} else {
|
||||
if (! isset($findMethod['name'])) {
|
||||
throw new RuntimeException('No method name was set');
|
||||
}
|
||||
$findMethodName = $findMethod['name'];
|
||||
$findMethodParams = isset($findMethod['params']) ? array_change_key_case($findMethod['params']) : [];
|
||||
$repository = $this->objectManager->getRepository($this->targetClass);
|
||||
|
||||
if (! method_exists($repository, $findMethodName)) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Method "%s" could not be found in repository "%s"',
|
||||
$findMethodName,
|
||||
get_class($repository)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$r = new ReflectionMethod($repository, $findMethodName);
|
||||
$args = [];
|
||||
|
||||
foreach ($r->getParameters() as $param) {
|
||||
if (array_key_exists(strtolower($param->getName()), $findMethodParams)) {
|
||||
$args[] = $findMethodParams[strtolower($param->getName())];
|
||||
} elseif ($param->isDefaultValueAvailable()) {
|
||||
$args[] = $param->getDefaultValue();
|
||||
} elseif (! $param->isOptional()) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Required parameter "%s" with no default value for method "%s" in repository "%s"'
|
||||
. ' was not provided',
|
||||
$param->getName(),
|
||||
$findMethodName,
|
||||
get_class($repository)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
$objects = $r->invokeArgs($repository, $args);
|
||||
}
|
||||
|
||||
$this->guardForArrayOrTraversable(
|
||||
$objects,
|
||||
sprintf('%s::%s() return value', get_class($repository), $findMethodName),
|
||||
'DoctrineModule\Form\Element\Exception\InvalidRepositoryResultException'
|
||||
);
|
||||
|
||||
$this->objects = $objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load value options
|
||||
*
|
||||
* @throws RuntimeException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadValueOptions()
|
||||
{
|
||||
if (! ($om = $this->objectManager)) {
|
||||
throw new RuntimeException('No object manager was set');
|
||||
}
|
||||
|
||||
if (! ($targetClass = $this->targetClass)) {
|
||||
throw new RuntimeException('No target class was set');
|
||||
}
|
||||
|
||||
$metadata = $om->getClassMetadata($targetClass);
|
||||
$identifier = $metadata->getIdentifierFieldNames();
|
||||
$objects = $this->getObjects();
|
||||
$options = [];
|
||||
$optionAttributes = [];
|
||||
|
||||
if ($this->displayEmptyItem) {
|
||||
$options[''] = $this->getEmptyItemLabel();
|
||||
}
|
||||
|
||||
foreach ($objects as $key => $object) {
|
||||
if (null !== ($generatedLabel = $this->generateLabel($object))) {
|
||||
$label = $generatedLabel;
|
||||
} elseif ($property = $this->property) {
|
||||
if ($this->isMethod == false && ! $metadata->hasField($property)) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Property "%s" could not be found in object "%s"',
|
||||
$property,
|
||||
$targetClass
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$getter = 'get' . Inflector::classify($property);
|
||||
|
||||
if (! is_callable([$object, $getter])) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Method "%s::%s" is not callable', $this->targetClass, $getter)
|
||||
);
|
||||
}
|
||||
|
||||
$label = $object->{$getter}();
|
||||
} else {
|
||||
if (! is_callable([$object, '__toString'])) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'%s must have a "__toString()" method defined if you have not set a property'
|
||||
. ' or method to use.',
|
||||
$targetClass
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$label = (string) $object;
|
||||
}
|
||||
|
||||
if (null !== $identifier && count($identifier) > 1) {
|
||||
$value = $key;
|
||||
} else {
|
||||
$value = current($metadata->getIdentifierValues($object));
|
||||
}
|
||||
|
||||
foreach ($this->getOptionAttributes() as $optionKey => $optionValue) {
|
||||
if (is_string($optionValue)) {
|
||||
$optionAttributes[$optionKey] = $optionValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_callable($optionValue)) {
|
||||
$callableValue = call_user_func($optionValue, $object);
|
||||
$optionAttributes[$optionKey] = (string) $callableValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Parameter "option_attributes" expects an array of key => value where value is of type'
|
||||
. '"string" or "callable". Value of type "%s" found.',
|
||||
gettype($optionValue)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// If no optgroup_identifier has been configured, apply default handling and continue
|
||||
if (is_null($this->getOptgroupIdentifier())) {
|
||||
$options[] = ['label' => $label, 'value' => $value, 'attributes' => $optionAttributes];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// optgroup_identifier found, handle grouping
|
||||
$optgroupGetter = 'get' . Inflector::classify($this->getOptgroupIdentifier());
|
||||
|
||||
if (! is_callable([$object, $optgroupGetter])) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Method "%s::%s" is not callable', $this->targetClass, $optgroupGetter)
|
||||
);
|
||||
}
|
||||
|
||||
$optgroup = $object->{$optgroupGetter}();
|
||||
|
||||
// optgroup_identifier contains a valid group-name. Handle default grouping.
|
||||
if (false === is_null($optgroup) && trim($optgroup) !== '') {
|
||||
$options[$optgroup]['label'] = $optgroup;
|
||||
$options[$optgroup]['options'][] = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'attributes' => $optionAttributes,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$optgroupDefault = $this->getOptgroupDefault();
|
||||
|
||||
// No optgroup_default has been provided. Line up without a group
|
||||
if (is_null($optgroupDefault)) {
|
||||
$options[] = ['label' => $label, 'value' => $value, 'attributes' => $optionAttributes];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Line up entry with optgroup_default
|
||||
$options[$optgroupDefault]['label'] = $optgroupDefault;
|
||||
$options[$optgroupDefault]['options'][] = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'attributes' => $optionAttributes,
|
||||
];
|
||||
}
|
||||
|
||||
$this->valueOptions = $options;
|
||||
}
|
||||
}
|
||||
594
src/DoctrineExpressiveModule/Hydrator/DoctrineObject.php
Normal file
594
src/DoctrineExpressiveModule/Hydrator/DoctrineObject.php
Normal file
@@ -0,0 +1,594 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator;
|
||||
|
||||
use DateTime;
|
||||
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Doctrine\Common\Util\Inflector;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Traversable;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
use Zend\Hydrator\AbstractHydrator;
|
||||
use Zend\Hydrator\Filter\FilterProviderInterface;
|
||||
|
||||
/**
|
||||
* This hydrator has been completely refactored for DoctrineModule 0.7.0. It provides an easy and powerful way
|
||||
* of extracting/hydrator objects in Doctrine, by handling most associations types.
|
||||
*
|
||||
* Starting from DoctrineModule 0.8.0, the hydrator can be used multiple times with different objects
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DoctrineObject extends AbstractHydrator
|
||||
{
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var ClassMetadata
|
||||
*/
|
||||
protected $metadata;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $byValue = true;
|
||||
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param ObjectManager $objectManager The ObjectManager to use
|
||||
* @param bool $byValue If set to true, hydrator will always use entity's public API
|
||||
*/
|
||||
public function __construct(ObjectManager $objectManager, $byValue = true)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->objectManager = $objectManager;
|
||||
$this->byValue = (bool) $byValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object
|
||||
*
|
||||
* @param object $object
|
||||
* @return array
|
||||
*/
|
||||
public function extract($object)
|
||||
{
|
||||
$this->prepare($object);
|
||||
|
||||
if ($this->byValue) {
|
||||
return $this->extractByValue($object);
|
||||
}
|
||||
|
||||
return $this->extractByReference($object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate $object with the provided $data.
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
public function hydrate(array $data, $object)
|
||||
{
|
||||
$this->prepare($object);
|
||||
|
||||
if ($this->byValue) {
|
||||
return $this->hydrateByValue($data, $object);
|
||||
}
|
||||
|
||||
return $this->hydrateByReference($data, $object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the hydrator by adding strategies to every collection valued associations
|
||||
*
|
||||
* @param object $object
|
||||
* @return void
|
||||
*/
|
||||
protected function prepare($object)
|
||||
{
|
||||
$this->metadata = $this->objectManager->getClassMetadata(get_class($object));
|
||||
$this->prepareStrategies();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare strategies before the hydrator is used
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareStrategies()
|
||||
{
|
||||
$associations = $this->metadata->getAssociationNames();
|
||||
|
||||
foreach ($associations as $association) {
|
||||
if ($this->metadata->isCollectionValuedAssociation($association)) {
|
||||
// Add a strategy if the association has none set by user
|
||||
if (!$this->hasStrategy($association)) {
|
||||
if ($this->byValue) {
|
||||
$this->addStrategy($association, new Strategy\AllowRemoveByValue());
|
||||
} else {
|
||||
$this->addStrategy($association, new Strategy\AllowRemoveByReference());
|
||||
}
|
||||
}
|
||||
|
||||
$strategy = $this->getStrategy($association);
|
||||
|
||||
if (!$strategy instanceof Strategy\AbstractCollectionStrategy) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf(
|
||||
'Strategies used for collections valued associations must inherit from '
|
||||
. 'Strategy\AbstractCollectionStrategy, %s given',
|
||||
get_class($strategy)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$strategy->setCollectionName($association)
|
||||
->setClassMetadata($this->metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object using a by-value logic (this means that it uses the entity
|
||||
* API, in this case, getters)
|
||||
*
|
||||
* @param object $object
|
||||
* @throws RuntimeException
|
||||
* @return array
|
||||
*/
|
||||
protected function extractByValue($object)
|
||||
{
|
||||
$fieldNames = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
|
||||
$methods = get_class_methods($object);
|
||||
$filter = $object instanceof FilterProviderInterface
|
||||
? $object->getFilter()
|
||||
: $this->filterComposite;
|
||||
|
||||
$data = [];
|
||||
foreach ($fieldNames as $fieldName) {
|
||||
if ($filter && !$filter->filter($fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$getter = 'get' . Inflector::classify($fieldName);
|
||||
$isser = 'is' . Inflector::classify($fieldName);
|
||||
|
||||
$dataFieldName = $this->computeExtractFieldName($fieldName);
|
||||
if (in_array($getter, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$getter(), $object);
|
||||
} elseif (in_array($isser, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$isser(), $object);
|
||||
} elseif (substr($fieldName, 0, 2) === 'is'
|
||||
&& ctype_upper(substr($fieldName, 2, 1))
|
||||
&& in_array($fieldName, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$fieldName(), $object);
|
||||
}
|
||||
|
||||
// Unknown fields are ignored
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object using a by-reference logic (this means that values are
|
||||
* directly fetched without using the public API of the entity, in this case, getters)
|
||||
*
|
||||
* @param object $object
|
||||
* @return array
|
||||
*/
|
||||
protected function extractByReference($object)
|
||||
{
|
||||
$fieldNames = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
|
||||
$refl = $this->metadata->getReflectionClass();
|
||||
$filter = $object instanceof FilterProviderInterface
|
||||
? $object->getFilter()
|
||||
: $this->filterComposite;
|
||||
|
||||
$data = [];
|
||||
foreach ($fieldNames as $fieldName) {
|
||||
if ($filter && !$filter->filter($fieldName)) {
|
||||
continue;
|
||||
}
|
||||
$reflProperty = $refl->getProperty($fieldName);
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
$dataFieldName = $this->computeExtractFieldName($fieldName);
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $reflProperty->getValue($object), $object);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the object using a by-value logic (this means that it uses the entity API, in this
|
||||
* case, setters)
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @throws RuntimeException
|
||||
* @return object
|
||||
*/
|
||||
protected function hydrateByValue(array $data, $object)
|
||||
{
|
||||
$tryObject = $this->tryConvertArrayToObject($data, $object);
|
||||
$metadata = $this->metadata;
|
||||
|
||||
if (is_object($tryObject)) {
|
||||
$object = $tryObject;
|
||||
}
|
||||
|
||||
foreach ($data as $field => $value) {
|
||||
$field = $this->computeHydrateFieldName($field);
|
||||
$value = $this->handleTypeConversions($value, $metadata->getTypeOfField($field));
|
||||
$setter = 'set' . Inflector::classify($field);
|
||||
|
||||
if ($metadata->hasAssociation($field)) {
|
||||
$target = $metadata->getAssociationTargetClass($field);
|
||||
|
||||
if ($metadata->isSingleValuedAssociation($field)) {
|
||||
if (! method_exists($object, $setter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
|
||||
|
||||
if (null === $value
|
||||
&& !current($metadata->getReflectionClass()->getMethod($setter)->getParameters())->allowsNull()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$object->$setter($value);
|
||||
} elseif ($metadata->isCollectionValuedAssociation($field)) {
|
||||
$this->toMany($object, $field, $target, $value);
|
||||
}
|
||||
} else {
|
||||
if (! method_exists($object, $setter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$object->$setter($this->hydrateValue($field, $value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the object using a by-reference logic (this means that values are modified directly without
|
||||
* using the public API, in this case setters, and hence override any logic that could be done in those
|
||||
* setters)
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
protected function hydrateByReference(array $data, $object)
|
||||
{
|
||||
$tryObject = $this->tryConvertArrayToObject($data, $object);
|
||||
$metadata = $this->metadata;
|
||||
$refl = $metadata->getReflectionClass();
|
||||
|
||||
if (is_object($tryObject)) {
|
||||
$object = $tryObject;
|
||||
}
|
||||
|
||||
foreach ($data as $field => $value) {
|
||||
$field = $this->computeHydrateFieldName($field);
|
||||
|
||||
// Ignore unknown fields
|
||||
if (!$refl->hasProperty($field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->handleTypeConversions($value, $metadata->getTypeOfField($field));
|
||||
$reflProperty = $refl->getProperty($field);
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
if ($metadata->hasAssociation($field)) {
|
||||
$target = $metadata->getAssociationTargetClass($field);
|
||||
|
||||
if ($metadata->isSingleValuedAssociation($field)) {
|
||||
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
|
||||
$reflProperty->setValue($object, $value);
|
||||
} elseif ($metadata->isCollectionValuedAssociation($field)) {
|
||||
$this->toMany($object, $field, $target, $value);
|
||||
}
|
||||
} else {
|
||||
$reflProperty->setValue($object, $this->hydrateValue($field, $value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function tries, given an array of data, to convert it to an object if the given array contains
|
||||
* an identifier for the object. This is useful in a context of updating existing entities, without ugly
|
||||
* tricks like setting manually the existing id directly into the entity
|
||||
*
|
||||
* @param array $data The data that may contain identifiers keys
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
protected function tryConvertArrayToObject($data, $object)
|
||||
{
|
||||
$metadata = $this->metadata;
|
||||
$identifierNames = $metadata->getIdentifierFieldNames($object);
|
||||
$identifierValues = [];
|
||||
|
||||
if (empty($identifierNames)) {
|
||||
return $object;
|
||||
}
|
||||
|
||||
foreach ($identifierNames as $identifierName) {
|
||||
if (!isset($data[$identifierName])) {
|
||||
return $object;
|
||||
}
|
||||
|
||||
$identifierValues[$identifierName] = $data[$identifierName];
|
||||
}
|
||||
|
||||
return $this->find($identifierValues, $metadata->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ToOne associations
|
||||
*
|
||||
* When $value is an array but is not the $target's identifiers, $value is
|
||||
* most likely an array of fieldset data. The identifiers will be determined
|
||||
* and a target instance will be initialized and then hydrated. The hydrated
|
||||
* target will be returned.
|
||||
*
|
||||
* @param string $target
|
||||
* @param mixed $value
|
||||
* @return object
|
||||
*/
|
||||
protected function toOne($target, $value)
|
||||
{
|
||||
$metadata = $this->objectManager->getClassMetadata($target);
|
||||
|
||||
if (is_array($value) && array_keys($value) != $metadata->getIdentifier()) {
|
||||
// $value is most likely an array of fieldset data
|
||||
$identifiers = array_intersect_key(
|
||||
$value,
|
||||
array_flip($metadata->getIdentifier())
|
||||
);
|
||||
$object = $this->find($identifiers, $target) ?: new $target;
|
||||
return $this->hydrate($value, $object);
|
||||
}
|
||||
|
||||
return $this->find($value, $target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ToMany associations. In proper Doctrine design, Collections should not be swapped, so
|
||||
* collections are always handled by reference. Internally, every collection is handled using specials
|
||||
* strategies that inherit from AbstractCollectionStrategy class, and that add or remove elements but without
|
||||
* changing the collection of the object
|
||||
*
|
||||
* @param object $object
|
||||
* @param mixed $collectionName
|
||||
* @param string $target
|
||||
* @param mixed $values
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function toMany($object, $collectionName, $target, $values)
|
||||
{
|
||||
$metadata = $this->objectManager->getClassMetadata(ltrim($target, '\\'));
|
||||
$identifier = $metadata->getIdentifier();
|
||||
|
||||
if (!is_array($values) && !$values instanceof Traversable) {
|
||||
$values = (array)$values;
|
||||
}
|
||||
|
||||
$collection = [];
|
||||
|
||||
// If the collection contains identifiers, fetch the objects from database
|
||||
foreach ($values as $value) {
|
||||
if ($value instanceof $target) {
|
||||
// assumes modifications have already taken place in object
|
||||
$collection[] = $value;
|
||||
continue;
|
||||
} elseif (empty($value)) {
|
||||
// assumes no id and retrieves new $target
|
||||
$collection[] = $this->find($value, $target);
|
||||
continue;
|
||||
}
|
||||
|
||||
$find = [];
|
||||
if (is_array($identifier)) {
|
||||
foreach ($identifier as $field) {
|
||||
switch (gettype($value)) {
|
||||
case 'object':
|
||||
$getter = 'get' . ucfirst($field);
|
||||
if (method_exists($value, $getter)) {
|
||||
$find[$field] = $value->$getter();
|
||||
} elseif (property_exists($value, $field)) {
|
||||
$find[$field] = $value->$field;
|
||||
}
|
||||
break;
|
||||
case 'array':
|
||||
if (array_key_exists($field, $value) && $value[$field] != null) {
|
||||
$find[$field] = $value[$field];
|
||||
unset($value[$field]); // removed identifier from persistable data
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$find[$field] = $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($find) && $found = $this->find($find, $target)) {
|
||||
$collection[] = (is_array($value)) ? $this->hydrate($value, $found) : $found;
|
||||
} else {
|
||||
$collection[] = (is_array($value)) ? $this->hydrate($value, new $target) : new $target;
|
||||
}
|
||||
}
|
||||
|
||||
$collection = array_filter(
|
||||
$collection,
|
||||
function ($item) {
|
||||
return null !== $item;
|
||||
}
|
||||
);
|
||||
|
||||
// Set the object so that the strategy can extract the Collection from it
|
||||
|
||||
/** @var \DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy $collectionStrategy */
|
||||
$collectionStrategy = $this->getStrategy($collectionName);
|
||||
$collectionStrategy->setObject($object);
|
||||
|
||||
// We could directly call hydrate method from the strategy, but if people want to override
|
||||
// hydrateValue function, they can do it and do their own stuff
|
||||
$this->hydrateValue($collectionName, $collection, $values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle various type conversions that should be supported natively by Doctrine (like DateTime)
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param string $typeOfField
|
||||
* @return DateTime
|
||||
*/
|
||||
protected function handleTypeConversions($value, $typeOfField)
|
||||
{
|
||||
switch ($typeOfField) {
|
||||
case 'datetimetz':
|
||||
case 'datetime':
|
||||
case 'time':
|
||||
case 'date':
|
||||
if ('' === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_int($value)) {
|
||||
$dateTime = new DateTime();
|
||||
$dateTime->setTimestamp($value);
|
||||
$value = $dateTime;
|
||||
} elseif (is_string($value)) {
|
||||
$value = new DateTime($value);
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an object by a given target class and identifier
|
||||
*
|
||||
* @param mixed $identifiers
|
||||
* @param string $targetClass
|
||||
*
|
||||
* @return object|null
|
||||
*/
|
||||
protected function find($identifiers, $targetClass)
|
||||
{
|
||||
if ($identifiers instanceof $targetClass) {
|
||||
return $identifiers;
|
||||
}
|
||||
|
||||
if ($this->isNullIdentifier($identifiers)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->objectManager->find($targetClass, $identifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies if a provided identifier is to be considered null
|
||||
*
|
||||
* @param mixed $identifier
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function isNullIdentifier($identifier)
|
||||
{
|
||||
if (null === $identifier) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($identifier instanceof Traversable || is_array($identifier)) {
|
||||
$nonNullIdentifiers = array_filter(
|
||||
ArrayUtils::iteratorToArray($identifier),
|
||||
function ($value) {
|
||||
return null !== $value;
|
||||
}
|
||||
);
|
||||
|
||||
return empty($nonNullIdentifiers);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the naming strategy if there is one set
|
||||
*
|
||||
* @param string $field
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function computeHydrateFieldName($field)
|
||||
{
|
||||
if ($this->hasNamingStrategy()) {
|
||||
$field = $this->getNamingStrategy()->hydrate($field);
|
||||
}
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the naming strategy if there is one set
|
||||
*
|
||||
* @param string $field
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function computeExtractFieldName($field)
|
||||
{
|
||||
if ($this->hasNamingStrategy()) {
|
||||
$field = $this->getNamingStrategy()->extract($field);
|
||||
}
|
||||
return $field;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
|
||||
class DoctrineObjectFactory
|
||||
{
|
||||
|
||||
public function __invoke(ContainerInterface $container)
|
||||
{
|
||||
$em = $container->get('doctrine.entity_manager.orm_default');
|
||||
return new DoctrineObject($em);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Filter;
|
||||
|
||||
use Zend\Hydrator\Filter\FilterInterface;
|
||||
|
||||
/**
|
||||
* Provides a filter to restrict returned fields by whitelisting or
|
||||
* blacklisting property names.
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @author Liam O'Boyle <liam@ontheroad.net.nz>
|
||||
*/
|
||||
class PropertyName implements FilterInterface
|
||||
{
|
||||
/**
|
||||
* The propteries to exclude.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $properties = [];
|
||||
|
||||
/**
|
||||
* Either an exclude or an include.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $exclude = null;
|
||||
|
||||
/**
|
||||
* @param [ string | array ] $properties The properties to exclude or include.
|
||||
* @param bool $exclude If the method should be excluded
|
||||
*/
|
||||
public function __construct($properties, $exclude = true)
|
||||
{
|
||||
$this->exclude = $exclude;
|
||||
$this->properties = is_array($properties)
|
||||
? $properties
|
||||
: [$properties];
|
||||
}
|
||||
|
||||
public function filter($property)
|
||||
{
|
||||
return in_array($property, $this->properties)
|
||||
? !$this->exclude
|
||||
: $this->exclude;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
|
||||
use Zend\Hydrator\Strategy\StrategyInterface;
|
||||
|
||||
/**
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
abstract class AbstractCollectionStrategy implements StrategyInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $collectionName;
|
||||
|
||||
/**
|
||||
* @var ClassMetadata
|
||||
*/
|
||||
protected $metadata;
|
||||
|
||||
/**
|
||||
* @var object
|
||||
*/
|
||||
protected $object;
|
||||
|
||||
|
||||
/**
|
||||
* Set the name of the collection
|
||||
*
|
||||
* @param string $collectionName
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setCollectionName($collectionName)
|
||||
{
|
||||
$this->collectionName = (string) $collectionName;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the collection
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getCollectionName()
|
||||
{
|
||||
return $this->collectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the class metadata
|
||||
*
|
||||
* @param ClassMetadata $classMetadata
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setClassMetadata(ClassMetadata $classMetadata)
|
||||
{
|
||||
$this->metadata = $classMetadata;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class metadata
|
||||
*
|
||||
* @return ClassMetadata
|
||||
*/
|
||||
public function getClassMetadata()
|
||||
{
|
||||
return $this->metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the object
|
||||
*
|
||||
* @param object $object
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setObject($object)
|
||||
{
|
||||
if (!is_object($object)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('The parameter given to setObject method of %s class is not an object', get_called_class())
|
||||
);
|
||||
}
|
||||
|
||||
$this->object = $object;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the object
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function getObject()
|
||||
{
|
||||
return $this->object;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function extract($value)
|
||||
{
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the collection by value (using the public API)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getCollectionFromObjectByValue()
|
||||
{
|
||||
$object = $this->getObject();
|
||||
$getter = 'get' . ucfirst($this->getCollectionName());
|
||||
|
||||
if (!method_exists($object, $getter)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf(
|
||||
'The getter %s to access collection %s in object %s does not exist',
|
||||
$getter,
|
||||
$this->getCollectionName(),
|
||||
get_class($object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $object->$getter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the collection by reference (not using the public API)
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getCollectionFromObjectByReference()
|
||||
{
|
||||
$object = $this->getObject();
|
||||
$refl = $this->getClassMetadata()->getReflectionClass();
|
||||
$reflProperty = $refl->getProperty($this->getCollectionName());
|
||||
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
return $reflProperty->getValue($object);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is used internally by array_udiff to check if two objects are equal, according to their
|
||||
* SPL hash. This is needed because the native array_diff only compare strings
|
||||
*
|
||||
* @param object $a
|
||||
* @param object $b
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function compareObjects($a, $b)
|
||||
{
|
||||
return strcmp(spl_object_hash($a), spl_object_hash($b));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy remove elements from the original collection. For instance, if the
|
||||
* collection initially contains elements A and B, and that the new collection contains elements B and C, then the
|
||||
* final collection will contain elements B and C (while element A will be asked to be removed).
|
||||
*
|
||||
* This strategy is by reference, this means it won't use public API to add/remove elements to the collection
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class AllowRemoveByReference extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
$collection = $this->getCollectionFromObjectByReference();
|
||||
$collectionArray = $collection->toArray();
|
||||
|
||||
$toAdd = array_udiff($value, $collectionArray, [$this, 'compareObjects']);
|
||||
$toRemove = array_udiff($collectionArray, $value, [$this, 'compareObjects']);
|
||||
|
||||
foreach ($toAdd as $element) {
|
||||
$collection->add($element);
|
||||
}
|
||||
|
||||
foreach ($toRemove as $element) {
|
||||
$collection->removeElement($element);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use LogicException;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy remove elements from the original collection. For instance, if the
|
||||
* collection initially contains elements A and B, and that the new collection contains elements B and C, then the
|
||||
* final collection will contain elements B and C (while element A will be asked to be removed).
|
||||
*
|
||||
* This strategy is by value, this means it will use the public API (in this case, adder and remover)
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class AllowRemoveByValue extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
// AllowRemove strategy need "adder" and "remover"
|
||||
$adder = 'add' . ucfirst($this->collectionName);
|
||||
$remover = 'remove' . ucfirst($this->collectionName);
|
||||
|
||||
if (!method_exists($this->object, $adder) || !method_exists($this->object, $remover)) {
|
||||
throw new LogicException(
|
||||
sprintf(
|
||||
'AllowRemove strategy for DoctrineModule hydrator requires both %s and %s to be defined in %s
|
||||
entity domain code, but one or both seem to be missing',
|
||||
$adder,
|
||||
$remover,
|
||||
get_class($this->object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$collection = $this->getCollectionFromObjectByValue();
|
||||
|
||||
if ($collection instanceof Collection) {
|
||||
$collection = $collection->toArray();
|
||||
}
|
||||
|
||||
$toAdd = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
|
||||
$toRemove = new ArrayCollection(array_udiff($collection, $value, [$this, 'compareObjects']));
|
||||
|
||||
$this->object->$adder($toAdd);
|
||||
$this->object->$remover($toRemove);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy will not remove those elements. At most, it will add new elements. For
|
||||
* instance, if the collection initially contains elements A and B, and that the new collection contains elements B
|
||||
* and C, then the final collection will contain elements A, B and C.
|
||||
*
|
||||
* This strategy is by reference, this means it won't use the public API to remove elements
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DisallowRemoveByReference extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
$collection = $this->getCollectionFromObjectByReference();
|
||||
$collectionArray = $collection->toArray();
|
||||
|
||||
$toAdd = array_udiff($value, $collectionArray, [$this, 'compareObjects']);
|
||||
|
||||
foreach ($toAdd as $element) {
|
||||
$collection->add($element);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use LogicException;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy will not remove those elements. At most, it will add new elements. For
|
||||
* instance, if the collection initially contains elements A and B, and that the new collection contains elements B
|
||||
* and C, then the final collection will contain elements A, B and C.
|
||||
*
|
||||
* This strategy is by value, this means it will use the public API (in this case, remover)
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DisallowRemoveByValue extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
// AllowRemove strategy need "adder"
|
||||
$adder = 'add' . ucfirst($this->collectionName);
|
||||
|
||||
if (!method_exists($this->object, $adder)) {
|
||||
throw new LogicException(
|
||||
sprintf(
|
||||
'DisallowRemove strategy for DoctrineModule hydrator requires %s to
|
||||
be defined in %s entity domain code, but it seems to be missing',
|
||||
$adder,
|
||||
get_class($this->object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$collection = $this->getCollectionFromObjectByValue();
|
||||
|
||||
if ($collection instanceof Collection) {
|
||||
$collection = $collection->toArray();
|
||||
}
|
||||
|
||||
$toAdd = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
|
||||
|
||||
$this->object->$adder($toAdd);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
43
src/DoctrineExpressiveModule/Validator/NoObjectExists.php
Normal file
43
src/DoctrineExpressiveModule/Validator/NoObjectExists.php
Normal file
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
/**
|
||||
* Class that validates if objects does not exist in a given repository with a given list of matched fields
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.4.0
|
||||
* @author Marco Pivetta <ocramius@gmail.com>
|
||||
*/
|
||||
class NoObjectExists extends ObjectExists
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_OBJECT_FOUND = 'objectFound';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_OBJECT_FOUND => "An object matching '%value%' was found",
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (is_object($match)) {
|
||||
$this->error(self::ERROR_OBJECT_FOUND, $value);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
175
src/DoctrineExpressiveModule/Validator/ObjectExists.php
Normal file
175
src/DoctrineExpressiveModule/Validator/ObjectExists.php
Normal file
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Doctrine\Common\Persistence\ObjectRepository;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
/**
|
||||
* Class that validates if objects exist in a given repository with a given list of matched fields
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.4.0
|
||||
* @author Marco Pivetta <ocramius@gmail.com>
|
||||
*/
|
||||
class ObjectExists extends AbstractValidator
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_NO_OBJECT_FOUND = 'noObjectFound';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_NO_OBJECT_FOUND => "No object matching '%value%' was found",
|
||||
];
|
||||
|
||||
/**
|
||||
* ObjectRepository from which to search for entities
|
||||
*
|
||||
* @var ObjectRepository
|
||||
*/
|
||||
protected $objectRepository;
|
||||
|
||||
/**
|
||||
* Fields to be checked
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fields;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options required keys are `object_repository`, which must be an instance of
|
||||
* Doctrine\Common\Persistence\ObjectRepository, and `fields`, with either
|
||||
* a string or an array of strings representing the fields to be matched by the validator.
|
||||
* @throws \Zend\Validator\Exception\InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $options)
|
||||
{
|
||||
if (! isset($options['object_repository']) || ! $options['object_repository'] instanceof ObjectRepository) {
|
||||
if (! array_key_exists('object_repository', $options)) {
|
||||
$provided = 'nothing';
|
||||
} else {
|
||||
if (is_object($options['object_repository'])) {
|
||||
$provided = get_class($options['object_repository']);
|
||||
} else {
|
||||
$provided = getType($options['object_repository']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf(
|
||||
'Option "object_repository" is required and must be an instance of'
|
||||
. ' Doctrine\Common\Persistence\ObjectRepository, %s given',
|
||||
$provided
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$this->objectRepository = $options['object_repository'];
|
||||
|
||||
if (! isset($options['fields'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Key `fields` must be provided and be a field or a list of fields to be used when searching for'
|
||||
. ' existing instances'
|
||||
);
|
||||
}
|
||||
|
||||
$this->fields = $options['fields'];
|
||||
$this->validateFields();
|
||||
|
||||
parent::__construct($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and validates the fields passed to the constructor
|
||||
*
|
||||
* @throws \Zend\Validator\Exception\InvalidArgumentException
|
||||
* @return array
|
||||
*/
|
||||
private function validateFields()
|
||||
{
|
||||
$fields = (array) $this->fields;
|
||||
|
||||
if (empty($fields)) {
|
||||
throw new Exception\InvalidArgumentException('Provided fields list was empty!');
|
||||
}
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
if (! is_string($field)) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf('Provided fields must be strings, %s provided for key %s', gettype($field), $key)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->fields = array_values($fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $value a field value or an array of field values if more fields have been configured to be
|
||||
* matched
|
||||
* @return array
|
||||
* @throws \Zend\Validator\Exception\RuntimeException
|
||||
*/
|
||||
protected function cleanSearchValue($value)
|
||||
{
|
||||
$value = is_object($value) ? [$value] : (array) $value;
|
||||
|
||||
if (ArrayUtils::isHashTable($value)) {
|
||||
$matchedFieldsValues = [];
|
||||
|
||||
foreach ($this->fields as $field) {
|
||||
if (! array_key_exists($field, $value)) {
|
||||
throw new Exception\RuntimeException(
|
||||
sprintf(
|
||||
'Field "%s" was not provided, but was expected since the configured field lists needs'
|
||||
. ' it for validation',
|
||||
$field
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$matchedFieldsValues[$field] = $value[$field];
|
||||
}
|
||||
} else {
|
||||
$matchedFieldsValues = @array_combine($this->fields, $value);
|
||||
|
||||
if (false === $matchedFieldsValues) {
|
||||
throw new Exception\RuntimeException(
|
||||
sprintf(
|
||||
'Provided values count is %s, while expected number of fields to be matched is %s',
|
||||
count($value),
|
||||
count($this->fields)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $matchedFieldsValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (is_object($match)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->error(self::ERROR_NO_OBJECT_FOUND, $value);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Zend\ServiceManager\FactoryInterface;
|
||||
use Interop\Container\ContainerInterface;
|
||||
use Zend\ServiceManager\ServiceLocatorInterface;
|
||||
use Zend\ServiceManager\ServiceLocatorAwareInterface;
|
||||
use DoctrineModule\Validator\Service\Exception\ServiceCreationException;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
/**
|
||||
* Factory for creating NoObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
abstract class AbstractValidatorFactory implements FactoryInterface
|
||||
{
|
||||
const DEFAULT_OBJECTMANAGER_KEY = 'doctrine.entitymanager.orm_default';
|
||||
|
||||
protected $creationOptions = [];
|
||||
|
||||
protected $validatorClass;
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @param array $options
|
||||
* @return \Doctrine\Common\Persistence\ObjectRepository
|
||||
* @throws ServiceCreationException
|
||||
*/
|
||||
protected function getRepository(ContainerInterface $container, array $options)
|
||||
{
|
||||
if (empty($options['target_class'])) {
|
||||
throw new ServiceCreationException(sprintf(
|
||||
"Option 'target_class' is missing when creating validator %s",
|
||||
__CLASS__
|
||||
));
|
||||
}
|
||||
|
||||
$objectManager = $this->getObjectManager($container, $options);
|
||||
$targetClassName = $options['target_class'];
|
||||
$objectRepository = $objectManager->getRepository($targetClassName);
|
||||
|
||||
return $objectRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @param array $options
|
||||
* @return \Doctrine\Common\Persistence\ObjectManager
|
||||
*/
|
||||
protected function getObjectManager(ContainerInterface $container, array $options)
|
||||
{
|
||||
$objectManager = ($options['object_manager']) ?? self::DEFAULT_OBJECTMANAGER_KEY;
|
||||
|
||||
if (is_string($objectManager)) {
|
||||
$objectManager = $container->get($objectManager);
|
||||
}
|
||||
|
||||
return $objectManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $options
|
||||
* @return array
|
||||
*/
|
||||
protected function getFields(array $options)
|
||||
{
|
||||
if (isset($options['fields'])) {
|
||||
return (array) $options['fields'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to merge options array passed to `__invoke`
|
||||
* together with the options array created based on the above
|
||||
* helper methods.
|
||||
*
|
||||
* @param array $previousOptions
|
||||
* @param array $newOptions
|
||||
* @return array
|
||||
*/
|
||||
protected function merge($previousOptions, $newOptions)
|
||||
{
|
||||
return ArrayUtils::merge($previousOptions, $newOptions, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for ZF2 compatiblity.
|
||||
*
|
||||
* In ZF2 the plugin manager instance if passed to `createService`
|
||||
* instead of the global service manager instance (as in ZF3).
|
||||
*
|
||||
* @param ContainerInterface $container
|
||||
* @return ContainerInterface
|
||||
*/
|
||||
protected function container(ContainerInterface $container)
|
||||
{
|
||||
if ($container instanceof ServiceLocatorAwareInterface) {
|
||||
$container = $container->getServiceLocator();
|
||||
}
|
||||
|
||||
return $container;
|
||||
}
|
||||
|
||||
public function createService(ServiceLocatorInterface $serviceLocator)
|
||||
{
|
||||
return $this($serviceLocator, $this->validatorClass, $this->creationOptions);
|
||||
}
|
||||
|
||||
public function setCreationOptions(array $options)
|
||||
{
|
||||
$this->creationOptions = $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service\Exception;
|
||||
|
||||
use RuntimeException as BaseRuntimeException;
|
||||
|
||||
/**
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class ServiceCreationException extends BaseRuntimeException
|
||||
{
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\NoObjectExists;
|
||||
|
||||
/**
|
||||
* Factory for creating NoObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class NoObjectExistsFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = NoObjectExists::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$repository = $this->getRepository($container, $options);
|
||||
|
||||
$validator = new NoObjectExists($this->merge($options, [
|
||||
'object_repository' => $repository,
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\ObjectExists;
|
||||
|
||||
/**
|
||||
* Factory for creating ObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class ObjectExistsFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = ObjectExists::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$repository = $this->getRepository($container, $options);
|
||||
|
||||
$validator = new ObjectExists($this->merge($options, [
|
||||
'object_repository' => $repository,
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\UniqueObject;
|
||||
|
||||
class UniqueObjectFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = UniqueObject::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$useContext = isset($options['use_context']) ? (boolean) $options['use_context'] : false;
|
||||
|
||||
$validator = new UniqueObject($this->merge($options, [
|
||||
'object_manager' => $this->getObjectManager($container, $options),
|
||||
'use_context' => $useContext,
|
||||
'object_repository' => $this->getRepository($container, $options),
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
166
src/DoctrineExpressiveModule/Validator/UniqueObject.php
Normal file
166
src/DoctrineExpressiveModule/Validator/UniqueObject.php
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
/**
|
||||
* Class that validates if objects exist in a given repository with a given list of matched fields only once.
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @author Oskar Bley <oskar@programming-php.net>
|
||||
*/
|
||||
class UniqueObject extends ObjectExists
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_OBJECT_NOT_UNIQUE = 'objectNotUnique';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_OBJECT_NOT_UNIQUE => "There is already another object matching '%value%'",
|
||||
];
|
||||
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $useContext;
|
||||
|
||||
/***
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options required keys are `object_repository`, which must be an instance of
|
||||
* Doctrine\Common\Persistence\ObjectRepository, `object_manager`, which
|
||||
* must be an instance of Doctrine\Common\Persistence\ObjectManager,
|
||||
* and `fields`, with either a string or an array of strings representing
|
||||
* the fields to be matched by the validator.
|
||||
* @throws Exception\InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $options)
|
||||
{
|
||||
parent::__construct($options);
|
||||
|
||||
if (! isset($options['object_manager']) || ! $options['object_manager'] instanceof ObjectManager) {
|
||||
if (! array_key_exists('object_manager', $options)) {
|
||||
$provided = 'nothing';
|
||||
} else {
|
||||
if (is_object($options['object_manager'])) {
|
||||
$provided = get_class($options['object_manager']);
|
||||
} else {
|
||||
$provided = getType($options['object_manager']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf(
|
||||
'Option "object_manager" is required and must be an instance of'
|
||||
. ' Doctrine\Common\Persistence\ObjectManager, %s given',
|
||||
$provided
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$this->objectManager = $options['object_manager'];
|
||||
$this->useContext = isset($options['use_context']) ? (boolean) $options['use_context'] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns false if there is another object with the same field values but other identifiers.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param array $context
|
||||
* @return boolean
|
||||
*/
|
||||
public function isValid($value, $context = null)
|
||||
{
|
||||
if (! $this->useContext) {
|
||||
$context = (array) $value;
|
||||
}
|
||||
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (! is_object($match)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$expectedIdentifiers = $this->getExpectedIdentifiers($context);
|
||||
$foundIdentifiers = $this->getFoundIdentifiers($match);
|
||||
|
||||
if (count(array_diff_assoc($expectedIdentifiers, $foundIdentifiers)) == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->error(self::ERROR_OBJECT_NOT_UNIQUE, $value);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the identifiers from the matched object.
|
||||
*
|
||||
* @param object $match
|
||||
* @return array
|
||||
* @throws Exception\RuntimeException
|
||||
*/
|
||||
protected function getFoundIdentifiers($match)
|
||||
{
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierValues($match);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the identifiers from the context.
|
||||
*
|
||||
* @param array|object $context
|
||||
* @return array
|
||||
* @throws Exception\RuntimeException
|
||||
*/
|
||||
protected function getExpectedIdentifiers($context = null)
|
||||
{
|
||||
if ($context === null) {
|
||||
throw new Exception\RuntimeException(
|
||||
'Expected context to be an array but is null'
|
||||
);
|
||||
}
|
||||
|
||||
$className = $this->objectRepository->getClassName();
|
||||
|
||||
if ($context instanceof $className) {
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierValues($context);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($this->getIdentifiers() as $identifierField) {
|
||||
if (! array_key_exists($identifierField, $context)) {
|
||||
throw new Exception\RuntimeException(\sprintf('Expected context to contain %s', $identifierField));
|
||||
}
|
||||
|
||||
$result[$identifierField] = $context[$identifierField];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array the names of the identifiers
|
||||
*/
|
||||
protected function getIdentifiers()
|
||||
{
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierFieldNames();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user