probiers-us / php-json-property
PHP JSON property helper trait
Fund package maintenance!
nick-zh
Requires
- php: ^7.4
- ext-json: *
Requires (Dev)
- infection/infection: ^0.16
- johnkary/phpunit-speedtrap: ^3.1
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^9.1
- rregeer/phpunit-coverage-check: ^0.3.1
- squizlabs/php_codesniffer: ^3.5
This package is auto-updated.
Last update: 2024-10-19 04:17:47 UTC
README
Description
This is a helper to add attributes to an array. This will help,
if you need to represent JSON entities / classes and resolve recursively when JSON encoding.
Installation
composer require probiers-us/php-json-property
Usage
You can use JsonPropertyInterface
and JsonPropertyTrait
in the classes
you want to add this. Calling json_encode
will recursively resolve all embedded
classes in the JSON properties array, leveraging JsonSerializable
.
Add a property
$jsonPropertyClass->addJsonProperty('key', 'value');
Add multiple properties
$jsonPropertyClass->addJsonProperties(['key', 'value']);
Remove property
$jsonPropertyClass->removeJsonProperty('key');
Set properties array of class
$jsonPropertyClass->setJsonProperties(['key', 'value']);
Get properties
Get the array without resolving embedded properties
$jsonPropertyClass->getJsonProperties();
Get the array of properties and resolve embedded
$jsonPropertyClass->getJsonProperties(true);
Add typed properties
To add typed JSON properties, add a wrapper around e.g. addJsonProperty
public function addName(string $name) { $this->addJsonProperty('name', $name); }