/**
  * {@inheritdoc}
  */
 public function parse($input)
 {
     $meta = $this->factory->getMetadataForClass($input);
     if (null === $meta) {
         throw new \InvalidArgumentException(sprintf("No metadata found for class %s", $input));
     }
     $params = array();
     //iterate over property metadata
     foreach ($meta->propertyMetadata as $item) {
         if (!is_null($item->type)) {
             $name = isset($item->serializedName) ? $item->serializedName : $item->name;
             $dataType = $this->processDataType(is_string($item->type) ? $item->type : $item->type['name']);
             $params[$name] = array('dataType' => $dataType['normalized'], 'required' => false, 'description' => $this->getDescription($input, $item), 'readonly' => $item->readOnly);
             // if class already parsed, continue, to avoid infinite recursion
             if (in_array($dataType['class'], $this->parsedClasses)) {
                 continue;
             }
             //check for nested classes with JMS metadata
             if ($dataType['class'] && null !== $this->factory->getMetadataForClass($dataType['class'])) {
                 $this->parsedClasses[] = $dataType['class'];
                 $params[$name]['children'] = $this->parse($dataType['class']);
             }
         }
     }
     $this->parsedClasses = array();
     return $params;
 }
 /**
  * Recursively parse all metadata for a class
  *
  * @param  string                    $className Class to get all metadata for
  * @param  array                     $visited   Classes we've already visited to prevent infinite recursion.
  * @param  array                     $groups    Serialization groups to include.
  * @return array                     metadata for given class
  * @throws \InvalidArgumentException
  */
 protected function doParse($className, $visited = array(), array $groups = array())
 {
     $meta = $this->factory->getMetadataForClass($className);
     if (null === $meta) {
         throw new \InvalidArgumentException(sprintf("No metadata found for class %s", $className));
     }
     $exclusionStrategies = array();
     $exclusionStrategies[] = new GroupsExclusionStrategy($groups);
     $params = array();
     // iterate over property metadata
     foreach ($meta->propertyMetadata as $item) {
         if (!is_null($item->type)) {
             $name = $this->namingStrategy->translateName($item);
             $dataType = $this->processDataType($item);
             // apply exclusion strategies
             foreach ($exclusionStrategies as $strategy) {
                 if (true === $strategy->shouldSkipProperty($item, SerializationContext::create())) {
                     continue 2;
                 }
             }
             $params[$name] = array('dataType' => $dataType['normalized'], 'required' => false, 'description' => $this->getDescription($className, $item), 'readonly' => $item->readOnly, 'sinceVersion' => $item->sinceVersion, 'untilVersion' => $item->untilVersion);
             // if class already parsed, continue, to avoid infinite recursion
             if (in_array($dataType['class'], $visited)) {
                 continue;
             }
             // check for nested classes with JMS metadata
             if ($dataType['class'] && null !== $this->factory->getMetadataForClass($dataType['class'])) {
                 $visited[] = $dataType['class'];
                 $params[$name]['children'] = $this->doParse($dataType['class'], $visited, $groups);
             }
         }
     }
     return $params;
 }
 /**
  * @param LifecycleEventArgs $ea
  */
 public function prePersist(LifecycleEventArgs $ea)
 {
     $entity = $ea->getEntity();
     foreach ($this->metadataFactory->getMetadataForClass(get_class($entity))->propertyMetadata as $file) {
         $this->mogrify($entity, $file);
     }
 }
 /**
  * Recursively parse all metadata for a class
  *
  * @param  string                    $className Class to get all metadata for
  * @param  array                     $visited   Classes we've already visited to prevent infinite recursion.
  * @param  array                     $groups    Serialization groups to include.
  * @return array                     metadata for given class
  * @throws \InvalidArgumentException
  */
 protected function doParse($className, $visited = array(), array $groups = array())
 {
     $meta = $this->factory->getMetadataForClass($className);
     if (null === $meta) {
         throw new \InvalidArgumentException(sprintf("No metadata found for class %s", $className));
     }
     $exclusionStrategies = array();
     if ($groups) {
         $exclusionStrategies[] = new GroupsExclusionStrategy($groups);
     }
     $params = array();
     $reflection = new \ReflectionClass($className);
     $defaultProperties = array_map(function ($default) {
         if (is_array($default) && count($default) === 0) {
             return null;
         }
         return $default;
     }, $reflection->getDefaultProperties());
     // iterate over property metadata
     foreach ($meta->propertyMetadata as $item) {
         if (!is_null($item->type)) {
             $name = $this->namingStrategy->translateName($item);
             $dataType = $this->processDataType($item);
             // apply exclusion strategies
             foreach ($exclusionStrategies as $strategy) {
                 if (true === $strategy->shouldSkipProperty($item, SerializationContext::create())) {
                     $params[$name] = null;
                     continue 2;
                 }
             }
             if (!$dataType['inline']) {
                 $params[$name] = array('dataType' => $dataType['normalized'], 'actualType' => $dataType['actualType'], 'subType' => $dataType['class'], 'required' => false, 'default' => isset($defaultProperties[$item->name]) ? $defaultProperties[$item->name] : null, 'description' => $this->getDescription($item), 'readonly' => $item->readOnly, 'sinceVersion' => $item->sinceVersion, 'untilVersion' => $item->untilVersion);
                 if (!is_null($dataType['class']) && false === $dataType['primitive']) {
                     $params[$name]['class'] = $dataType['class'];
                 }
             }
             // we can use type property also for custom handlers, then we don't have here real class name
             if (!class_exists($dataType['class'])) {
                 continue;
             }
             // if class already parsed, continue, to avoid infinite recursion
             if (in_array($dataType['class'], $visited)) {
                 continue;
             }
             // check for nested classes with JMS metadata
             if ($dataType['class'] && false === $dataType['primitive'] && null !== $this->factory->getMetadataForClass($dataType['class'])) {
                 $visited[] = $dataType['class'];
                 $children = $this->doParse($dataType['class'], $visited, $groups);
                 if ($dataType['inline']) {
                     $params = array_merge($params, $children);
                 } else {
                     $params[$name]['children'] = $children;
                 }
             }
         }
     }
     return $params;
 }
Beispiel #5
0
 /**
  * @param object $object
  *
  * @return Relation[]
  */
 public function getRelations($object)
 {
     $relations = array();
     if (null !== ($classMetadata = $this->metadataFactory->getMetadataForClass(get_class($object)))) {
         $relations = array_merge($relations, $classMetadata->getRelations());
     }
     $relations = array_merge($relations, $this->relationProvider->getRelations($object));
     return $relations;
 }
Beispiel #6
0
 /**
  * {@inheritDoc}
  */
 public function getInheritPathForClass($objectOrClass)
 {
     $class = is_object($objectOrClass) ? get_class($objectOrClass) : $objectOrClass;
     if (!is_string($class)) {
         throw new \InvalidArgumentException('Expected object or string.');
     }
     if (null === ($m = $this->metadataFactory->getMetadataForClass($class))) {
         throw new \RuntimeException(sprintf('No characteristics metadata found for class "%s".', $class));
     }
     return $m->inherit;
 }
 /**
  * {@inheritDoc}
  */
 public function setUp()
 {
     self::bootKernel();
     $this->container = static::$kernel->getContainer();
     $this->application = new Application(static::$kernel);
     $this->application->setAutoExit(false);
     $this->application->setCatchExceptions(false);
     $this->metadataFactory = $this->container->get('abc.job.metadata_factory');
     /** @var ClassMetadata $classMetadata */
     $this->classMetadata = $this->metadataFactory->getMetadataForClass(AnnotatedJob::class)->getRootClassMetadata();
 }
 /**
  * {@inheritdoc}
  */
 public function getType($type)
 {
     if (parent::hasType($type)) {
         return parent::getType($type);
     }
     $metadata = $this->metadataFactory->getMetadataForClass($type);
     if (!$metadata) {
         throw new \InvalidArgumentException(sprintf('The type "%s" cannot be loaded by this extension', $type));
     }
     $surrogateType = new SurrogateType($type, $this->fieldRegistry, $metadata);
     return $surrogateType;
 }
 private function getElementName($data, Embed $embed = null)
 {
     $elementName = null;
     if (null !== $embed) {
         $elementName = $embed->getXmlElementName();
     }
     if (null == $elementName && is_object($data)) {
         $metadata = $this->metadataFactory->getMetadataForClass(ClassUtils::getClass($data));
         $elementName = $metadata->xmlRootName;
     }
     return $elementName ?: 'entry';
 }
 /**
  * @param MethodInvocation $method
  * @return mixed
  * @throws \Exception
  * @throws RuntimeException
  * @throws AuthenticationCredentialsNotFoundException
  * @throws AccessDeniedException
  */
 public function intercept(MethodInvocation $method)
 {
     $metadata = $this->metadataFactory->getMetadataForClass($method->reflection->class);
     // no security metadata, proceed
     if (empty($metadata) || !isset($metadata->methodMetadata[$method->reflection->name])) {
         return $method->proceed();
     }
     $metadata = $metadata->methodMetadata[$method->reflection->name];
     if (null === ($token = $this->tokenStorage->getToken())) {
         throw new AuthenticationCredentialsNotFoundException('The TokenStorage was not populated with a Token.');
     }
     if ($this->alwaysAuthenticate || !$token->isAuthenticated()) {
         $token = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($token);
     }
     if (!empty($metadata->roles) && false === $this->accessDecisionManager->decide($token, $metadata->roles, $method)) {
         throw new AccessDeniedException('Token does not have the required roles.');
     }
     if (!empty($metadata->paramPermissions)) {
         foreach ($method->arguments as $index => $argument) {
             if (null !== $argument && isset($metadata->paramPermissions[$index]) && false === $this->accessDecisionManager->decide($token, $metadata->paramPermissions[$index], $argument)) {
                 throw new AccessDeniedException(sprintf('Token does not have the required permissions for method "%s::%s".', $method->reflection->class, $method->reflection->name));
             }
         }
     }
     $runAsToken = null;
     if (!empty($metadata->runAsRoles)) {
         $runAsToken = $this->runAsManager->buildRunAs($token, $method, $metadata->runAsRoles);
         if (null !== $this->logger) {
             $this->logger->debug('Populating TokenStorage with RunAsToken');
         }
         if (null === $runAsToken) {
             throw new RuntimeException('RunAsManager must not return null from buildRunAs().');
         }
         $this->tokenStorage->setToken($runAsToken);
     }
     try {
         $returnValue = $method->proceed();
         if (null !== $runAsToken) {
             $this->restoreOriginalToken($runAsToken);
         }
         if (empty($metadata->returnPermissions)) {
             return $returnValue;
         }
         return $this->afterInvocationManager->decide($this->tokenStorage->getToken(), $method, $metadata->returnPermissions, $returnValue);
     } catch (\Exception $failed) {
         if (null !== $runAsToken) {
             $this->restoreOriginalToken($runAsToken);
         }
         throw $failed;
     }
 }
 public function addRelations($object, ClassMetadataInterface $classMetadata)
 {
     // @todo fix hateoas metadata to include serializer metadata
     $metadata = $this->metadataFactory->getMetadataForClass($classMetadata->name);
     $relations = [];
     foreach ($metadata->propertyMetadata as $propertyName => $propertyMetadata) {
         if ($this->isPropertyDTO($propertyMetadata->type, $object->{$propertyName})) {
             $route = null;
             $relations[] = new Hateoas\Relation($propertyName, $route, new Hateoas\Embedded('expr(object.' . $propertyName . ')'));
         }
     }
     return $relations;
 }
 /**
  * @param JobTypeInterface $jobType
  * @param bool             $loadClassMetadata Whether to load class metadata of the job class
  */
 public function register(JobTypeInterface $jobType, $loadClassMetadata = false)
 {
     if ($loadClassMetadata) {
         /**
          * @var ClassMetadata $classMetadata
          */
         $classMetadata = $this->metadataFactory->getMetadataForClass($jobType->getClass())->getRootClassMetadata();
         $jobType->setParameterTypes($classMetadata->getParameterTypes($jobType->getMethod()));
         $jobType->setParameterTypeOptions($classMetadata->getParameterOptions($jobType->getMethod()));
         $jobType->setReturnType($classMetadata->getReturnType($jobType->getMethod()));
         $jobType->setReturnTypeOptions($classMetadata->getReturnOptions($jobType->getMethod()));
     }
     $jobType->setQueue($this->queueConfig->getQueue($jobType->getName()));
     $this->types[$jobType->getName()] = $jobType;
 }
 /**
  * {@inheritdoc}
  */
 public function shouldSkipProperty(PropertyMetadata $property, Context $context)
 {
     if (!$context instanceof SerializationContext) {
         return false;
     }
     /** @var \Mango\Bundle\JsonApiBundle\Configuration\Metadata\ClassMetadata $metadata */
     $metadata = $this->metadataFactory->getMetadataForClass(get_class($context->getObject()));
     if ($metadata) {
         foreach ($metadata->getRelationships() as $relationship) {
             if ($property->name === $relationship->getName()) {
                 return true;
             }
         }
     }
     return false;
 }
 /**
  * @param              $object
  * @param Relationship $relationship
  * @param Context      $context
  *
  * @return array
  */
 protected function processRelationship($object, Relationship $relationship, Context $context)
 {
     if (null === $object) {
         return null;
     }
     if (!is_object($object)) {
         throw new \RuntimeException(sprintf('Cannot process relationship "%s", because it is not an object but a %s.', $relationship->getName(), gettype($object)));
     }
     /** @var ClassMetadata $relationshipMetadata */
     $relationshipMetadata = $this->hateoasMetadataFactory->getMetadataForClass(get_class($object));
     if (null === $relationshipMetadata) {
         throw new \RuntimeException(sprintf('Metadata for class %s not found. Did you define at as a JSON-API resource?', ClassUtils::getRealClass(get_class($object))));
     }
     $relationshipId = $this->getId($relationshipMetadata, $object);
     // contains the relations type and id
     $relationshipDataArray = $this->getRelationshipDataArray($relationshipMetadata, $relationshipId);
     // only include this relationship if it is needed
     if ($relationship->isIncludedByDefault() && $this->canIncludeRelationship($relationshipMetadata, $relationshipId)) {
         $includedRelationship = $relationshipDataArray;
         // copy data array so we do not override it with our reference
         $this->includedRelationships[] =& $includedRelationship;
         $includedRelationship = $context->accept($object);
         // override previous reference with the serialized data
     }
     // the relationship data can only contain one reference to another resource
     return $relationshipDataArray;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $serializerMetadata = $this->metadataFactory->getMetadataForClass($this->class);
     $manager = $this->registry->getManagerForClass($this->class);
     $doctrineMetadata = $manager->getClassMetadata($this->class);
     foreach ($serializerMetadata->propertyMetadata as $propertyMetadata) {
         $name = $propertyMetadata->name;
         if (in_array($name, $doctrineMetadata->getIdentifierFieldNames()) && !$this->identifierOverwrite) {
             continue;
         }
         if (!in_array($this->group, $propertyMetadata->groups)) {
             continue;
         }
         $type = null;
         $nullable = true;
         if (isset($doctrineMetadata->fieldMappings[$name])) {
             $fieldMetadata = $doctrineMetadata->fieldMappings[$name];
             $type = isset($fieldMetadata['type']) ? $fieldMetadata['type'] : null;
             $nullable = isset($fieldMetadata['nullable']) ? $fieldMetadata['nullable'] : false;
         } else {
             if (isset($doctrineMetadata->associationMappings[$name])) {
                 $associationMetadata = $doctrineMetadata->associationMappings[$name];
                 if (isset($associationMetadata['joinColumns']['nullable'])) {
                     $nullable = $associationMetadata['joinColumns']['nullable'];
                 } else {
                     if (isset($associationMetadata['inverseJoinColumns']['nullable'])) {
                         $nullable = $associationMetadata['inverseJoinColumns']['nullable'];
                     }
                 }
             }
         }
         switch ($type) {
             case 'datetime':
                 $builder->add($name, $type, array('required' => !$nullable, 'widget' => 'single_text'));
                 break;
             case 'boolean':
                 $childBuilder = $builder->create($name, null, array('required' => !$nullable));
                 $childBuilder->addEventSubscriber(new FixCheckboxDataListener());
                 $builder->add($childBuilder);
                 break;
             default:
                 $builder->add($name, null, array('required' => !$nullable));
                 break;
         }
     }
 }
 /**
  * Populates an empty UriContextCollection with UriContexts.
  *
  * @param $uriContextCollection UriContextCollection
  */
 public function build(UriContextCollection $uriContextCollection)
 {
     $subjectObject = $uriContextCollection->getSubjectObject();
     $realClassName = $this->adapter->getRealClassName(get_class($subjectObject));
     $metadata = $this->metadataFactory->getMetadataForClass($realClassName);
     // TODO: This is where we will call $metadata->getUriSchemas() which will return an
     //       array of URI schemas (inc. the "template", TP configs and CR configs).
     $definitions = $metadata->getAutoRouteDefinitions();
     foreach ($definitions as $definition) {
         $locales = $this->adapter->getLocales($subjectObject) ?: array(null);
         foreach ($locales as $locale) {
             // create and add uri context to stack
             $uriContext = $uriContextCollection->createUriContext($definition->getUriSchema(), $definition->getDefaults(), $metadata->getTokenProviders(), $metadata->getConflictResolver(), $locale);
             $uriContextCollection->addUriContext($uriContext);
         }
     }
 }
Beispiel #17
0
 /**
  * @param $class
  * @return ClassMetadata|null
  */
 protected function getMetadata($class)
 {
     if (array_key_exists($class, $this->metadata)) {
         return $this->metadata[$class];
     }
     if (!class_exists($class)) {
         $this->metadata[$class] = null;
         return null;
     }
     /** @var ClassMetadata $classMetadata */
     $classMetadata = $this->metadataFactory->getMetadataForClass($class);
     if (!$classMetadata->isForm()) {
         $this->metadata[$class] = null;
         return null;
     }
     $this->metadata[$class] = $classMetadata;
     return $classMetadata;
 }
 /**
  * @param string $service
  * @return array|null
  */
 private function findServiceConfig($service)
 {
     if (!isset($this->services[$service])) {
         foreach ($this->services as $sc) {
             if ($sc[2] === $service) {
                 return $sc;
             }
         }
         foreach ($this->services as $sc) {
             $metadata = $this->metadataFactory->getMetadataForClass($sc[0]);
             if ($metadata instanceof ActionMetadata && $metadata->isAction && $metadata->alias === $service) {
                 return $sc;
             }
         }
     } else {
         return $this->services[$service];
     }
     return null;
 }
Beispiel #19
0
 public function getRelations($object)
 {
     $classMetadata = $this->metadataFactory->getMetadataForClass(get_class($object));
     if (!$classMetadata instanceof ClassMetadataInterface) {
         return array();
     }
     $relations = array();
     foreach ($classMetadata->getRelationProviders() as $configuration) {
         if (null === ($relationProviderCallable = $this->resolver->getRelationProvider($configuration, $object))) {
             continue;
         }
         if (!is_callable($relationProviderCallable)) {
             throw new \RuntimeException('The returned relation provider is not callable, it should be.');
         }
         $newRelations = call_user_func_array($relationProviderCallable, array($object, $classMetadata));
         if (is_array($newRelations)) {
             $relations = array_merge($relations, $newRelations);
         }
     }
     return $relations;
 }
 /**
  * Check if the given variable is a valid JSON-API resource.
  *
  * @param $data
  *
  * @return bool
  */
 protected function isResource($data)
 {
     if (is_object($data)) {
         /** @var JsonApiClassMetadata $metadata */
         if ($metadata = $this->metadataFactory->getMetadataForClass(get_class($data))) {
             if ($metadata->getResource()) {
                 return true;
             }
         }
     }
     return false;
 }
Beispiel #21
0
 /**
  * Get item type of collection field
  *
  * @param string $className Class name
  * @param string $fieldName Field name
  * @return string|null
  */
 private function getCollectionItemType($className, $fieldName)
 {
     $serializerMetadata = $this->serializerMetadataFactory->getMetadataForClass($className);
     if ($serializerMetadata === null) {
         return null;
     }
     if (!isset($serializerMetadata->propertyMetadata[$fieldName])) {
         return null;
     }
     $type = $serializerMetadata->propertyMetadata[$fieldName]->type;
     return isset($type['name'], $type['params'][0]['name']) && $type['name'] === 'array' ? $type['params'][0]['name'] : null;
 }
 /**
  * {@inheritdoc}
  */
 public function parse($input)
 {
     $className = $input['class'];
     $meta = $this->factory->getMetadataForClass($className);
     if (null === $meta) {
         throw new \InvalidArgumentException(sprintf("No metadata found for class %s", $className));
     }
     $groups = $input['groups'];
     $exclusionStrategies = array();
     if (true) {
         $exclusionStrategies[] = new GroupsExclusionStrategy($groups);
     }
     $params = array();
     //iterate over property metadata
     foreach ($meta->propertyMetadata as $item) {
         if (!is_null($item->type)) {
             $name = isset($item->serializedName) ? $item->serializedName : $item->name;
             $dataType = $this->processDataType($item->type);
             // apply exclusion strategies
             foreach ($exclusionStrategies as $strategy) {
                 if (true === $strategy->shouldSkipProperty($item)) {
                     continue 2;
                 }
             }
             $params[$name] = array('dataType' => $dataType['normalized'], 'required' => false, 'description' => $this->getDescription($item), 'readonly' => $item->readOnly);
             // if class already parsed, continue, to avoid infinite recursion
             if (in_array($dataType['class'], $this->parsedClasses)) {
                 continue;
             }
             //check for nested classes with JMS metadata
             if ($dataType['class'] && null !== $this->factory->getMetadataForClass($dataType['class'])) {
                 $this->parsedClasses[] = $dataType['class'];
                 $params[$name]['children'] = $this->parse(array_merge($dataType, array('groups' => $groups)));
             }
         }
     }
     $this->parsedClasses = array();
     return $params;
 }
 /**
  * Generate OpenGraph through metadata
  *
  * @param object $obj
  * @return OpenGraphInterface
  */
 public function generate($obj)
 {
     if (!is_object($obj)) {
         throw new \InvalidArgumentException('OpenGraphGenerator::generate only accept object argument.');
     }
     $openGraph = new OpenGraph();
     $classType = get_class($obj);
     $metadata = $this->factory->getMetadataForClass($classType);
     if (is_array($metadata->namespaces)) {
         foreach ($metadata->namespaces as $namespace) {
             $openGraph->addNamespace($namespace->prefix, $namespace->uri);
         }
     }
     if (is_array($metadata->nodes)) {
         foreach ($metadata->nodes as $graphNode) {
             if (!empty($graphNode['node']->namespaceUri)) {
                 $openGraph->addNamespace($graphNode['node']->namespace, $graphNode['node']->namespaceUri);
             }
             $openGraph->add($graphNode['node']->namespace, $graphNode['node']->tag, $graphNode['object']->getValue($obj));
         }
     }
     return $openGraph;
 }
Beispiel #24
0
 /**
  * Builds the authtorization mapping for the given $classname.
  *
  * @param string $classname
  */
 private function buildRights($classname)
 {
     $metadatas = $this->metadataFactory->getMetadataForClass($classname);
     $reflection = new \ReflectionClass($classname);
     $this->rights[$classname] = array();
     if (null !== $metadatas) {
         foreach ($metadatas->propertyMetadata as $propertyName => $propertyMetadata) {
             $propertyName = $this->cleanPropertyName($propertyName);
             $this->rights[$classname][$propertyName] = array();
             if (false === $propertyMetadata->readOnly && $reflection->hasMethod($this->buildProperMethodName('set', $propertyName))) {
                 $this->rights[$classname][$propertyName][] = 'replace';
             }
         }
     }
 }
Beispiel #25
0
 /**
  * @param object $object
  */
 protected function addObjectConstraints($object)
 {
     $metadata = $this->metadataFactory->getMetadataForClass(get_class($object));
     if ($metadata !== null) {
         /** @var ClassMetadata $classMetadata */
         $classMetadata = $metadata->getRootClassMetadata();
         foreach ($classMetadata->getPropertiesMetadata() as $propertyMetadata) {
             foreach ($propertyMetadata->getConstraints() as $group => $constraints) {
                 $allOf = Assert::create();
                 foreach ($constraints as $constraint) {
                     $allOf->addRules($constraint->getRules());
                 }
                 $this->addConstraint(Assert::create()->attribute($propertyMetadata->getPropertyName(), $allOf), get_class($object), $group);
             }
         }
     }
 }
 /**
  * rename extracted parameters with JMS metadata naming strategy
  *
  * @param array $parameters
  * @param array $input
  * @return array
  */
 protected function renameJmsParameters($parameters, $input)
 {
     $result = [];
     foreach ($parameters as $name => $value) {
         $className = $input['class'];
         $meta = null;
         try {
             $meta = $this->factory->getMetadataForClass($className);
         } catch (\ReflectionException $e) {
         }
         if (isset($meta->propertyMetadata[$name])) {
             $name = $this->namingStrategy->translateName($meta->propertyMetadata[$name]);
         }
         $result[$name] = $value;
     }
     return $result;
 }
 /**
  * {@inheritdoc}
  */
 public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
 {
     $rs = parent::endVisitingObject($metadata, $data, $type, $context);
     /** @var JsonApiClassMetadata $jsonApiMetadata */
     $jsonApiMetadata = $this->metadataFactory->getMetadataForClass(get_class($data));
     if (null === $jsonApiMetadata) {
         return $rs;
     }
     $idField = $jsonApiMetadata->getIdField();
     if (empty($rs)) {
         $rs = new \ArrayObject();
         if (array() === $this->getRoot()) {
             $this->setRoot(clone $rs);
         }
         return $rs;
     }
     $result = array();
     if (isset($rs['type'])) {
         $result['type'] = $rs['type'];
     }
     if (isset($rs[$idField])) {
         $result['id'] = $rs[$idField];
     }
     $result['attributes'] = array_filter($rs, function ($key) use($idField) {
         switch ($key) {
             case $idField:
             case 'type':
             case 'relationships':
             case 'links':
                 return false;
         }
         return true;
     }, ARRAY_FILTER_USE_KEY);
     if (isset($rs['relationships'])) {
         $result['relationships'] = $rs['relationships'];
     }
     if (isset($rs['links'])) {
         $result['links'] = $rs['links'];
     }
     return $result;
 }
 /**
  * @param LifecycleEventArgs $args
  * @param string             $event
  */
 protected function handleEvent(LifecycleEventArgs $args, $event)
 {
     $object = $args->getObject();
     $om = $args->getObjectManager();
     $class = get_class($object);
     $classMetadata = $this->metadataFactory->getMetadataForClass($class);
     $classMetadataInfo = $om->getClassMetadata($class);
     $identifierFields = $classMetadataInfo->getIdentifierFieldNames();
     foreach ($classMetadata->propertyMetadata as $propertyMetadata) {
         if ($propertyMetadata instanceof PropertyMetadata && count($propertyMetadata->slugFields)) {
             $hasIdentifierFields = count(array_intersect($identifierFields, $propertyMetadata->slugFields)) > 0;
             if ($event == 'prePersist' && $hasIdentifierFields || $event == 'postPersist' && !$hasIdentifierFields) {
                 continue;
                 // generate slug in another event
             }
             $slug = null;
             if ($event == 'preUpdate') {
                 if ($args->hasChangedField($propertyMetadata->name)) {
                     // generate custom slug
                     $slug = $this->slugger->slugify($args->getNewValue($propertyMetadata->name), $propertyMetadata->slugSeparator);
                 } elseif (null !== $propertyMetadata->getValue($object)) {
                     continue;
                     // no changes
                 }
             } else {
                 // generate custom slug
                 $slug = $this->slugger->slugify($propertyMetadata->getValue($object), $propertyMetadata->slugSeparator);
             }
             if (!trim($slug)) {
                 // generate slug from the sluggable fields
                 $slug = $this->generateSlugFromMetadata($object, $propertyMetadata->slugFields, $propertyMetadata->slugSeparator);
             }
             $id = $event == 'preUpdate' && method_exists($object, 'getId') ? $object->getId() : null;
             // generate unique slug
             $slug = $this->generateUniqueSlug($om, $object, $propertyMetadata->name, $slug, $propertyMetadata->slugSeparator, $id);
             $propertyMetadata->setValue($object, $slug);
             $this->recomputeSingleObjectChangeSet($om, $object);
         }
     }
 }
Beispiel #29
0
 /**
  * {@inheritdoc}
  */
 public function getMetadataForClass($className)
 {
     return $this->metadataFactory->getMetadataForClass($className);
 }
Beispiel #30
0
 /**
  * @param \Staffim\DTOBundle\DTO\Model\DTOInterface $modelObject
  * @return \Staffim\DTOBundle\Filterer\Metadata\PropertyMetadata
  */
 private function getClassPropertyMetadata($modelObject)
 {
     return $this->metadataFactory->getMetadataForClass(get_class($modelObject))->getRootClassMetadata()->propertyMetadata;
 }