123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493 |
- <?php
- /*
- * This file is part of the Sonata package.
- *
- * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- namespace Sonata\DoctrineORMAdminBundle\Model;
- use Sonata\DoctrineORMAdminBundle\Admin\FieldDescription;
- use Sonata\AdminBundle\Model\ModelManagerInterface;
- use Sonata\AdminBundle\Admin\FieldDescriptionInterface;
- use Sonata\AdminBundle\Datagrid\DatagridInterface;
- use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
- use Sonata\AdminBundle\Exception\ModelManagerException;
- use Doctrine\ORM\QueryBuilder;
- use Symfony\Component\Form\Exception\PropertyAccessDeniedException;
- use Symfony\Bridge\Doctrine\RegistryInterface;
- use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
- class ModelManager implements ModelManagerInterface
- {
- protected $registry;
- /**
- *
- * @param \Doctrine\ORM\EntityManager $entityManager
- */
- public function __construct(\Symfony\Bridge\Doctrine\RegistryInterface $registry)
- {
- $this->registry = $registry;
- }
- /**
- * Returns the related model's metadata
- *
- * @abstract
- * @param string $name
- * @return \Doctrine\ORM\Mapping\ClassMetadataInfo
- */
- public function getMetadata($class)
- {
- return $this->getEntityManager($class)->getMetadataFactory()->getMetadataFor($class);
- }
- /**
- * Returns true is the model has some metadata
- *
- * @param $class
- * @return boolean
- */
- public function hasMetadata($class)
- {
- return $this->getEntityManager($class)->getMetadataFactory()->hasMetadataFor($class);
- }
- /**
- * Returns a new FieldDescription
- *
- * @throws \RunTimeException
- * @param $class
- * @param $name
- * @param array $options
- * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
- */
- public function getNewFieldDescriptionInstance($class, $name, array $options = array())
- {
- if (!is_string($name)) {
- throw new \RunTimeException('The name argument must be a string');
- }
- $metadata = $this->getMetadata($class);
- $fieldDescription = new FieldDescription;
- $fieldDescription->setName($name);
- $fieldDescription->setOptions($options);
- if (isset($metadata->associationMappings[$name])) {
- $fieldDescription->setAssociationMapping($metadata->associationMappings[$name]);
- }
- if (isset($metadata->fieldMappings[$name])) {
- $fieldDescription->setFieldMapping($metadata->fieldMappings[$name]);
- }
- return $fieldDescription;
- }
- public function create($object)
- {
- try {
- $entityManager = $this->getEntityManager($object);
- $entityManager->persist($object);
- $entityManager->flush();
- } catch ( \PDOException $e ) {
- throw new ModelManagerException('', 0, $e);
- }
- }
- public function update($object)
- {
- try {
- $entityManager = $this->getEntityManager($object);
- $entityManager->persist($object);
- $entityManager->flush();
- } catch ( \PDOException $e ) {
- throw new ModelManagerException('', 0, $e);
- }
- }
- public function delete($object)
- {
- try {
- $entityManager = $this->getEntityManager($object);
- $entityManager->remove($object);
- $entityManager->flush();
- } catch ( \PDOException $e ) {
- throw new ModelManagerException('', 0, $e);
- }
- }
- /**
- * Find one object from the given class repository.
- *
- * @param string $class Class name
- * @param string|int $id Identifier. Can be a string with several IDs concatenated, separated by '-'.
- * @return Object
- */
- public function find($class, $id)
- {
- $values = array_combine($this->getIdentifierFieldNames($class), explode('-', $id));
- return $this->getEntityManager($class)->getRepository($class)->find($values);
- }
- /**
- * @param $class
- * @param array $criteria
- * @return array
- */
- public function findBy($class, array $criteria = array())
- {
- return $this->getEntityManager($class)->getRepository($class)->findBy($criteria);
- }
- /**
- * @param $class
- * @param array $criteria
- * @return array
- */
- public function findOneBy($class, array $criteria = array())
- {
- return $this->getEntityManager($class)->getRepository($class)->findOneBy($criteria);
- }
- /**
- * @return \Doctrine\ORM\EntityManager
- */
- public function getEntityManager($class)
- {
- if (is_object($class)) {
- $class = get_class($class);
- }
- return $this->registry->getEntityManagerForClass($class);
- }
- /**
- * @param string $parentAssociationMapping
- * @param string $class
- * @return \Sonata\AdminBundle\Admin\ORM\FieldDescription
- */
- public function getParentFieldDescription($parentAssociationMapping, $class)
- {
- $fieldName = $parentAssociationMapping['fieldName'];
- $metadata = $this->getMetadata($class);
- $associatingMapping = $metadata->associationMappings[$parentAssociationMapping];
- $fieldDescription = $this->getNewFieldDescriptionInstance($class, $fieldName);
- $fieldDescription->setName($parentAssociationMapping);
- $fieldDescription->setAssociationMapping($associatingMapping);
- return $fieldDescription;
- }
- /**
- * @param $class
- * @param string $alias
- * @return \Doctrine\ORM\QueryBuilder
- */
- public function createQuery($class, $alias = 'o')
- {
- $repository = $this->getEntityManager($class)->getRepository($class);
- return new ProxyQuery($repository->createQueryBuilder($alias));
- }
- /**
- * @param $query
- * @return mixed
- */
- public function executeQuery($query)
- {
- if ($query instanceof QueryBuilder) {
- return $query->getQuery()->execute();
- }
- return $query->execute();
- }
- /**
- * @param string $class
- * @return string
- */
- public function getModelIdentifier($class)
- {
- return $this->getMetadata($class)->identifier;
- }
- /**
- * @throws \RuntimeException
- * @param $entity
- * @return
- */
- public function getIdentifierValues($entity)
- {
- $entityManager = $this->getEntityManager($entity);
- if (!$entityManager->getUnitOfWork()->isInIdentityMap($entity)) {
- throw new \RuntimeException('Entities passed to the choice field must be managed');
- }
- return $entityManager->getUnitOfWork()->getEntityIdentifier($entity);
- }
- /**
- * @param $class
- * @return mixed
- */
- public function getIdentifierFieldNames($class)
- {
- return $this->getMetadata($class)->getIdentifierFieldNames();
- }
- /**
- * @throws \RunTimeException
- * @param $entity
- * @return null|string
- */
- public function getNormalizedIdentifier($entity)
- {
- if (is_scalar($entity)) {
- throw new \RunTimeException('Invalid argument, object or null required');
- }
- // the entities is not managed
- if (!$entity || !$this->getEntityManager($entity)->getUnitOfWork()->isInIdentityMap($entity)) {
- return null;
- }
- $values = $this->getIdentifierValues($entity);
- return implode('-', $values);
- }
- /**
- * @param $class
- * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy
- * @param array $idx
- * @return void
- */
- public function addIdentifiersToQuery($class, ProxyQueryInterface $queryProxy, array $idx)
- {
- $fieldNames = $this->getIdentifierFieldNames($class);
- $qb = $queryProxy->getQueryBuilder();
- $prefix = uniqid();
- $sqls = array();
- foreach ($idx as $pos => $id) {
- $ids = explode('-', $id);
- $ands = array();
- foreach ($fieldNames as $posName => $name) {
- $parameterName = sprintf('field_%s_%s_%d', $prefix, $name, $pos);
- $ands[] = sprintf('%s.%s = :%s', $qb->getRootAlias(), $name, $parameterName);
- $qb->setParameter($parameterName, $ids[$posName]);
- }
- $sqls[] = implode(' AND ', $ands);
- }
- $qb->andWhere(sprintf('( %s )', implode(' OR ', $sqls)));
- }
- /**
- * Deletes a set of $class identified by the provided $idx array
- *
- * @param $class
- * @param \Sonata\AdminBundle\Datagrid\ProxyQueryInterface $queryProxy
- * @return void
- */
- public function batchDelete($class, ProxyQueryInterface $queryProxy)
- {
- try {
- $entityManager = $this->getEntityManager($class);
- $i = 0;
- foreach ($queryProxy->getQuery()->iterate() as $pos => $object) {
- $entityManager->remove($object[0]);
- if ((++$i % 20) == 0) {
- $entityManager->flush();
- $entityManager->clear();
- }
- }
- $entityManager->flush();
- $entityManager->clear();
- } catch ( \PDOException $e ) {
- throw new ModelManagerException('', 0, $e);
- }
- }
- /**
- * Returns a new model instance
- * @param string $class
- * @return
- */
- public function getModelInstance($class)
- {
- return new $class;
- }
- /**
- * Returns the parameters used in the columns header
- *
- * @param \Sonata\AdminBundle\Admin\FieldDescriptionInterface $fieldDescription
- * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
- * @return array
- */
- public function getSortParameters(FieldDescriptionInterface $fieldDescription, DatagridInterface $datagrid)
- {
- $values = $datagrid->getValues();
- if ($fieldDescription->getOption('sortable') == $values['_sort_by']) {
- if ($values['_sort_order'] == 'ASC') {
- $values['_sort_order'] = 'DESC';
- } else {
- $values['_sort_order'] = 'ASC';
- }
- } else {
- $values['_sort_order'] = 'ASC';
- $values['_sort_by'] = $fieldDescription->getOption('sortable');
- }
- return array('filter' => $values);
- }
- /**
- * @param \Sonata\AdminBundle\Datagrid\DatagridInterface $datagrid
- * @param $page
- * @return array
- */
- public function getPaginationParameters(DatagridInterface $datagrid, $page)
- {
- $values = $datagrid->getValues();
- $values['_page'] = $page;
- return array('filter' => $values);
- }
- /**
- * @param sring $class
- * @return array
- */
- public function getDefaultSortValues($class)
- {
- return array(
- '_sort_order' => 'ASC',
- '_sort_by' => implode(',', $this->getModelIdentifier($class)),
- '_page' => 1
- );
- }
- /**
- * @param string $class
- * @param object $instance
- * @return mixed
- */
- public function modelTransform($class, $instance)
- {
- return $instance;
- }
- /**
- * @param string $class
- * @param array $array
- * @return object
- */
- public function modelReverseTransform($class, array $array = array())
- {
- $instance = $this->getModelInstance($class);
- $metadata = $this->getMetadata($class);
- $reflClass = $metadata->reflClass;
- foreach ($array as $name => $value) {
- $reflection_property = false;
- // property or association ?
- if (array_key_exists($name, $metadata->fieldMappings)) {
- $property = $metadata->fieldMappings[$name]['fieldName'];
- $reflection_property = $metadata->reflFields[$name];
- } else if (array_key_exists($name, $metadata->associationMappings)) {
- $property = $metadata->associationMappings[$name]['fieldName'];
- } else {
- $property = $name;
- }
- $setter = 'set'.$this->camelize($name);
- if ($reflClass->hasMethod($setter)) {
- if (!$reflClass->getMethod($setter)->isPublic()) {
- throw new PropertyAccessDeniedException(sprintf('Method "%s()" is not public in class "%s"', $setter, $reflClass->getName()));
- }
- $instance->$setter($value);
- } else if ($reflClass->hasMethod('__set')) {
- // needed to support magic method __set
- $instance->$property = $value;
- } else if ($reflClass->hasProperty($property)) {
- if (!$reflClass->getProperty($property)->isPublic()) {
- throw new PropertyAccessDeniedException(sprintf('Property "%s" is not public in class "%s". Maybe you should create the method "set%s()"?', $property, $reflClass->getName(), ucfirst($property)));
- }
- $instance->$property = $value;
- } else if ($reflection_property) {
- $reflection_property->setValue($instance, $value);
- }
- }
- return $instance;
- }
- /**
- * method taken from PropertyPath
- *
- * @param $property
- * @return mixed
- */
- protected function camelize($property)
- {
- return preg_replace(array('/(^|_)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $property);
- }
- /**
- * @param string $class
- * @return \Doctrine\Common\Collections\ArrayCollection
- */
- public function getModelCollectionInstance($class)
- {
- return new \Doctrine\Common\Collections\ArrayCollection();
- }
- public function collectionClear(&$collection)
- {
- return $collection->clear();
- }
- public function collectionHasElement(&$collection, &$element)
- {
- return $collection->contains($element);
- }
- public function collectionAddElement(&$collection, &$element)
- {
- return $collection->add($element);
- }
- public function collectionRemoveElement(&$collection, &$element)
- {
- return $collection->removeElement($element);
- }
- }
|