Skip to content

probiers-us/php-json-property-class

Repository files navigation

php-json-property-class

CircleCI Maintainability Test Coverage Latest Stable Version Latest Unstable Version

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);
}