From dffadb87f17d3080bc60533677fc2967ee251304 Mon Sep 17 00:00:00 2001 From: Alexey Starikov Date: Sun, 10 Nov 2019 17:51:37 +0300 Subject: [PATCH] add set/get by path --- README.en.md | 187 +++++++++++++++++++----------------- README.md | 191 +++++++++++++++++++------------------ composer.json | 2 +- src/alexstar/JsonMaker.php | 33 ++++++- test.php | 25 +++++ 5 files changed, 256 insertions(+), 182 deletions(-) create mode 100644 test.php diff --git a/README.en.md b/README.en.md index bd5dcb2..9366117 100644 --- a/README.en.md +++ b/README.en.md @@ -1,89 +1,98 @@ -# jsonMaker -Create JSON easy - -PHP class for creating and modifying a text string in JSON format -# Installation - -``` -composer require alexsuperstar/jsonmaker -``` - -# Creating JSON - -```php -$a = new \alexstar\JsonMaker(); -$cc='xyz'; -$a->{$cc}->bbb->cccc[0]->xxx=5; -$a->{$cc}->zz='qq'; -$a->xyz->zf='qq'; -$a->xx->zz='qq'; -echo $a; -``` - -Result -``` -{"xyz":{"bbb":{"cccc":[{"xxx":5}]},"zz":"qq","zf":"qq"},"xx":{"zz":"qq"}} - ``` - -# Editing JSON -  -Original JSON -``` -{ - "firstName": "Иван", - "lastName": "Иванов", - "address": { - "streetAddress": "Московское ш., 101, кв.101", - "city": "Ленинград", - "postalCode": 101101 - }, - "phoneNumbers": [ - "812 123-1234", - "916 123-4567" - ] -} -``` - -PHP code - -```php -firstName='Алексей'; -$dom='дом'; -$json->address->{$dom}=6; -$json->address->code[]='123'; -$json->address->code[]='456'; -$json->phoneNumbers[2]='+7(123)1233-45-67'; -unset($json->address->city,$json->phoneNumbers[0]); -echo $json; -echo 'code count: ',count($json->address->code); -``` - -Result - -``` -{ - "firstName": "Алексей", - "lastName": "Иванов", - "address": { - "streetAddress": "Московское ш., 101, кв.101", - "postalCode": 101101, - "дом": 6, - "code": [ - "123", - "456" - ] - }, - "phoneNumbers": { - "1": "916 123-4567", - "2": "+7(123)1233-45-67" - } -} -code count: 2 -``` - -PS: about the use of memory, I can not say anything, like everything is transmitted by links, but I'm not sure. - -Translated Google Translate +# jsonMaker +Create JSON easy + +PHP class for creating and modifying a text string in JSON format +# Installation + +``` +composer require alexsuperstar/jsonmaker +``` + +# Creating JSON + +```php +$a = new \alexstar\JsonMaker(); +$cc='xyz'; +$a->{$cc}->bbb->cccc[0]->xxx=5; +$a->{$cc}->zz='qq'; +$a->xyz->zf='qq'; +$a->xx->zz='qq'; +# Set value by path +$a('/zz/name','AlexStar'); +$a('/zz/groups',['Admin'])[1]="Super user"; +$a('/zz/address',['City'=>"Moscow"])->Streen="Bulvar"; +# get value by path, return JsonMaker or null +$street=$a('/zz/address/City');// Moscow +$group0=$a('/zz/groups/0');// Admin +$group1=$a('/zz/groups/1');// Super user +var_dump($a('/zz/not_set')); // return null +$a('/zz')->groups[0]; //Admin +``` + +Result +``` +{"xyz":{"bbb":{"cccc":[{"xxx":5}]},"zz":"qq","zf":"qq"},"xx":{"zz":"qq"},"zz":{"name":"AlexStar","groups":["Admin","Super user"],"address":{"City":"Moscow","Streen":"Bulvar"}}} + ``` + +# Editing JSON +  +Original JSON +``` +{ + "firstName": "Иван", + "lastName": "Иванов", + "address": { + "streetAddress": "Московское ш., 101, кв.101", + "city": "Ленинград", + "postalCode": 101101 + }, + "phoneNumbers": [ + "812 123-1234", + "916 123-4567" + ] +} +``` + +PHP code + +```php +firstName='Алексей'; +$dom='дом'; +$json->address->{$dom}=6; +$json->address->code[]='123'; +$json->address->code[]='456'; +$json->phoneNumbers[2]='+7(123)1233-45-67'; +unset($json->address->city,$json->phoneNumbers[0]); +echo $json; +echo 'code count: ',count($json->address->code); +``` + +Result + +``` +{ + "firstName": "Алексей", + "lastName": "Иванов", + "address": { + "streetAddress": "Московское ш., 101, кв.101", + "postalCode": 101101, + "дом": 6, + "code": [ + "123", + "456" + ] + }, + "phoneNumbers": { + "1": "916 123-4567", + "2": "+7(123)1233-45-67" + } +} +code count: 2 +``` + +PS: about the use of memory, I can not say anything, like everything is transmitted by links, but I'm not sure. + +Translated Google Translate diff --git a/README.md b/README.md index dbf78ed..1888a14 100644 --- a/README.md +++ b/README.md @@ -1,91 +1,100 @@ -# jsonMaker -Create JSON easy - -*Read this in other languages: [English](README.en.md).* - -PHP класс для создания и модификации текстовой строки в формате JSON - -# Установка - -``` -composer require alexsuperstar/jsonmaker -``` - -# Создание JSON - -```php -$a = new \alexstar\JsonMaker(); -$cc='xyz'; -$a->{$cc}->bbb->cccc[0]->xxx=5; -$a->{$cc}->zz='qq'; -$a->xyz->zf='qq'; -$a->xx->zz='qq'; -echo $a; -``` - -Результат -``` -{"xyz":{"bbb":{"cccc":[{"xxx":5}]},"zz":"qq","zf":"qq"},"xx":{"zz":"qq"}} - ``` - -# Редактирование JSON - -Исходный JSON -``` -{ - "firstName": "Иван", - "lastName": "Иванов", - "address": { - "streetAddress": "Московское ш., 101, кв.101", - "city": "Ленинград", - "postalCode": 101101 - }, - "phoneNumbers": [ - "812 123-1234", - "916 123-4567" - ] -} -``` - -PHP код - -```php -firstName='Алексей'; -$dom='дом'; -$json->address->{$dom}=6; -$json->address->code[]='123'; -$json->address->code[]='456'; -$json->phoneNumbers[2]='+7(123)1233-45-67'; -unset($json->address->city,$json->phoneNumbers[0]); -echo $json; -echo 'code count: ',count($json->address->code); -``` - -Результат - -``` -{ - "firstName": "Алексей", - "lastName": "Иванов", - "address": { - "streetAddress": "Московское ш., 101, кв.101", - "postalCode": 101101, - "дом": 6, - "code": [ - "123", - "456" - ] - }, - "phoneNumbers": { - "1": "916 123-4567", - "2": "+7(123)1233-45-67" - } -} -code count: 2 -``` - - -PS: по поводу расходования памяти ничего сказать не могу, вроде все передается по ссылкам но я не уверен. +# jsonMaker +Create JSON easy + +*Read this in other languages: [English](README.en.md).* + +PHP класс для создания и модификации текстовой строки в формате JSON + +# Установка + +``` +composer require alexsuperstar/jsonmaker +``` + +# Создание JSON + +```php +$a = new \alexstar\JsonMaker(); +$cc='xyz'; +$a->{$cc}->bbb->cccc[0]->xxx=5; +$a->{$cc}->zz='qq'; +$a->xyz->zf='qq'; +$a->xx->zz='qq'; +# Устанавливаем значение по пути +$a('/zz/name','AlexStar'); +$a('/zz/groups',['Admin'])[1]="Super user"; +$a('/zz/address',['City'=>"Moscow"])->Streen="Bulvar"; +# запрос значения, вернет объект JsonMaker или null +$street=$a('/zz/address/City');// Moscow +$group0=$a('/zz/groups/0');// Admin +$group1=$a('/zz/groups/1');// Super user +var_dump($a('/zz/not_set')); // return null +$a('/zz')->groups[0]; //Admin +``` + +Результат +``` +{"xyz":{"bbb":{"cccc":[{"xxx":5}]},"zz":"qq","zf":"qq"},"xx":{"zz":"qq"},"zz":{"name":"AlexStar","groups":["Admin","Super user"],"address":{"City":"Moscow","Streen":"Bulvar"}}} + ``` + +# Редактирование JSON + +Исходный JSON +``` +{ + "firstName": "Иван", + "lastName": "Иванов", + "address": { + "streetAddress": "Московское ш., 101, кв.101", + "city": "Ленинград", + "postalCode": 101101 + }, + "phoneNumbers": [ + "812 123-1234", + "916 123-4567" + ] +} +``` + +PHP код + +```php +firstName='Алексей'; +$dom='дом'; +$json->address->{$dom}=6; +$json->address->code[]='123'; +$json->address->code[]='456'; +$json->phoneNumbers[2]='+7(123)1233-45-67'; +unset($json->address->city,$json->phoneNumbers[0]); +echo $json; +echo 'code count: ',count($json->address->code); +``` + +Результат + +``` +{ + "firstName": "Алексей", + "lastName": "Иванов", + "address": { + "streetAddress": "Московское ш., 101, кв.101", + "postalCode": 101101, + "дом": 6, + "code": [ + "123", + "456" + ] + }, + "phoneNumbers": { + "1": "916 123-4567", + "2": "+7(123)1233-45-67" + } +} +code count: 2 +``` + + +PS: по поводу расходования памяти ничего сказать не могу, вроде все передается по ссылкам но я не уверен. diff --git a/composer.json b/composer.json index a5fef5d..2cbe65b 100644 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name": "alexsuperstar/jsonmaker", "description": "PHP JSON Maker", "type": "library", - "version": "1.2.1", + "version": "1.3.0", "authors": [ { "name": "Alexey Starikov", diff --git a/src/alexstar/JsonMaker.php b/src/alexstar/JsonMaker.php index 400c7b0..533c4c8 100644 --- a/src/alexstar/JsonMaker.php +++ b/src/alexstar/JsonMaker.php @@ -52,7 +52,38 @@ public function parse($data) } } } - + /* + * set/get value by path + * */ + public function __invoke() + { + if(func_num_args()>0){ + $path=func_get_arg(0); + if(func_num_args()>1) { + $newVal = func_get_arg(1); + } + $p = explode('/', trim($path,'/')); + $vars =& $this; + foreach ($p as $k => $v) { + if(is_numeric($v)){# array + if(!isset($vars[$v]) && !isset($newVal)) return null; + $vars=&$vars[$v]; + }else{ # method + if(!isset($vars->{$v}) && !isset($newVal)) return null; + $vars =&$vars->{$v}; + } + } + if(isset($newVal)) { + if (is_numeric($v)) { + $vars[$v] = is_scalar($newVal)?$newVal:new self($newVal); + } else { + $vars = is_scalar($newVal)?$newVal:new self($newVal); + } + } + return $vars; + } + return null; + } # overloading public function __set($name, $value) { diff --git a/test.php b/test.php new file mode 100644 index 0000000..6814e1a --- /dev/null +++ b/test.php @@ -0,0 +1,25 @@ + + * Date: 10.11.2019 + * Time: 17:30 + */ +include 'src/alexstar/JsonMaker.php'; +$a = new \alexstar\JsonMaker(); +$cc='xyz'; +$a->{$cc}->bbb->cccc[0]->xxx=5; +$a->{$cc}->zz='qq'; +$a->xyz->zf='qq'; +$a->xx->zz='qq'; +# Устанавливаем значение по пути +$a('/zz/name','AlexStar'); +$a('/zz/groups',['Admin'])[1]="Super user"; +$a('/zz/address',['City'=>"Moscow"])->Streen="Bulvar"; +# запрос значения, вернет объект JsonMaker или null +$street=$a('/zz/address/City');// Moscow +$group0=$a('/zz/groups/0');// Admin +$group1=$a('/zz/groups/1');// Super user +var_dump($a('/zz/not_set')); // return null +$a('/zz')->groups[0]; //Admin + +echo $a; \ No newline at end of file