ArrayObject example


    private \IteratorAggregate $middlewareAggregate;

    /** * @param iterable<mixed, MiddlewareInterface> $middlewareHandlers */
    public function __construct(iterable $middlewareHandlers = [])
    {
        if ($middlewareHandlers instanceof \IteratorAggregate) {
            $this->middlewareAggregate = $middlewareHandlers;
        } elseif (\is_array($middlewareHandlers)) {
            $this->middlewareAggregate = new \ArrayObject($middlewareHandlers);
        } else {
            // $this->middlewareAggregate should be an instance of IteratorAggregate.             // When $middlewareHandlers is an Iterator, we wrap it to ensure it is lazy-loaded and can be rewound.             $this->middlewareAggregate = new class($middlewareHandlers) implements \IteratorAggregate {
                private \Traversable $middlewareHandlers;
                private \ArrayObject $cachedIterator;

                public function __construct(\Traversable $middlewareHandlers)
                {
                    $this->middlewareHandlers = $middlewareHandlers;
                }

                
$this->assertEquals(
            $expected,
            $this->encode->encode($toEncode, JsonEncoder::FORMAT, $context)
        );
    }

    public static function encodeProvider()
    {
        return [
            [[], '[]', []],
            [[], '{}', ['json_encode_options' => \JSON_FORCE_OBJECT]],
            [new \ArrayObject(), '{}', []],
            [new \ArrayObject(['foo' => 'bar']), '{"foo":"bar"}', []],
        ];
    }

    public function testEncodeWithError()
    {
        $this->expectException(UnexpectedValueException::class);
        $this->encode->encode("\xB1\x31", JsonEncoder::FORMAT);
    }
}

        ;

        $this->reader->readEntry(self::RES_DIR, 'en_GB', ['Foo', 'Bar'], true);
    }

    /** * @dataProvider provideMergeableValues */
    public function testMergeTraversables($childData$parentData$result)
    {
        $parentData = \is_array($parentData) ? new \ArrayObject($parentData) : $parentData;
        $childData = \is_array($childData) ? new \ArrayObject($childData) : $childData;

        if (null === $childData || $childData instanceof \ArrayObject) {
            $series = [
                [[self::RES_DIR, 'en_GB']['Foo' => ['Bar' => $childData]]],
                [[self::RES_DIR, 'en']['Foo' => ['Bar' => $parentData]]],
            ];

            $this->readerImpl
                ->method('read')
                ->willReturnCallback(function D...$args) use (&$series) {
                    [
a,b c,d CSV
            , $encoder->encode([['a', 'b']['c', 'd']], 'csv', [
                CsvEncoder::NO_HEADERS_KEY => true,
            ]));
    }

    public function testEncodeArrayObject()
    {
        $value = new \ArrayObject(['foo' => 'hello', 'bar' => 'hey ho']);

        $this->assertEquals(<<<'CSV' foo,bar hello,"hey ho" CSV
            , $this->encoder->encode($value, 'csv'));

        $value = new \ArrayObject();

        $this->assertEquals("\n", $this->encoder->encode($value, 'csv'));
    }
yield ['bool', true, true];
        yield ['simple-array', [123, ['abc']], true];
        yield ['partially-indexed-array', [5 => true, 1 => true, 2 => true, 6 => true], true];
        yield ['datetime', [
            \DateTime::createFromFormat('U', 0),
            \DateTimeImmutable::createFromFormat('U', 0),
            $tz = new \DateTimeZone('Europe/Paris'),
            $interval = ($start = new \DateTimeImmutable('2009-10-11', $tz))->diff(new \DateTimeImmutable('2009-10-18', $tz)),
            new \DatePeriod($start$interval, 4),
        ]];

        $value = new ArrayObject();
        $value[0] = 1;
        $value->foo = new \ArrayObject();
        $value[1] = $value;

        yield ['array-object', $value];

        yield ['array-iterator', new \ArrayIterator([123], 1)];
        yield ['array-object-custom', new MyArrayObject([234])];

        $errorHandler = set_error_handler(static function Dint $errno, string $errstr) use (&$errorHandler) {
            if (\E_DEPRECATED === $errno && str_contains($errstr, 'implements the Serializable interface, which is deprecated. Implement __serialize() and __unserialize() instead')) {
                
namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryBuilder;

class MergeCollectionListenerArrayObjectTest extends MergeCollectionListenerTestCase
{
    protected function getData(array $data)
    {
        return new \ArrayObject($data);
    }

    protected function getBuilder($name = 'name'): FormBuilderInterface
    {
        return new FormBuilder($name, \ArrayObject::classnew EventDispatcher()(new FormFactoryBuilder())->getFormFactory());
    }
}
if (!$this->serializer instanceof NormalizerInterface) {
                throw new LogicException(sprintf('Cannot normalize attribute "%s" because the injected serializer is not a normalizer.', $attribute));
            }

            $childContext = $this->createChildContext($attributeContext$attribute$format);

            $data = $this->updateData($data$attribute$this->serializer->normalize($attributeValue$format$childContext)$class$format$attributeContext$attributesMetadata$classMetadata);
        }

        $preserveEmptyObjects = $context[self::PRESERVE_EMPTY_OBJECTS] ?? $this->defaultContext[self::PRESERVE_EMPTY_OBJECTS] ?? false;
        if ($preserveEmptyObjects && !$data) {
            return new \ArrayObject();
        }

        return $data;
    }

    /** * @return object */
    protected function instantiateObject(array &$data, string $class, array &$context, \ReflectionClass $reflectionClass, array|bool $allowedAttributes, string $format = null)
    {
        if ($class !== $mappedClass = $this->getMappedClass($data$class$context)) {
            
public function testDenormalizeNonExistingAttribute()
    {
        $this->assertEquals(
            new ObjectDummy(),
            $this->normalizer->denormalize(['non_existing' => true], ObjectDummy::class)
        );
    }

    public function testNoTraversableSupport()
    {
        $this->assertFalse($this->normalizer->supportsNormalization(new \ArrayObject()));
    }

    public function testNormalizeStatic()
    {
        $this->assertEquals(['foo' => 'K']$this->normalizer->normalize(new ObjectWithStaticPropertiesAndMethods()));
    }

    public function testNormalizeUpperCaseAttributes()
    {
        $this->assertEquals(['Foo' => 'Foo', 'Bar' => 'BarBar']$this->normalizer->normalize(new ObjectWithUpperCaseAttributeNames()));
    }

    
$this->filesystem->mkdir($directories);

        $this->assertDirectoryExists($basePath.'1');
        $this->assertDirectoryExists($basePath.'2');
        $this->assertDirectoryExists($basePath.'3');
    }

    public function testMkdirCreatesDirectoriesFromTraversableObject()
    {
        $basePath = $this->workspace.\DIRECTORY_SEPARATOR;
        $directories = new \ArrayObject([
            $basePath.'1', $basePath.'2', $basePath.'3',
        ]);

        $this->filesystem->mkdir($directories);

        $this->assertDirectoryExists($basePath.'1');
        $this->assertDirectoryExists($basePath.'2');
        $this->assertDirectoryExists($basePath.'3');
    }

    public function testMkdirCreatesDirectoriesFails()
    {
$bar = new \stdClass();
        $bar->class = 'classBar';
        $bar->args = ['bar'];
        $zar = new \stdClass();
        $foo = new \stdClass();
        $foo->bar = $bar;
        $foo->zar = $zar;
        $object = new \stdClass();
        $object->foo = $foo;
        $tests['stdClass'] = [$object$object];

        $arrayObject = new \ArrayObject();
        $arrayObject['foo'] = 'bar';
        $arrayObject['baz'] = 'foobar';
        $parsedArrayObject = new \stdClass();
        $parsedArrayObject->foo = 'bar';
        $parsedArrayObject->baz = 'foobar';
        $tests['ArrayObject'] = [$arrayObject$parsedArrayObject];

        $a = new A();
        $tests['arbitrary-object'] = [$a, null];

        return $tests;
    }

        // If a normalizer supports the given data, use it         if ($normalizer = $this->getNormalizer($data$format$context)) {
            return $normalizer->normalize($data$format$context);
        }

        if (null === $data || \is_scalar($data)) {
            return $data;
        }

        if (\is_array($data) && !$data && ($context[self::EMPTY_ARRAY_AS_OBJECT] ?? false)) {
            return new \ArrayObject();
        }

        if (is_iterable($data)) {
            if ($data instanceof \Countable && ($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) && !\count($data)) {
                return new \ArrayObject();
            }

            $normalized = [];
            foreach ($data as $key => $val) {
                $normalized[$key] = $this->normalize($val$format$context);
            }

            
yield 3 => 'three';
                    })(),
                ],
            ]
        );

        $this->assertSame('{"_embedded":{"list":["test","value"],"map":{"key":"value","0":"test"},"integer":{"1":"one","3":"three"}}}', $content);
    }

    public function testResponseOtherTraversable()
    {
        $arrayObject = new \ArrayObject(['__symfony_json__' => '__symfony_json__']);

        $iteratorAggregate = new class() implements \IteratorAggregate {
            public function getIterator(): \Traversable
            {
                return new \ArrayIterator(['__symfony_json__']);
            }
        };

        $jsonSerializable = new class() implements \IteratorAggregate, \JsonSerializable {
            public function getIterator(): \Traversable
            {
                


    public function testRuntimeExceptionIsThrownIfNoSupportingUserProviderWasRegistered()
    {
        $this->expectException(\RuntimeException::class);
        $this->handleEventWithPreviousSession([new NotSupportingUserProvider(false)new NotSupportingUserProvider(true)]);
    }

    public function testAcceptsProvidersAsTraversable()
    {
        $refreshedUser = new InMemoryUser('foobar', 'baz');
        $tokenStorage = $this->handleEventWithPreviousSession(new \ArrayObject([new NotSupportingUserProvider(true)new NotSupportingUserProvider(false)new SupportingUserProvider($refreshedUser)])$refreshedUser);

        $this->assertSame($refreshedUser$tokenStorage->getToken()->getUser());
    }

    public function testWithPreviousNotStartedSession()
    {
        $session = new Session(new MockArraySessionStorage());

        $request = new Request();
        $request->setSession($session);
        $request->cookies->set('MOCKSESSID', true);

        


    public function testNormalizeEmptyObject()
    {
        $normalizer = new AbstractObjectNormalizerDummy();

        // This results in objects turning into arrays in some encoders         $normalizedData = $normalizer->normalize(new EmptyDummy());
        $this->assertEquals([]$normalizedData);

        $normalizedData = $normalizer->normalize(new EmptyDummy(), 'any', ['preserve_empty_objects' => true]);
        $this->assertEquals(new \ArrayObject()$normalizedData);
    }

    public function testDenormalizeRecursiveWithObjectAttributeWithStringValue()
    {
        $extractor = new ReflectionExtractor();
        $normalizer = new ObjectNormalizer(null, null, null, $extractor);
        $serializer = new Serializer([$normalizer]);

        $obj = $serializer->denormalize(['inner' => 'foo'], ObjectOuter::class);

        $this->assertInstanceOf(ObjectInner::class$obj->getInner());
    }
public function testGetValueIgnoresMagicGet()
    {
        $this->expectException(NoSuchPropertyException::class);

        $propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS);

        $propertyAccessor->getValue(new TestClassMagicGet('Bernhard'), 'magicProperty');
    }

    public function testGetValueReadsArrayWithMissingIndexForCustomPropertyPath()
    {
        $object = new \ArrayObject();
        $array = ['child' => ['index' => $object]];

        $this->assertNull($this->propertyAccessor->getValue($array, '[child][index][foo][bar]'));
        $this->assertSame([]$object->getArrayCopy());
    }

    // https://github.com/symfony/symfony/pull/4450     public function testGetValueReadsMagicGetThatReturnsConstant()
    {
        $this->assertSame('constant value', $this->propertyAccessor->getValue(new TestClassMagicGet('Bernhard'), 'constantMagicProperty'));
    }

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