/** * {@inheritdoc} */ public function transform($entity) { if (empty($entity)) { return; } return $this->modelManager->getNormalizedIdentifier($entity); }
/** * @param string $baseClass * @param string $propertyFullName * @param ModelManagerInterface $modelManager * * @return array|null */ protected function getParentMetadataForProperty($baseClass, $propertyFullName, ModelManagerInterface $modelManager) { try { return $modelManager->getParentMetadataForProperty($baseClass, $propertyFullName); } catch (MappingException $e) { // no metadata not found. return; } }
/** * @param BundleInterface $bundle * @param string $adminClassBasename * @param string $modelClass * @throws \RuntimeException */ public function generate(BundleInterface $bundle, $adminClassBasename, $modelClass) { $this->class = sprintf('%s\\Admin\\%s', $bundle->getNamespace(), $adminClassBasename); $this->file = sprintf('%s/Admin/%s.php', $bundle->getPath(), str_replace('\\', '/', $adminClassBasename)); $parts = explode('\\', $this->class); if (file_exists($this->file)) { throw new \RuntimeException(sprintf('Unable to generate the admin class "%s". The file "%s" already exists.', $this->class, realpath($this->file))); } $this->renderFile('Admin.php.twig', $this->file, array('classBasename' => array_pop($parts), 'namespace' => implode('\\', $parts), 'fields' => $this->modelManager->getExportFields($modelClass))); }
public function testWithFieldsCascadeTranslationDomain() { $this->admin->setModelManager($this->modelManager); $this->modelManager->expects($this->once())->method('getNewFieldDescriptionInstance')->with('class', 'foo', array('translation_domain' => 'Foobar', 'type' => 'bar'))->will($this->returnValue($this->fieldDescription)); $this->contractor->expects($this->once())->method('getDefaultOptions')->will($this->returnValue(array())); $this->admin->setLabelTranslatorStrategy($this->labelTranslatorStrategy); $this->formMapper->with('foobar', array('translation_domain' => 'Foobar'))->add('foo', 'bar')->end(); $this->assertSame(array('default' => array('collapsed' => false, 'class' => false, 'description' => false, 'translation_domain' => 'Foobar', 'name' => 'default', 'auto_created' => true, 'groups' => array('foobar'), 'tab' => true)), $this->admin->getFormTabs()); $this->assertSame(array('foobar' => array('collapsed' => false, 'class' => false, 'description' => false, 'translation_domain' => 'Foobar', 'name' => 'foobar', 'fields' => array('foo' => 'foo'))), $this->admin->getFormGroups()); }
/** * {@inheritdoc} */ public function reverseTransform($array) { // when the object is created the form return an array // one the object is persisted, the edit $array is the user instance if ($array instanceof $this->className) { return $array; } $instance = new $this->className(); if (!is_array($array)) { return $instance; } return $this->modelManager->modelReverseTransform($this->className, $array); }
/** * @param object $entity * * @return array */ private function getIdentifierValues($entity) { try { return $this->modelManager->getIdentifierValues($entity); } catch (\Exception $e) { throw new \InvalidArgumentException(sprintf('Unable to retrieve the identifier values for entity %s', ClassUtils::getClass($entity)), 0, $e); } }
public function setUp() { $this->contractor = $this->getMock('Sonata\\AdminBundle\\Builder\\FormContractorInterface'); $formFactory = $this->getMock('Symfony\\Component\\Form\\FormFactoryInterface'); $eventDispatcher = $this->getMock('Symfony\\Component\\EventDispatcher\\EventDispatcherInterface'); $formBuilder = new FormBuilder('test', 'stdClass', $eventDispatcher, $formFactory); $this->admin = new CleanAdmin('code', 'class', 'controller'); $this->modelManager = $this->getMock('Sonata\\AdminBundle\\Model\\ModelManagerInterface'); // php 5.3 BC $fieldDescription = $this->getFieldDescriptionMock(); $this->modelManager->expects($this->any())->method('getNewFieldDescriptionInstance')->will($this->returnCallback(function ($class, $name, array $options = array()) use($fieldDescription) { $fieldDescriptionClone = clone $fieldDescription; $fieldDescriptionClone->setName($name); $fieldDescriptionClone->setOptions($options); return $fieldDescriptionClone; })); $this->admin->setModelManager($this->modelManager); $labelTranslatorStrategy = $this->getMock('Sonata\\AdminBundle\\Translator\\LabelTranslatorStrategyInterface'); $this->admin->setLabelTranslatorStrategy($labelTranslatorStrategy); $this->formMapper = new FormMapper($this->contractor, $formBuilder, $this->admin); }
/** * @param FormEvent $event */ public function onBind(FormEvent $event) { $collection = $event->getForm()->getData(); $data = $event->getData(); // looks like there is no way to remove other listeners $event->stopPropagation(); if (!$collection) { $collection = $data; } elseif (count($data) === 0) { $this->modelManager->collectionClear($collection); } else { // merge $data into $collection foreach ($collection as $entity) { if (!$this->modelManager->collectionHasElement($data, $entity)) { $this->modelManager->collectionRemoveElement($collection, $entity); } else { $this->modelManager->collectionRemoveElement($data, $entity); } } foreach ($data as $entity) { $this->modelManager->collectionAddElement($collection, $entity); } } $event->setData($collection); }
/** * {@inheritdoc} */ public function transform($entityOrCollection) { $result = array(); if (!$entityOrCollection) { return $result; } if ($this->multiple) { $isArray = is_array($entityOrCollection); if (!$isArray && substr(get_class($entityOrCollection), -1 * strlen($this->className)) == $this->className) { throw new \InvalidArgumentException('A multiple selection must be passed a collection not a single value. Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true" is set for many-to-many or one-to-many relations.'); } elseif ($isArray || $entityOrCollection instanceof \ArrayAccess) { $collection = $entityOrCollection; } else { throw new \InvalidArgumentException('A multiple selection must be passed a collection not a single value. Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true" is set for many-to-many or one-to-many relations.'); } } else { if (substr(get_class($entityOrCollection), -1 * strlen($this->className)) == $this->className) { $collection = array($entityOrCollection); } elseif ($entityOrCollection instanceof \ArrayAccess) { throw new \InvalidArgumentException('A single selection must be passed a single value not a collection. Make sure that form option "multiple=false" is set for many-to-one relation and "multiple=true" is set for many-to-many or one-to-many relations.'); } else { $collection = array($entityOrCollection); } } if (empty($this->property)) { throw new \RuntimeException('Please define "property" parameter.'); } foreach ($collection as $entity) { $id = current($this->modelManager->getIdentifierValues($entity)); if ($this->toStringCallback !== null) { if (!is_callable($this->toStringCallback)) { throw new \RuntimeException('Callback in "to_string_callback" option doesn`t contain callable function.'); } $label = call_user_func($this->toStringCallback, $entity, $this->property); } else { try { $label = (string) $entity; } catch (\Exception $e) { throw new \RuntimeException(sprintf("Unable to convert the entity %s to String, entity must have a '__toString()' method defined", ClassUtils::getClass($entity)), 0, $e); } } $result[] = $id; $result['_labels'][] = $label; } return $result; }
/** * Initializes the choices and returns them. * * The choices are generated from the entities. If the entities have a * composite identifier, the choices are indexed using ascending integers. * Otherwise the identifiers are used as indices. * * If the entities were passed in the "choices" option, this method * does not have any significant overhead. Otherwise, if a query builder * was passed in the "query" option, this builder is now used to construct * a query which is executed. In the last case, all entities for the * underlying class are fetched from the repository. * * If the option "property" was passed, the property path in that option * is used as option values. Otherwise this method tries to convert * objects to strings using __toString(). * * @param $choices * * @return array An array of choices */ protected function load($choices) { if (is_array($choices) && count($choices) > 0) { $entities = $choices; } elseif ($this->query) { $entities = $this->modelManager->executeQuery($this->query); } else { $entities = $this->modelManager->findBy($this->class); } if (null === $entities) { return array(); } $choices = array(); $this->entities = array(); foreach ($entities as $key => $entity) { if ($this->propertyPath) { // If the property option was given, use it $value = $this->propertyAccessor->getValue($entity, $this->propertyPath); } else { // Otherwise expect a __toString() method in the entity try { $value = (string) $entity; } catch (\Exception $e) { throw new RuntimeException(sprintf('Unable to convert the entity "%s" to string, provide ' . '"property" option or implement "__toString()" method in your entity.', ClassUtils::getClass($entity)), 0, $e); } } if (count($this->identifier) > 1) { // When the identifier consists of multiple field, use // naturally ordered keys to refer to the choices $choices[$key] = $value; $this->entities[$key] = $entity; } else { // When the identifier is a single field, index choices by // entity ID for performance reasons $id = current($this->getIdentifierValues($entity)); $choices[$id] = $value; $this->entities[$id] = $entity; } } return $choices; }
/** * Returns the target object * * @param integer $id * @return object */ public function getObject($id) { return $this->modelManager->findOne($this->getClass(), $id); }
/** * Returns the values of the identifier fields of an entity * * Doctrine must know about this entity, that is, the entity must already * be persisted or added to the identity map before. Otherwise an * exception is thrown. * * @param object $entity The entity for which to get the identifier * @throws FormException If the entity does not exist in Doctrine's * identity map */ public function getIdentifierValues($entity) { return $this->modelManager->getIdentifierValues($entity); }
/** * {@inheritdoc} */ public function guessType($class, $property, ModelManagerInterface $modelManager) { if (!($ret = $modelManager->getParentMetadataForProperty($class, $property, $modelManager))) { return false; } $options = array('field_type' => null, 'field_options' => array(), 'options' => array()); list($metadata, $propertyName, $parentAssociationMappings) = $ret; $options['parent_association_mappings'] = $parentAssociationMappings; // FIXME: Try to implement association using elastica /* if ($metadata->hasAssociation($propertyName)) { $mapping = $metadata->getAssociationMapping($propertyName); switch ($mapping['type']) { case ClassMetadataInfo::ONE_TO_ONE: case ClassMetadataInfo::ONE_TO_MANY: case ClassMetadataInfo::MANY_TO_ONE: case ClassMetadataInfo::MANY_TO_MANY: $options['operator_type'] = 'sonata_type_equal'; $options['operator_options'] = array(); $options['field_type'] = 'entity'; $options['field_options'] = array( 'class' => $mapping['targetEntity'] ); $options['field_name'] = $mapping['fieldName']; $options['mapping_type'] = $mapping['type']; return new TypeGuess('doctrine_orm_model', $options, Guess::HIGH_CONFIDENCE); } }*/ $options['field_name'] = $metadata->fieldMappings[$propertyName]['fieldName']; switch ($metadata->getTypeOfField($propertyName)) { case 'boolean': $options['field_type'] = 'sonata_type_boolean'; $options['field_options'] = array(); return new TypeGuess('sonata_search_elastic_boolean', $options, Guess::HIGH_CONFIDENCE); case 'datetime': case 'vardatetime': case 'datetimetz': return new TypeGuess('sonata_search_elastica_datetime', $options, Guess::HIGH_CONFIDENCE); case 'date': return new TypeGuess('sonata_search_elastica_date', $options, Guess::HIGH_CONFIDENCE); case 'decimal': case 'float': $options['field_type'] = 'number'; return new TypeGuess('sonata_search_elastica_number', $options, Guess::MEDIUM_CONFIDENCE); case 'integer': case 'bigint': case 'smallint': $options['field_type'] = 'number'; return new TypeGuess('sonata_search_elastica_number', $options, Guess::MEDIUM_CONFIDENCE); case 'string': case 'text': $options['field_type'] = 'text'; return new TypeGuess('sonata_search_elastica_string', $options, Guess::MEDIUM_CONFIDENCE); case 'time': return new TypeGuess('sonata_search_elastica_time', $options, Guess::HIGH_CONFIDENCE); default: return new TypeGuess('sonata_search_elastica_string', $options, Guess::LOW_CONFIDENCE); } }