-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathPropertyAccessorTest.php
1108 lines (868 loc) · 45.5 KB
/
PropertyAccessorTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\PropertyAccess\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyAccess\Tests\Fixtures\AsymmetricVisibility;
use Symfony\Component\PropertyAccess\Tests\Fixtures\ExtendedUninitializedProperty;
use Symfony\Component\PropertyAccess\Tests\Fixtures\ReturnTyped;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestAdderRemoverInvalidArgumentLength;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestAdderRemoverInvalidMethods;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClass;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassIsWritable;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassMagicCall;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassMagicGet;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassSetValue;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassTypedProperty;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestClassTypeErrorInsideCall;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestPublicPropertyDynamicallyCreated;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestPublicPropertyGetterOnObject;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestPublicPropertyGetterOnObjectMagicGet;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TestSingularAndPluralProps;
use Symfony\Component\PropertyAccess\Tests\Fixtures\Ticket5775Object;
use Symfony\Component\PropertyAccess\Tests\Fixtures\TypeHinted;
use Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedObjectProperty;
use Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty;
use Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedProperty;
use Symfony\Component\VarExporter\ProxyHelper;
class PropertyAccessorTest extends TestCase
{
private PropertyAccessorInterface $propertyAccessor;
protected function setUp(): void
{
$this->propertyAccessor = new PropertyAccessor();
}
public static function getPathsWithMissingProperty()
{
return [
[(object) ['firstName' => 'Bernhard'], 'lastName'],
[(object) ['property' => (object) ['firstName' => 'Bernhard']], 'property.lastName'],
[['index' => (object) ['firstName' => 'Bernhard']], '[index].lastName'],
[new TestClass('Bernhard'), 'protectedProperty'],
[new TestClass('Bernhard'), 'privateProperty'],
[new TestClass('Bernhard'), 'protectedAccessor'],
[new TestClass('Bernhard'), 'protectedIsAccessor'],
[new TestClass('Bernhard'), 'protectedHasAccessor'],
[new TestClass('Bernhard'), 'privateAccessor'],
[new TestClass('Bernhard'), 'privateIsAccessor'],
[new TestClass('Bernhard'), 'privateHasAccessor'],
// Properties are not camelized
[new TestClass('Bernhard'), 'public_property'],
];
}
public static function getPathsWithMissingIndex()
{
return [
[['firstName' => 'Bernhard'], '[lastName]'],
[[], '[index][lastName]'],
[['index' => []], '[index][lastName]'],
[['index' => ['firstName' => 'Bernhard']], '[index][lastName]'],
[(object) ['property' => ['firstName' => 'Bernhard']], 'property[lastName]'],
];
}
/**
* @dataProvider getValidReadPropertyPaths
*/
public function testGetValue(array|object $objectOrArray, string $path, ?string $value)
{
$this->assertSame($value, $this->propertyAccessor->getValue($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingProperty
*/
public function testGetValueThrowsExceptionIfPropertyNotFound(array|object $objectOrArray, string $path)
{
$this->expectException(NoSuchPropertyException::class);
$this->propertyAccessor->getValue($objectOrArray, $path);
}
/**
* @dataProvider getPathsWithMissingProperty
*/
public function testGetValueReturnsNullIfPropertyNotFoundAndExceptionIsDisabled(array|object $objectOrArray, string $path)
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_GET | PropertyAccessor::MAGIC_SET, PropertyAccessor::DO_NOT_THROW);
$this->assertNull($this->propertyAccessor->getValue($objectOrArray, $path), $path);
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testGetValueThrowsNoExceptionIfIndexNotFound(array|object $objectOrArray, string $path)
{
$this->assertNull($this->propertyAccessor->getValue($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testGetValueThrowsExceptionIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path)
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
$this->expectException(NoSuchIndexException::class);
$this->propertyAccessor->getValue($objectOrArray, $path);
}
public function testGetValueThrowsExceptionIfUninitializedProperty()
{
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The property "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedProperty::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.');
$this->propertyAccessor->getValue(new UninitializedProperty(), 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetter()
{
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The method "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?');
$this->propertyAccessor->getValue(new UninitializedPrivateProperty(), 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousClass()
{
$object = new class {
private $uninitialized;
public function getUninitialized(): array
{
return $this->uninitialized;
}
};
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The method "class@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?');
$this->propertyAccessor->getValue($object, 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedNotNullablePropertyWithGetterOfAnonymousClass()
{
$object = new class {
private string $uninitialized;
public function getUninitialized(): string
{
return $this->uninitialized;
}
};
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The property "class@anonymous::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.');
$this->propertyAccessor->getValue($object, 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedPropertyOfAnonymousClass()
{
$object = new class {
public string $uninitialized;
};
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The property "class@anonymous::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.');
$this->propertyAccessor->getValue($object, 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedNotNullableOfParentClass()
{
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The property "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedProperty::$uninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.');
$this->propertyAccessor->getValue(new ExtendedUninitializedProperty(), 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedNotNullablePropertyWithGetterOfParentClass()
{
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The property "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedProperty::$privateUninitialized" is not readable because it is typed "string". You should initialize it or declare a default value instead.');
$this->propertyAccessor->getValue(new ExtendedUninitializedProperty(), 'privateUninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousStdClass()
{
$object = new class extends \stdClass {
private $uninitialized;
public function getUninitialized(): array
{
return $this->uninitialized;
}
};
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The method "stdClass@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?');
$this->propertyAccessor->getValue($object, 'uninitialized');
}
public function testGetValueThrowsExceptionIfUninitializedPropertyWithGetterOfAnonymousChildClass()
{
$object = new class extends UninitializedPrivateProperty {
};
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The method "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedPrivateProperty@anonymous::getUninitialized()" returned "null", but expected type "array". Did you forget to initialize a property or to make the return type nullable using "?array"?');
$this->propertyAccessor->getValue($object, 'uninitialized');
}
public function testGetValueThrowsExceptionIfNotArrayAccess()
{
$this->expectException(NoSuchIndexException::class);
$this->propertyAccessor->getValue(new \stdClass(), '[index]');
}
public function testGetValueReadsMagicGet()
{
$this->assertSame('Bernhard', $this->propertyAccessor->getValue(new TestClassMagicGet('Bernhard'), 'magicProperty'));
}
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'));
}
public function testGetValueNotModifyObject()
{
$object = new \stdClass();
$object->firstName = ['Bernhard'];
$this->assertNull($this->propertyAccessor->getValue($object, 'firstName[1]'));
$this->assertSame(['Bernhard'], $object->firstName);
}
public function testGetValueNotModifyObjectException()
{
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
$object = new \stdClass();
$object->firstName = ['Bernhard'];
try {
$propertyAccessor->getValue($object, 'firstName[1]');
} catch (NoSuchIndexException $e) {
}
$this->assertSame(['Bernhard'], $object->firstName);
}
public function testGetValueDoesNotReadMagicCallByDefault()
{
$this->expectException(NoSuchPropertyException::class);
$this->propertyAccessor->getValue(new TestClassMagicCall('Bernhard'), 'magicCallProperty');
}
public function testGetValueReadsMagicCallIfEnabled()
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_GET | PropertyAccessor::MAGIC_SET | PropertyAccessor::MAGIC_CALL);
$this->assertSame('Bernhard', $this->propertyAccessor->getValue(new TestClassMagicCall('Bernhard'), 'magicCallProperty'));
}
// https://github.com/symfony/symfony/pull/4450
public function testGetValueReadsMagicCallThatReturnsConstant()
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_CALL);
$this->assertSame('constant value', $this->propertyAccessor->getValue(new TestClassMagicCall('Bernhard'), 'constantMagicCallProperty'));
}
/**
* @dataProvider getValidWritePropertyPaths
*/
public function testSetValue(array|object $objectOrArray, string $path)
{
$this->propertyAccessor->setValue($objectOrArray, $path, 'Updated');
$this->assertSame('Updated', $this->propertyAccessor->getValue($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingProperty
*/
public function testSetValueThrowsExceptionIfPropertyNotFound(array|object $objectOrArray, string $path)
{
$this->expectException(NoSuchPropertyException::class);
$this->propertyAccessor->setValue($objectOrArray, $path, 'Updated');
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testSetValueThrowsNoExceptionIfIndexNotFound(array|object $objectOrArray, string $path)
{
$this->propertyAccessor->setValue($objectOrArray, $path, 'Updated');
$this->assertSame('Updated', $this->propertyAccessor->getValue($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testSetValueThrowsNoExceptionIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path)
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
$this->propertyAccessor->setValue($objectOrArray, $path, 'Updated');
$this->assertSame('Updated', $this->propertyAccessor->getValue($objectOrArray, $path));
}
public function testSetValueThrowsExceptionIfNotArrayAccess()
{
$object = new \stdClass();
$this->expectException(NoSuchIndexException::class);
$this->propertyAccessor->setValue($object, '[index]', 'Updated');
}
public function testSetValueUpdatesMagicSet()
{
$author = new TestClassMagicGet('Bernhard');
$this->propertyAccessor->setValue($author, 'magicProperty', 'Updated');
$this->assertEquals('Updated', $author->__get('magicProperty'));
}
public function testSetValueIgnoresMagicSet()
{
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS);
$author = new TestClassMagicGet('Bernhard');
$this->expectException(NoSuchPropertyException::class);
$propertyAccessor->setValue($author, 'magicProperty', 'Updated');
}
public function testSetValueThrowsExceptionIfThereAreMissingParameters()
{
$object = new TestClass('Bernhard');
$this->expectException(NoSuchPropertyException::class);
$this->propertyAccessor->setValue($object, 'publicAccessorWithMoreRequiredParameters', 'Updated');
}
public function testSetValueDoesNotUpdateMagicCallByDefault()
{
$author = new TestClassMagicCall('Bernhard');
$this->expectException(NoSuchPropertyException::class);
$this->propertyAccessor->setValue($author, 'magicCallProperty', 'Updated');
}
public function testSetValueUpdatesMagicCallIfEnabled()
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_CALL);
$author = new TestClassMagicCall('Bernhard');
$this->propertyAccessor->setValue($author, 'magicCallProperty', 'Updated');
$this->assertEquals('Updated', $author->__call('getMagicCallProperty', []));
}
public function testGetValueWhenArrayValueIsNull()
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
$this->assertNull($this->propertyAccessor->getValue(['index' => ['nullable' => null]], '[index][nullable]'));
}
/**
* @dataProvider getValidReadPropertyPaths
*/
public function testIsReadable(array|object $objectOrArray, string $path)
{
$this->assertTrue($this->propertyAccessor->isReadable($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingProperty
*/
public function testIsReadableReturnsFalseIfPropertyNotFound(array|object $objectOrArray, string $path)
{
$this->assertFalse($this->propertyAccessor->isReadable($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testIsReadableReturnsTrueIfIndexNotFound(array|object $objectOrArray, string $path)
{
// Non-existing indices can be read. In this case, null is returned
$this->assertTrue($this->propertyAccessor->isReadable($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testIsReadableReturnsFalseIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path)
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
// When exceptions are enabled, non-existing indices cannot be read
$this->assertFalse($this->propertyAccessor->isReadable($objectOrArray, $path));
}
public function testIsReadableRecognizesMagicGet()
{
$this->assertTrue($this->propertyAccessor->isReadable(new TestClassMagicGet('Bernhard'), 'magicProperty'));
}
public function testIsReadableDoesNotRecognizeMagicCallByDefault()
{
$this->assertFalse($this->propertyAccessor->isReadable(new TestClassMagicCall('Bernhard'), 'magicCallProperty'));
}
public function testIsReadableRecognizesMagicCallIfEnabled()
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_CALL);
$this->assertTrue($this->propertyAccessor->isReadable(new TestClassMagicCall('Bernhard'), 'magicCallProperty'));
}
/**
* @dataProvider getValidWritePropertyPaths
*/
public function testIsWritable(array|object $objectOrArray, string $path)
{
$this->assertTrue($this->propertyAccessor->isWritable($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingProperty
*/
public function testIsWritableReturnsFalseIfPropertyNotFound(array|object $objectOrArray, string $path)
{
$this->assertFalse($this->propertyAccessor->isWritable($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testIsWritableReturnsTrueIfIndexNotFound(array|object $objectOrArray, string $path)
{
// Non-existing indices can be written. Arrays are created on-demand.
$this->assertTrue($this->propertyAccessor->isWritable($objectOrArray, $path));
}
/**
* @dataProvider getPathsWithMissingIndex
*/
public function testIsWritableReturnsTrueIfIndexNotFoundAndIndexExceptionsEnabled(array|object $objectOrArray, string $path)
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
// Non-existing indices can be written even if exceptions are enabled
$this->assertTrue($this->propertyAccessor->isWritable($objectOrArray, $path));
}
public function testIsWritableRecognizesMagicSet()
{
$this->assertTrue($this->propertyAccessor->isWritable(new TestClassMagicGet('Bernhard'), 'magicProperty'));
}
public function testIsWritableDoesNotRecognizeMagicCallByDefault()
{
$this->assertFalse($this->propertyAccessor->isWritable(new TestClassMagicCall('Bernhard'), 'magicCallProperty'));
}
public function testIsWritableRecognizesMagicCallIfEnabled()
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_CALL);
$this->assertTrue($this->propertyAccessor->isWritable(new TestClassMagicCall('Bernhard'), 'magicCallProperty'));
}
public static function getValidWritePropertyPaths()
{
return [
[['Bernhard', 'Schussek'], '[0]', 'Bernhard'],
[['Bernhard', 'Schussek'], '[1]', 'Schussek'],
[['firstName' => 'Bernhard'], '[firstName]', 'Bernhard'],
[['index' => ['firstName' => 'Bernhard']], '[index][firstName]', 'Bernhard'],
[(object) ['firstName' => 'Bernhard'], 'firstName', 'Bernhard'],
[(object) ['first.Name' => 'Bernhard'], 'first.Name', 'Bernhard'],
[(object) ['property' => ['firstName' => 'Bernhard']], 'property[firstName]', 'Bernhard'],
[['index' => (object) ['firstName' => 'Bernhard']], '[index].firstName', 'Bernhard'],
[(object) ['property' => (object) ['firstName' => 'Bernhard']], 'property.firstName', 'Bernhard'],
// Accessor methods
[new TestClass('Bernhard'), 'publicProperty', 'Bernhard'],
[new TestClass('Bernhard'), 'publicAccessor', 'Bernhard'],
[new TestClass('Bernhard'), 'publicAccessorWithDefaultValue', 'Bernhard'],
[new TestClass('Bernhard'), 'publicAccessorWithRequiredAndDefaultValue', 'Bernhard'],
[new TestClass('Bernhard'), 'publicIsAccessor', 'Bernhard'],
[new TestClass('Bernhard'), 'publicHasAccessor', 'Bernhard'],
[new TestClass('Bernhard'), 'publicGetSetter', 'Bernhard'],
[new TestClass('Bernhard'), 'publicCanAccessor', 'Bernhard'],
// Methods are camelized
[new TestClass('Bernhard'), 'public_accessor', 'Bernhard'],
[new TestClass('Bernhard'), '_public_accessor', 'Bernhard'],
// Missing indices
[['index' => []], '[index][firstName]', null],
[['root' => ['index' => []]], '[root][index][firstName]', null],
// Special chars
[['%!@$§.' => 'Bernhard'], '[%!@$§.]', 'Bernhard'],
[['index' => ['%!@$§.' => 'Bernhard']], '[index][%!@$§.]', 'Bernhard'],
[(object) ['%!@$§' => 'Bernhard'], '%!@$§', 'Bernhard'],
[(object) ['property' => (object) ['%!@$§' => 'Bernhard']], 'property.%!@$§', 'Bernhard'],
// nested objects and arrays
[['foo' => new TestClass('bar')], '[foo].publicGetSetter', 'bar'],
[new TestClass(['foo' => 'bar']), 'publicGetSetter[foo]', 'bar'],
[new TestClass(new TestClass('bar')), 'publicGetter.publicGetSetter', 'bar'],
[new TestClass(['foo' => new TestClass('bar')]), 'publicGetter[foo].publicGetSetter', 'bar'],
[new TestClass(new TestClass(new TestClass('bar'))), 'publicGetter.publicGetter.publicGetSetter', 'bar'],
[new TestClass(['foo' => ['baz' => new TestClass('bar')]]), 'publicGetter[foo][baz].publicGetSetter', 'bar'],
];
}
public static function getValidReadPropertyPaths(): iterable
{
yield from self::getValidWritePropertyPaths();
// Optional paths can only be read and can't be written to.
yield [(object) [], 'foo?', null];
yield [(object) ['foo' => (object) ['firstName' => 'Bernhard']], 'foo.bar?', null];
yield [(object) ['foo' => (object) ['firstName' => 'Bernhard']], 'foo.bar?.baz?', null];
yield [(object) ['foo' => null], 'foo?.bar', null];
yield [(object) ['foo' => null], 'foo?.bar.baz', null];
yield [(object) ['foo' => (object) ['bar' => null]], 'foo?.bar?.baz', null];
yield [(object) ['foo' => (object) ['bar' => null]], 'foo.bar?.baz', null];
yield from self::getNullSafeIndexPaths();
}
public static function getNullSafeIndexPaths(): iterable
{
yield [(object) ['foo' => ['bar' => null]], 'foo[bar?].baz', null];
yield [[], '[foo?]', null];
yield [['foo' => ['firstName' => 'Bernhard']], '[foo][bar?]', null];
yield [['foo' => ['firstName' => 'Bernhard']], '[foo][bar?][baz?]', null];
}
/**
* @dataProvider getNullSafeIndexPaths
*/
public function testNullSafeIndexWithThrowOnInvalidIndex(array|object $objectOrArray, string $path, ?string $value)
{
$this->propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_INDEX | PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH);
$this->assertSame($value, $this->propertyAccessor->getValue($objectOrArray, $path));
}
public function testTicket5755()
{
$object = new Ticket5775Object();
$this->propertyAccessor->setValue($object, 'property', 'foobar');
$this->assertEquals('foobar', $object->getProperty());
}
public function testSetValueDeepWithMagicGetter()
{
$obj = new TestClassMagicGet('foo');
$obj->publicProperty = ['foo' => ['bar' => 'some_value']];
$this->propertyAccessor->setValue($obj, 'publicProperty[foo][bar]', 'Updated');
$this->assertSame('Updated', $obj->publicProperty['foo']['bar']);
}
public static function getReferenceChainObjectsForSetValue()
{
return [
[['a' => ['b' => ['c' => 'old-value']]], '[a][b][c]', 'new-value'],
[new TestClassSetValue(new TestClassSetValue('old-value')), 'value.value', 'new-value'],
[new TestClassSetValue(['a' => ['b' => ['c' => new TestClassSetValue('old-value')]]]), 'value[a][b][c].value', 'new-value'],
[new TestClassSetValue(['a' => ['b' => 'old-value']]), 'value[a][b]', 'new-value'],
[new \ArrayIterator(['a' => ['b' => ['c' => 'old-value']]]), '[a][b][c]', 'new-value'],
];
}
/**
* @dataProvider getReferenceChainObjectsForSetValue
*/
public function testSetValueForReferenceChainIssue($object, $path, $value)
{
$this->propertyAccessor->setValue($object, $path, $value);
$this->assertEquals($value, $this->propertyAccessor->getValue($object, $path));
}
public static function getReferenceChainObjectsForIsWritable()
{
return [
[new TestClassIsWritable(['a' => ['b' => 'old-value']]), 'value[a][b]', false],
[new TestClassIsWritable(new \ArrayIterator(['a' => ['b' => 'old-value']])), 'value[a][b]', true],
[new TestClassIsWritable(['a' => ['b' => ['c' => new TestClassSetValue('old-value')]]]), 'value[a][b][c].value', true],
];
}
/**
* @dataProvider getReferenceChainObjectsForIsWritable
*/
public function testIsWritableForReferenceChainIssue($object, $path, $value)
{
$this->assertEquals($value, $this->propertyAccessor->isWritable($object, $path));
}
public function testThrowTypeError()
{
$object = new TypeHinted();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected argument of type "DateTimeImmutable", "string" given at property path "date"');
$this->propertyAccessor->setValue($object, 'date', 'This is a string, \DateTimeImmutable expected.');
}
public function testThrowTypeErrorWithNullArgument()
{
$object = new TypeHinted();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected argument of type "DateTimeImmutable", "null" given');
$this->propertyAccessor->setValue($object, 'date', null);
}
public function testSetTypeHint()
{
$date = new \DateTimeImmutable();
$object = new TypeHinted();
$this->propertyAccessor->setValue($object, 'date', $date);
$this->assertSame($date, $object->getDate());
}
public function testArrayNotBeeingOverwritten()
{
$value = ['value1' => 'foo', 'value2' => 'bar'];
$object = new TestClass($value);
$this->propertyAccessor->setValue($object, 'publicAccessor[value2]', 'baz');
$this->assertSame('baz', $this->propertyAccessor->getValue($object, 'publicAccessor[value2]'));
$this->assertSame(['value1' => 'foo', 'value2' => 'baz'], $object->getPublicAccessor());
}
public function testCacheReadAccess()
{
$obj = new TestClass('foo');
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH, new ArrayAdapter());
$this->assertEquals('foo', $propertyAccessor->getValue($obj, 'publicGetSetter'));
$propertyAccessor->setValue($obj, 'publicGetSetter', 'bar');
$propertyAccessor->setValue($obj, 'publicGetSetter', 'baz');
$this->assertEquals('baz', $propertyAccessor->getValue($obj, 'publicGetSetter'));
}
public function testAttributeWithSpecialChars()
{
$obj = new \stdClass();
$obj->{'@foo'} = 'bar';
$obj->{'a/b'} = '1';
$obj->{'a%2Fb'} = '2';
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH, new ArrayAdapter());
$this->assertSame('bar', $propertyAccessor->getValue($obj, '@foo'));
$this->assertSame('1', $propertyAccessor->getValue($obj, 'a/b'));
$this->assertSame('2', $propertyAccessor->getValue($obj, 'a%2Fb'));
}
public function testThrowTypeErrorWithInterface()
{
$object = new TypeHinted();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected argument of type "Countable", "string" given');
$this->propertyAccessor->setValue($object, 'countable', 'This is a string, \Countable expected.');
}
public function testAnonymousClassRead()
{
$value = 'bar';
$obj = $this->generateAnonymousClass($value);
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH, new ArrayAdapter());
$this->assertEquals($value, $propertyAccessor->getValue($obj, 'foo'));
}
public function testAnonymousClassReadThrowExceptionOnInvalidPropertyPath()
{
$obj = $this->generateAnonymousClass('bar');
$this->expectException(NoSuchPropertyException::class);
$this->propertyAccessor->getValue($obj, 'invalid_property');
}
public function testAnonymousClassReadReturnsNullOnInvalidPropertyWithDisabledException()
{
$obj = $this->generateAnonymousClass('bar');
$this->propertyAccessor = PropertyAccess::createPropertyAccessorBuilder()->disableExceptionOnInvalidPropertyPath()->getPropertyAccessor();
$this->assertNull($this->propertyAccessor->getValue($obj, 'invalid_property'));
}
public function testAnonymousClassWrite()
{
$value = 'bar';
$obj = $this->generateAnonymousClass('');
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS, PropertyAccessor::THROW_ON_INVALID_PROPERTY_PATH, new ArrayAdapter());
$propertyAccessor->setValue($obj, 'foo', $value);
$this->assertEquals($value, $propertyAccessor->getValue($obj, 'foo'));
}
private function generateAnonymousClass($value)
{
return new class($value) {
private $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function getFoo()
{
return $this->foo;
}
public function setFoo($foo)
{
$this->foo = $foo;
}
};
}
public function testThrowTypeErrorInsideSetterCall()
{
$object = new TestClassTypeErrorInsideCall();
$this->expectException(\TypeError::class);
$this->propertyAccessor->setValue($object, 'property', 'foo');
}
public function testDoNotDiscardReturnTypeError()
{
$object = new ReturnTyped();
$this->expectException(\TypeError::class);
$this->propertyAccessor->setValue($object, 'foos', [new \DateTimeImmutable()]);
}
public function testDoNotDiscardReturnTypeErrorWhenWriterMethodIsMisconfigured()
{
$object = new ReturnTyped();
$this->expectException(\TypeError::class);
$this->propertyAccessor->setValue($object, 'name', 'foo');
}
public function testWriteToSingularPropertyWhilePluralOneExists()
{
$object = new TestSingularAndPluralProps();
$this->propertyAccessor->isWritable($object, 'email'); // cache access info
$this->propertyAccessor->setValue($object, 'email', 'test@email.com');
self::assertEquals('test@email.com', $object->getEmail());
self::assertEmpty($object->getEmails());
}
public function testWriteToPluralPropertyWhileSingularOneExists()
{
$object = new TestSingularAndPluralProps();
$this->propertyAccessor->isWritable($object, 'emails'); // cache access info
$this->propertyAccessor->setValue($object, 'emails', ['test@email.com']);
$this->assertEquals(['test@email.com'], $object->getEmails());
$this->assertNull($object->getEmail());
}
public function testAdderAndRemoverArePreferredOverSetter()
{
$object = new TestPluralAdderRemoverAndSetter();
$this->propertyAccessor->isWritable($object, 'emails'); // cache access info
$this->propertyAccessor->setValue($object, 'emails', ['test@email.com']);
$this->assertEquals(['test@email.com'], $object->getEmails());
}
public function testAdderAndRemoverArePreferredOverSetterForSameSingularAndPlural()
{
$object = new TestPluralAdderRemoverAndSetterSameSingularAndPlural();
$this->propertyAccessor->isWritable($object, 'aircraft'); // cache access info
$this->propertyAccessor->setValue($object, 'aircraft', ['aeroplane']);
$this->assertEquals(['aeroplane'], $object->getAircraft());
}
public function testAdderWithoutRemover()
{
$object = new TestAdderRemoverInvalidMethods();
$this->expectException(NoSuchPropertyException::class);
$this->expectExceptionMessageMatches('/.*The add method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding remove method "removeFoo" was not found\./');
$this->propertyAccessor->setValue($object, 'foos', [1, 2]);
}
public function testRemoverWithoutAdder()
{
$object = new TestAdderRemoverInvalidMethods();
$this->expectException(NoSuchPropertyException::class);
$this->expectExceptionMessageMatches('/.*The remove method "removeBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidMethods" was found, but the corresponding add method "addBar" was not found\./');
$this->propertyAccessor->setValue($object, 'bars', [1, 2]);
}
public function testAdderAndRemoveNeedsTheExactParametersDefined()
{
$object = new TestAdderRemoverInvalidArgumentLength();
$this->expectException(NoSuchPropertyException::class);
$this->expectExceptionMessageMatches('/.*The method "addFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 0 arguments, but should accept only 1\./');
$this->propertyAccessor->setValue($object, 'foo', [1, 2]);
}
public function testSetterNeedsTheExactParametersDefined()
{
$object = new TestAdderRemoverInvalidArgumentLength();
$this->expectException(NoSuchPropertyException::class);
$this->expectExceptionMessageMatches('/.*The method "setBar" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestAdderRemoverInvalidArgumentLength" requires 2 arguments, but should accept only 1\./');
$this->propertyAccessor->setValue($object, 'bar', [1, 2]);
}
public function testSetterNeedsPublicAccess()
{
$object = new TestClassSetValue(0);
$this->expectException(NoSuchPropertyException::class);
$this->expectExceptionMessageMatches('/.*The method "setFoo" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestClassSetValue" was found but does not have public access./');
$this->propertyAccessor->setValue($object, 'foo', 1);
}
public function testGetPublicProperty()
{
$value = 'A';
$path = 'a';
$object = new TestPublicPropertyGetterOnObject();
$this->assertSame($value, $this->propertyAccessor->getValue($object, $path));
}
public function testGetPrivateProperty()
{
$object = new TestPublicPropertyGetterOnObject();
$this->expectException(NoSuchPropertyException::class);
$this->expectExceptionMessageMatches('/.*Can\'t get a way to read the property "b" in class "Symfony\\\Component\\\PropertyAccess\\\Tests\\\Fixtures\\\TestPublicPropertyGetterOnObject./');
$this->propertyAccessor->getValue($object, 'b');
}
public function testGetDynamicPublicProperty()
{
$value = 'Bar';
$path = 'foo';
$object = new TestPublicPropertyDynamicallyCreated('Bar');
$this->assertSame($value, $this->propertyAccessor->getValue($object, $path));
}
public function testGetDynamicPublicPropertyWithMagicGetterDisallow()
{
$object = new TestPublicPropertyGetterOnObjectMagicGet();
$propertyAccessor = new PropertyAccessor(PropertyAccessor::DISALLOW_MAGIC_METHODS);
$this->expectException(NoSuchPropertyException::class);
$propertyAccessor->getValue($object, 'c');
}
public function testGetDynamicPublicPropertyWithMagicGetterAllow()
{
$value = 'B';
$path = 'b';
$object = new TestPublicPropertyGetterOnObjectMagicGet();
$this->assertSame($value, $this->propertyAccessor->getValue($object, $path));
}
public function testSetValueWrongTypeShouldThrowWrappedException()
{
$object = new TestClassTypedProperty();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected argument of type "float", "string" given at property path "publicProperty"');
$this->propertyAccessor->setValue($object, 'publicProperty', 'string');
}
public function testCastDateTime()
{
$object = new TypeHinted();
$this->propertyAccessor->setValue($object, 'date', new \DateTime());
$this->assertInstanceOf(\DateTimeImmutable::class, $object->getDate());
}
public function testCastDateTimeImmutable()
{
$object = new TypeHinted();
$this->propertyAccessor->setValue($object, 'date_mutable', new \DateTimeImmutable());
$this->assertInstanceOf(\DateTime::class, $object->getDate());
}
public function testGetValuePropertyThrowsExceptionIfUninitializedWithoutLazyGhost()
{
$this->expectException(UninitializedPropertyException::class);
$this->expectExceptionMessage('The property "Symfony\Component\PropertyAccess\Tests\Fixtures\UninitializedObjectProperty::$uninitialized" is not readable because it is typed "DateTimeInterface". You should initialize it or declare a default value instead.');
$this->propertyAccessor->getValue(new UninitializedObjectProperty(), 'uninitialized');
}
public function testGetValueGetterThrowsExceptionIfUninitializedWithoutLazyGhost()
{
$this->expectException(UninitializedPropertyException::class);