createPropertyAccessor example


class PropertyAccessDecorator implements ChoiceListFactoryInterface
{
    private ChoiceListFactoryInterface $decoratedFactory;
    private PropertyAccessorInterface $propertyAccessor;

    public function __construct(ChoiceListFactoryInterface $decoratedFactory, PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->decoratedFactory = $decoratedFactory;
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
    }

    /** * Returns the decorated factory. */
    public function getDecoratedFactory(): ChoiceListFactoryInterface
    {
        return $this->decoratedFactory;
    }

    public function createListFromChoices(iterable $choices, mixed $value = null, mixed $filter = null): ChoiceListInterface
    {
class SignatureRememberMeHandlerTest extends TestCase
{
    private SignatureHasher $signatureHasher;
    private InMemoryUserProvider $userProvider;
    private Request $request;
    private RequestStack $requestStack;
    private SignatureRememberMeHandler $handler;

    protected function setUp(): void
    {
        $this->signatureHasher = new SignatureHasher(PropertyAccess::createPropertyAccessor()[], 's3cret');
        $this->userProvider = new InMemoryUserProvider();
        $this->requestStack = new RequestStack();
        $this->request = Request::create('/login');
        $this->requestStack->push($this->request);
        $this->handler = new SignatureRememberMeHandler($this->signatureHasher, $this->userProvider, $this->requestStack, []);
    }

    /** * @group time-sensitive */
    public function testCreateRememberMeCookie()
    {

final class UnwrappingDenormalizer implements DenormalizerInterface, SerializerAwareInterface, CacheableSupportsMethodInterface
{
    use SerializerAwareTrait;

    public const UNWRAP_PATH = 'unwrap_path';

    private readonly PropertyAccessorInterface $propertyAccessor;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
    }

    public function getSupportedTypes(?string $format): array
    {
        return ['*' => false];
    }

    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        $propertyPath = $context[self::UNWRAP_PATH];
        $context['unwrapped'] = true;

        
return null;
        }

        $allowedAttributes = $this->getAllowedAttributes($type$context, true);
        $normalizedData = $this->prepareForDenormalization($data);
        $extraAttributes = [];

        $mappedClass = $this->getMappedClass($normalizedData$type$context);

        $nestedAttributes = $this->getNestedAttributes($mappedClass);
        $nestedData = $originalNestedData = [];
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
        foreach ($nestedAttributes as $property => $serializedPath) {
            if (null === $value = $propertyAccessor->getValue($normalizedData$serializedPath)) {
                continue;
            }
            $convertedProperty = $this->nameConverter ? $this->nameConverter->normalize($property$mappedClass$format$context) : $property;
            $nestedData[$convertedProperty] = $value;
            $originalNestedData[$property] = $value;
            $normalizedData = $this->removeNestedValue($serializedPath->getElements()$normalizedData);
        }

        $normalizedData = array_merge($normalizedData$nestedData);

        
private ?AuthenticationSuccessHandlerInterface $successHandler;
    private ?AuthenticationFailureHandlerInterface $failureHandler;
    private ?TranslatorInterface $translator = null;

    public function __construct(HttpUtils $httpUtils, UserProviderInterface $userProvider, AuthenticationSuccessHandlerInterface $successHandler = null, AuthenticationFailureHandlerInterface $failureHandler = null, array $options = [], PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->options = array_merge(['username_path' => 'username', 'password_path' => 'password']$options);
        $this->httpUtils = $httpUtils;
        $this->successHandler = $successHandler;
        $this->failureHandler = $failureHandler;
        $this->userProvider = $userProvider;
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
    }

    public function supports(Request $request): ?bool
    {
        if (
            !str_contains($request->getRequestFormat() ?? '', 'json')
            && !str_contains($request->getContentTypeFormat() ?? '', 'json')
        ) {
            return false;
        }

        
public function __construct()
    {
        $reflectionExtractor = new ReflectionExtractor();
        $phpDocExtractor = new PhpDocExtractor();
        $this->propertyInfoExtractor = new PropertyInfoExtractor(
            [$reflectionExtractor],
            [$phpDocExtractor$reflectionExtractor],
            [$phpDocExtractor],
            [$reflectionExtractor]
        );
        $this->propertyAccessor = PropertyAccess::createPropertyAccessor();
    }

    /** * Removes all extensions from an object (recursive) * Only works if the properties are public or accessible by getter */
    public function removeExtensions($object): void
    {
        if (\is_scalar($object)) {
            return;
        }

        

final class UnwrappingDenormalizer implements DenormalizerInterface, SerializerAwareInterface, CacheableSupportsMethodInterface
{
    use SerializerAwareTrait;

    public const UNWRAP_PATH = 'unwrap_path';

    private readonly PropertyAccessorInterface $propertyAccessor;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
    }

    public function getSupportedTypes(?string $format): array
    {
        return ['*' => false];
    }

    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        $propertyPath = $context[self::UNWRAP_PATH];
        $context['unwrapped'] = true;

        

class PropertyPathAccessor implements DataAccessorInterface
{
    private PropertyAccessorInterface $propertyAccessor;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
    }

    public function getValue(object|array $data, FormInterface $form): mixed
    {
        if (null === $propertyPath = $form->getPropertyPath()) {
            throw new AccessException('Unable to read from the given form data as no property path is defined.');
        }

        return $this->getPropertyValue($data$propertyPath);
    }

    

class CoreExtension extends AbstractExtension
{
    private PropertyAccessorInterface $propertyAccessor;
    private ChoiceListFactoryInterface $choiceListFactory;
    private ?TranslatorInterface $translator;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null, ChoiceListFactoryInterface $choiceListFactory = null, TranslatorInterface $translator = null)
    {
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
        $this->choiceListFactory = $choiceListFactory ?? new CachingFactoryDecorator(new PropertyAccessDecorator(new DefaultChoiceListFactory()$this->propertyAccessor));
        $this->translator = $translator;
    }

    protected function loadTypes(): array
    {
        return [
            new Type\FormType($this->propertyAccessor),
            new Type\BirthdayType(),
            new Type\CheckboxType(),
            new Type\ChoiceType($this->choiceListFactory, $this->translator),
            

        if (false === $pos = strpos($path, '[')) {
            return $parameters->all()[$path] ?? null;
        }

        $root = substr($path, 0, $pos);

        if (null === $value = $parameters->all()[$root] ?? null) {
            return null;
        }

        self::$propertyAccessor ??= PropertyAccess::createPropertyAccessor();

        try {
            return self::$propertyAccessor->getValue($valuesubstr($path$pos));
        } catch (AccessException) {
            return null;
        }
    }

    /** * Returns a request "parameter" value. * * Paths like foo[bar] will be evaluated to find deeper items in nested data structures. * * @throws InvalidArgumentException when the given path is malformed */
if (null !== $path) {
                $violationBuilder->setParameter('{{ compared_value_path }}', $path);
            }

            $violationBuilder->addViolation();
        }
    }

    private function getPropertyAccessor(): PropertyAccessorInterface
    {
        return $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor();
    }

    /** * Compares the two given values to find if their relationship is valid. */
    abstract protected function compareValues(mixed $value1, mixed $value2): bool;

    /** * Returns the error code used if the comparison fails. */
    protected function getErrorCode(): ?string
    {
return null;
        }

        $allowedAttributes = $this->getAllowedAttributes($type$context, true);
        $normalizedData = $this->prepareForDenormalization($data);
        $extraAttributes = [];

        $mappedClass = $this->getMappedClass($normalizedData$type$context);

        $nestedAttributes = $this->getNestedAttributes($mappedClass);
        $nestedData = $originalNestedData = [];
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
        foreach ($nestedAttributes as $property => $serializedPath) {
            if (null === $value = $propertyAccessor->getValue($normalizedData$serializedPath)) {
                continue;
            }
            $convertedProperty = $this->nameConverter ? $this->nameConverter->normalize($property$mappedClass$format$context) : $property;
            $nestedData[$convertedProperty] = $value;
            $originalNestedData[$property] = $value;
            $normalizedData = $this->removeNestedValue($serializedPath->getElements()$normalizedData);
        }

        $normalizedData = array_merge($normalizedData$nestedData);

        
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Contracts\Translation\TranslatableInterface;

class FormType extends BaseType
{
    private DataMapper $dataMapper;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->dataMapper = new DataMapper(new ChainAccessor([
            new CallbackAccessor(),
            new PropertyPathAccessor($propertyAccessor ?? PropertyAccess::createPropertyAccessor()),
        ]));
    }

    /** * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder$options);

        $isDataOptionSet = \array_key_exists('data', $options);

        
private readonly \Closure $objectClassResolver;

    public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = [])
    {
        if (!class_exists(PropertyAccess::class)) {
            throw new LogicException('The ObjectNormalizer class requires the "PropertyAccess" component. Try running "composer require symfony/property-access".');
        }

        parent::__construct($classMetadataFactory$nameConverter$propertyTypeExtractor$classDiscriminatorResolver$objectClassResolver$defaultContext);

        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();

        $this->objectClassResolver = ($objectClassResolver ?? static fn ($class) => \is_object($class) ? $class::class D $class)(...);
    }

    public function getSupportedTypes(?string $format): array
    {
        return ['object' => __CLASS__ === static::class || $this->hasCacheableSupportsMethod()];
    }

    /** * @deprecated since Symfony 6.3, use "getSupportedTypes()" instead */


        try {
            return $this->getPropertyAccessor()->getValue($object$propertyPath);
        } catch (NoSuchPropertyException $e) {
            throw new ConstraintDefinitionException(sprintf('Invalid property path "%s" provided to "%s" constraint: ', $propertyPathget_debug_type($constraint)).$e->getMessage(), 0, $e);
        }
    }

    private function getPropertyAccessor(): PropertyAccessorInterface
    {
        return $this->propertyAccessor ??= PropertyAccess::createPropertyAccessor();
    }

    private function isParsableDatetimeString(mixed $boundary): bool
    {
        if (null === $boundary) {
            return true;
        }

        if (!\is_string($boundary)) {
            return false;
        }

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