PHP code example of square / pjson

1. Go to this page and download the library: Download square/pjson library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

square / pjson example snippets


use Square\Pjson\Json;
use Square\Pjson\JsonSerialize;

class Schedule
{
    use JsonSerialize;

    #[Json]
    protected int $start;

    #[Json]
    protected int $end;

    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
}

(new Schedule(1, 2))->toJson();

Schedule::fromJsonString('{"start":1,"end":2}');

use Square\Pjson\Json;
use Square\Pjson\JsonSerialize;

class Schedule
{
    use JsonSerialize;

    #[Json('begin')]
    protected int $start;

    #[Json('stop')]
    protected int $end;

    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
}

(new Schedule(1, 2))->toJson();

dump(Schedule::fromJsonString('{"begin":1,"stop":2}'));

// ^ Schedule^ {#345
//   #start: 1
//   #end: 2
// }

class Schedule
{
    use JsonSerialize;

    #[Json(['data', 'start'])]
    protected int $start;

    #[Json(['data', 'end'])]
    protected int $end;

    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
}

class Schedule
{
    use JsonSerialize;

    #[Json]
    protected int $start;

    #[Json]
    protected int $end;
}

class Weekend
{
    use JsonSerialize;

    #[Json('saturday')]
    protected Schedule $sat;
    #[Json('sunday')]
    protected Schedule $sun;
}

class Week
{
    use JsonSerialize;

    #[Json(type: Schedule::class)]
    protected array $days;
}

class Collector
{
    use JsonSerialize;

    #[Json(type: Schedule::class)]
    public Collection $schedules;

    #[Json(type: Schedule::class, collection_factory_method: 'make')]
    public Collection $static_factoried_schedules;

    #[Json(type: Schedule::class, collection_factory_method: 'makeme')]
    public Collection $factoried_schedules;
}

abstract class CatalogObject
{
    use JsonSerialize;

    #[Json]
    protected $id;

    #[Json]
    protected string $type;
}

class CatalogCategory extends CatalogObject
{
    use JsonSerialize;

    #[Json('parent_category_id')]
    protected string $parentCategoryId;
}

class CatalogItem extends CatalogObject
{
    use JsonSerialize;

    #[Json]
    protected string $name;
}

abstract class CatalogObject
{
    use JsonSerialize;

    #[Json]
    protected $id;

    #[Json]
    protected string $type;

    public static function fromJsonData($jd): static
    {
        $t = $jd['type'];

        return match ($t) {
            'category' => CatalogCategory::fromJsonData($jd),
            'item' => CatalogItem::fromJsonData($jd),
        };
    }
}

$jsonCat = '{"type": "category", "id": "123", "parent_category_id": "456"}';
$c = CatalogObject::fromJsonString($jsonCat);
$this->assertEquals(CatalogCategory::class, get_class($c));

$jsonItem = '{"type": "item", "id": "123", "name": "Sandals"}';
$c = CatalogObject::fromJsonString($jsonItem);
$this->assertEquals(CatalogItem::class, get_class($c));

Schedule::listFromJsonString('[
    {
        "schedule_start": 1,
        "schedule_end": 2
    },
    {
        "schedule_start": 11,
        "schedule_end": 22
    },
    {
        "schedule_start": 111,
        "schedule_end": 222
    }
]');

[
    new Schedule(1, 2),
    new Schedule(11, 22),
    new Schedule(111, 222),
];

Schedule::fromJsonString('{
    "data": {
        "schedule_start": 1,
        "schedule_end": 2
    }
}', path: 'data');

Schedule::fromJsonString('{
    "data": {
        "main": {
            "schedule_start": 1,
            "schedule_end": 2
        }
    }
}', path: ['data', 'main']);

class Widget
{
    use JsonSerialize;

    #[Json]
    public Status $status;
}

enum Status : string
{
    case ON = 'ON';
    case OFF = 'OFF';
}
$w = new Widget;
$w->status = Status::ON;

$w->toJson(); // {"status": "ON"}

class Widget
{
    use JsonSerialize;

    #[Json]
    public Size $size;
}

enum Size
{
    use JsonSerialize;

    case BIG;
    case SMALL;

    public static function fromJsonData($d, array|string $path = []): static
    {
        return match ($d) {
            'BIG' => self::BIG,
            'SMALL' => self::SMALL,
            'big' => self::BIG,
            'small' => self::SMALL,
        };
    }

    public function toJsonData()
    {
        return strtolower($this->name);
    }
}

$w = new Widget;
$w->size = Size::BIG;

$w->toJson(); // {"status": "big"}

readonly class Token
{
    use JsonSerialize;

    #[Json(('{"key":"data"}'); // successful

Token::fromJsonString('{"other":"has no key"}'); // throws Exception

class Stats
{
    use JsonSerialize;

    #[Json]
    public BigInt $count;
}

class BigInt implements JsonDataSerializable
{
    public function __construct(
        protected string $value,
    ) {
    }

    public static function fromJsonData($jd, array|string $path = []) : static
    {
        return new BigInt($jd);
    }

    public function toJsonData()
    {
        return $this->value;
    }
}

$stats = new Stats;
$stats->count = new BigInt("123456789876543234567898765432345678976543234567876543212345678765432");
$stats->toJson(); // {"count":"123456789876543234567898765432345678976543234567876543212345678765432"}

use Illuminate\Contracts\Database\Eloquent\Castable;
use Square\Pjson\Json;
use Square\Pjson\JsonSerialize;
use Square\Pjson\Integrations\Laravel\JsonCastable;

class Schedule implements Castable // implement the laravel interface
{
    use JsonSerialize;
    use JsonCastable; // use the provided Pjson trait

    #[Json]
    protected int $start;

    #[Json]
    protected int $end;

    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
}

$casts = [
    'schedule' => Schedule::class,
];

use Square\Pjson\Json;
use Square\Pjson\JsonSerialize;

class Schedule
{
    use JsonSerialize;

    #[Json]
    protected int $start;

    #[Json]
    protected int $end;

    public function __construct(int $start, int $end)
    {
        $this->start = $start;
        $this->end = $end;
    }
}

$casts = [
    'schedule' => JsonCaster::class.':'.Schedule::class,
];