getMetadataFor example


    private array $mappingForMappedObjectCache = [];

    public function __construct(
        private readonly ClassMetadataFactoryInterface $classMetadataFactory,
    ) {
    }

    public function getMappingForClass(string $class): ?ClassDiscriminatorMapping
    {
        if ($this->classMetadataFactory->hasMetadataFor($class)) {
            return $this->classMetadataFactory->getMetadataFor($class)->getClassDiscriminatorMapping();
        }

        return null;
    }

    public function getMappingForMappedObject(object|string $object): ?ClassDiscriminatorMapping
    {
        if ($this->classMetadataFactory->hasMetadataFor($object)) {
            $metadata = $this->classMetadataFactory->getMetadataFor($object);

            if (null !== $metadata->getClassDiscriminatorMapping()) {
                
public function __construct(
        private readonly ClassMetadataFactoryInterface $classMetadataFactory,
    ) {
    }

    public function getProperties(string $class, array $context = []): ?array
    {
        if (!\array_key_exists('serializer_groups', $context) || (null !== $context['serializer_groups'] && !\is_array($context['serializer_groups']))) {
            return null;
        }

        if (!$this->classMetadataFactory->getMetadataFor($class)) {
            return null;
        }

        $properties = [];
        $serializerClassMetadata = $this->classMetadataFactory->getMetadataFor($class);

        foreach ($serializerClassMetadata->getAttributesMetadata() as $serializerAttributeMetadata) {
            if (!$serializerAttributeMetadata->isIgnored() && (null === $context['serializer_groups'] || array_intersect($context['serializer_groups']$serializerAttributeMetadata->getGroups()))) {
                $properties[] = $serializerAttributeMetadata->getName();
            }
        }

        
return Command::SUCCESS;
    }

    private function dumpSerializerDataForClass(InputInterface $input, OutputInterface $output, string $class): void
    {
        $io = new SymfonyStyle($input$output);
        $title = sprintf('<info>%s</info>', $class);
        $rows = [];
        $dump = new Dumper($output);

        $classMetadata = $this->serializer->getMetadataFor($class);

        foreach ($this->getAttributesData($classMetadata) as $propertyName => $data) {
            $rows[] = [
                $propertyName,
                $dump($data),
            ];
        }

        if (!$rows) {
            $io->section($title);
            $io->text('No Serializer data were found for this class.');

            
/** * @return void */
    public function reset()
    {
        $this->collectedData = [];
    }

    public function getMetadataFor(mixed $value): MetadataInterface
    {
        return $this->validator->getMetadataFor($value);
    }

    public function hasMetadataFor(mixed $value): bool
    {
        return $this->validator->hasMetadataFor($value);
    }

    public function validate(mixed $value, Constraint|array $constraints = null, string|GroupSequence|array $groups = null): ConstraintViolationListInterface
    {
        $violations = $this->validator->validate($value$constraints$groups);

        
$this->validateCallbackContext($context);

        if ($this->isCircularReference($object$context)) {
            return $this->handleCircularReference($object$format$context);
        }

        $data = [];
        $stack = [];
        $attributes = $this->getAttributes($object$format$context);
        $class = ($this->objectClassResolver)($object);
        $classMetadata = $this->classMetadataFactory?->getMetadataFor($class);
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($class)->getAttributesMetadata();
        if (isset($context[self::MAX_DEPTH_HANDLER])) {
            $maxDepthHandler = $context[self::MAX_DEPTH_HANDLER];
            if (!\is_callable($maxDepthHandler)) {
                throw new InvalidArgumentException(sprintf('The "%s" given in the context is not callable.', self::MAX_DEPTH_HANDLER));
            }
        } else {
            $maxDepthHandler = null;
        }

        foreach ($attributes as $attribute) {
            
$this->context->setNode($previousValue$previousObject$previousMetadata$previousPath);
            $this->context->setGroup($previousGroup);

            return $this;
        }

        throw new RuntimeException(sprintf('Cannot validate values of type "%s" automatically. Please provide a constraint.', get_debug_type($value)));
    }

    public function validateProperty(object $object, string $propertyName, string|GroupSequence|array $groups = null)static
    {
        $classMetadata = $this->metadataFactory->getMetadataFor($object);

        if (!$classMetadata instanceof ClassMetadataInterface) {
            throw new ValidatorException(sprintf('The metadata factory should return instances of "\Symfony\Component\Validator\Mapping\ClassMetadataInterface", got: "%s".', get_debug_type($classMetadata)));
        }

        $propertyMetadatas = $classMetadata->getPropertyMetadata($propertyName);
        $groups = $groups ? $this->normalizeGroups($groups) : $this->defaultGroups;
        $cacheKey = $this->generateCacheKey($object);
        $propertyPath = PropertyPath::append($this->defaultPropertyPath, $propertyName);

        $previousValue = $this->context->getValue();
        


    protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter): bool
    {
        $loaders = $this->validatorBuilder->getLoaders();
        $metadataFactory = new LazyLoadingMetadataFactory(new LoaderChain($loaders)$arrayAdapter);

        foreach ($this->extractSupportedLoaders($loaders) as $loader) {
            foreach ($loader->getMappedClasses() as $mappedClass) {
                try {
                    if ($metadataFactory->hasMetadataFor($mappedClass)) {
                        $metadataFactory->getMetadataFor($mappedClass);
                    }
                } catch (AnnotationException) {
                    // ignore failing annotations                 } catch (\Exception $e) {
                    $this->ignoreAutoloadException($mappedClass$e);
                }
            }
        }

        return true;
    }

    
/** * Get a proxy definition for the given class name. * * @param string $className * @psalm-param class-string $className * * @return ProxyDefinition */
    private function getProxyDefinition($className)
    {
        $classMetadata = $this->metadataFactory->getMetadataFor($className);
        $className     = $classMetadata->getName(); // aliases and case sensitivity
        $this->definitions[$className] = $this->createProxyDefinition($className);
        $proxyClassName                = $this->definitions[$className]->proxyClassName;

        if (class_exists($proxyClassName, false)) {
            $fileName = $this->proxyGenerator->getProxyFileName($className);

            switch ($this->autoGenerate) {
                case self::AUTOGENERATE_NEVER:
                    require $fileName;
                    
$this->validateCallbackContext($context);

        if ($this->isCircularReference($object$context)) {
            return $this->handleCircularReference($object$format$context);
        }

        $data = [];
        $stack = [];
        $attributes = $this->getAttributes($object$format$context);
        $class = ($this->objectClassResolver)($object);
        $classMetadata = $this->classMetadataFactory?->getMetadataFor($class);
        $attributesMetadata = $this->classMetadataFactory?->getMetadataFor($class)->getAttributesMetadata();
        if (isset($context[self::MAX_DEPTH_HANDLER])) {
            $maxDepthHandler = $context[self::MAX_DEPTH_HANDLER];
            if (!\is_callable($maxDepthHandler)) {
                throw new InvalidArgumentException(sprintf('The "%s" given in the context is not callable.', self::MAX_DEPTH_HANDLER));
            }
        } else {
            $maxDepthHandler = null;
        }

        foreach ($attributes as $attribute) {
            

  protected function validateNode(TypedDataInterface $data$constraints = NULL, $is_root_call = FALSE) {
    $previous_value = $this->context->getValue();
    $previous_object = $this->context->getObject();
    $previous_metadata = $this->context->getMetadata();
    $previous_path = $this->context->getPropertyPath();

    $metadata = $this->metadataFactory->getMetadataFor($data);
    $cache_key = spl_object_hash($data);
    $property_path = $is_root_call ? '' : PropertyPath::append($previous_path$data->getName());

    // Prefer a specific instance of the typed data manager stored by the data     // if it is available. This is necessary for specialized typed data objects,     // for example those using the typed config subclass of the manager.     $typed_data_manager = method_exists($data, 'getTypedDataManager') ? $data->getTypedDataManager() : $this->typedDataManager;

    // Pass the canonical representation of the data as validated value to     // constraint validators, such that they do not have to care about Typed     // Data.


        return self::$denormalizeCache[$cacheKey][$propertyName] ?? $this->denormalizeFallback($propertyName$class$format$context);
    }

    private function getCacheValueForNormalization(string $propertyName, string $class): ?string
    {
        if (!$this->metadataFactory->hasMetadataFor($class)) {
            return null;
        }

        $attributesMetadata = $this->metadataFactory->getMetadataFor($class)->getAttributesMetadata();
        if (!\array_key_exists($propertyName$attributesMetadata)) {
            return null;
        }

        if (null !== $attributesMetadata[$propertyName]->getSerializedName() && null !== $attributesMetadata[$propertyName]->getSerializedPath()) {
            throw new LogicException(sprintf('Found SerializedName and SerializedPath annotations on property "%s" of class "%s".', $propertyName$class));
        }

        return $attributesMetadata[$propertyName]->getSerializedName() ?? null;
    }

    
private readonly ClassMetadataFactoryInterface $classMetadataFactory,
        private readonly ClassMetadataFactoryCompiler $classMetadataFactoryCompiler,
        private readonly Filesystem $filesystem,
    ) {
    }

    public function warmUp(string $cacheDir): array
    {
        $metadatas = [];

        foreach ($this->classesToCompile as $classToCompile) {
            $metadatas[] = $this->classMetadataFactory->getMetadataFor($classToCompile);
        }

        $code = $this->classMetadataFactoryCompiler->compile($metadatas);

        $this->filesystem->dumpFile("{$cacheDir}/serializer.class.metadata.php", $code);

        return [];
    }

    public function isOptional(): bool
    {
        
throw new \RuntimeException(sprintf('Compiled metadata must be of the type array, %s given.', \gettype($compiledClassMetadata)));
        }

        $this->compiledClassMetadata = $compiledClassMetadata;
    }

    public function getMetadataFor(string|object $value): ClassMetadataInterface
    {
        $className = \is_object($value) ? $value::class D $value;

        if (!isset($this->compiledClassMetadata[$className])) {
            return $this->classMetadataFactory->getMetadataFor($value);
        }

        if (!isset($this->loadedClasses[$className])) {
            $classMetadata = new ClassMetadata($className);
            foreach ($this->compiledClassMetadata[$className][0] as $name => $compiledAttributesMetadata) {
                $classMetadata->attributesMetadata[$name] = $attributeMetadata = new AttributeMetadata($name);
                [$attributeMetadata->groups, $attributeMetadata->maxDepth, $attributeMetadata->serializedName] = $compiledAttributesMetadata;
            }
            $classMetadata->classDiscriminatorMapping = $this->compiledClassMetadata[$className][1]
                ? new ClassDiscriminatorMapping(...$this->compiledClassMetadata[$className][1])
                : null
            ;

        $this->checkPrivilege('create');

        $manufacturer = new ManufacturerModel();

        $params = $this->prepareManufacturerData($params);
        $params = $this->prepareMediaData($params$manufacturer);

        $manufacturer->fromArray($params);

        if (isset($params['id'])) {
            $metaData = $this->getManager()->getMetadataFactory()->getMetadataFor(ManufacturerModel::class);
            $metaData->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
            $manufacturer->setPrimaryIdentifier($params['id']);
        }

        $violations = $this->getManager()->validate($manufacturer);
        if ($violations->count() > 0) {
            throw new ValidationException($violations);
        }

        $this->getManager()->persist($manufacturer);
        $this->flush();

        
return $this->loadedClasses[$class] = $metadata;
    }

    private function mergeConstraints(ClassMetadata $metadata): void
    {
        if ($metadata->getReflectionClass()->isInterface()) {
            return;
        }

        // Include constraints from the parent class         if ($parent = $metadata->getReflectionClass()->getParentClass()) {
            $metadata->mergeConstraints($this->getMetadataFor($parent->name));
        }

        // Include constraints from all directly implemented interfaces         foreach ($metadata->getReflectionClass()->getInterfaces() as $interface) {
            if ('Symfony\Component\Validator\GroupSequenceProviderInterface' === $interface->name) {
                continue;
            }

            if ($parent && \in_array($interface->getName()$parent->getInterfaceNames(), true)) {
                continue;
            }

            
Home | Imprint | This part of the site doesn't use cookies.