File tree Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Expand file tree Collapse file tree 2 files changed +63
-0
lines changed Original file line number Diff line number Diff line change @@ -9,6 +9,8 @@ class Meta implements \JsonSerializable
99
1010 public function __construct (\stdClass $ data )
1111 {
12+ $ this ->validateObject ($ data );
13+
1214 $ this ->data = $ data ;
1315 }
1416
@@ -21,4 +23,22 @@ public function jsonSerialize()
2123 {
2224 return $ this ->data ;
2325 }
26+
27+ private function validateObject ($ object )
28+ {
29+ foreach ($ object as $ name => $ value ) {
30+ if (is_string ($ name ) && !$ this ->isValidMemberName ($ name )) {
31+ throw new \OutOfBoundsException ("Not a valid attribute name ' $ name' " );
32+ }
33+
34+ if (is_array ($ value ) || $ value instanceof \stdClass) {
35+ $ this ->validateObject ($ value );
36+ }
37+ }
38+ }
39+
40+ private function isValidMemberName (string $ name ): bool
41+ {
42+ return preg_match ('/^(?=[^-_ ])[a-zA-Z0-9\x{0080}-\x{FFFF}-_ ]*(?<=[^-_ ])$/u ' , $ name ) === 1 ;
43+ }
2444}
Original file line number Diff line number Diff line change 44namespace JsonApiPhp \JsonApi \Test ;
55
66use JsonApiPhp \JsonApi \Document \Link \Link ;
7+ use JsonApiPhp \JsonApi \Document \Meta ;
78use JsonApiPhp \JsonApi \Document \Resource \Relationship ;
89use JsonApiPhp \JsonApi \Document \Resource \ResourceObject ;
910use PHPUnit \Framework \TestCase ;
@@ -45,6 +46,48 @@ public function testInvalidRelationshipNamesAreNotAllowed(string $name)
4546 $ res ->setRelationship ($ name , Relationship::fromSelfLink (new Link ('https://example.com ' )));
4647 }
4748
49+ /**
50+ * @param string $name
51+ * @expectedException \OutOfBoundsException
52+ * @expectedExceptionMessage Not a valid attribute name
53+ * @dataProvider invalidAttributeNames
54+ */
55+ public function testInvalidMetaNames (string $ name )
56+ {
57+ Meta::fromArray (
58+ [
59+ 'copyright ' => 'Copyright 2015 Example Corp. ' ,
60+ 'authors ' => [
61+ [
62+ 'firstname ' => 'Yehuda ' ,
63+ $ name => 'Katz ' ,
64+ ],
65+ ],
66+ ]
67+ );
68+ }
69+
70+ /**
71+ * @param string $name
72+ * @dataProvider validAttributeNames
73+ */
74+ public function testValidMetaNames (string $ name )
75+ {
76+ $ meta = Meta::fromArray (
77+ [
78+ 'copyright ' => 'Copyright 2015 Example Corp. ' ,
79+ 'authors ' => [
80+ [
81+ 'firstname ' => 'Yehuda ' ,
82+ $ name => 'Katz ' ,
83+ ],
84+ ],
85+ ]
86+ );
87+
88+ $ this ->assertInternalType ('string ' , json_encode ($ meta ));
89+ }
90+
4891 /**
4992 * @param string $name
5093 * @dataProvider validAttributeNames
You can’t perform that action at this time.
0 commit comments