PHP code example of hedgehoglab-engineering / php-declared-data

1. Go to this page and download the library: Download hedgehoglab-engineering/php-declared-data 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/ */

    

hedgehoglab-engineering / php-declared-data example snippets


use HedgehoglabEngineering\DeclaredData\AbstractDeclaredData;

class UserData extends AbstractDeclaredData
{
    public function __construct(
        public string $name,
        public string $email,
        public int $age,
    ) {
        //
    }
}

use HedgehoglabEngineering\DeclaredData\Contracts\ResolvableData;

class UserData extends AbstractDeclaredData implements ResolvableData
{
    // ...
}

use HedgehoglabEngineering\DeclaredData\Contracts\LenientData;

class UserData extends AbstractDeclaredData implements LenientData
{
    // ...
}

use HedgehoglabEngineering\DeclaredData\Contracts\SparseData;

class UserData extends AbstractDeclaredData implements SparseData
{
    // ...
}

use HedgehoglabEngineering\DeclaredData\Attributes\CollectionOf;

#[CollectionOf(class: PostData::class)]
public readonly Collection $posts;

use HedgehoglabEngineering\DeclaredData\Attributes\DateTimeFromFormat;

#[DateTimeFromFormat(format: 'Y-m-d', timezone: 'UTC', toTimezone: 'America/New_York')]
public readonly DateTimeInterface $publishedAt;

use HedgehoglabEngineering\DeclaredData\Attributes\JsonDecode;

#[JsonDecode(associative: true)]
public readonly array $settings;

use HedgehoglabEngineering\DeclaredData\Attributes\MapArgumentName;

#[MapArgumentName(name: 'first_name')]
public string $firstName;

use HedgehoglabEngineering\DeclaredData\AbstractDeclaredData;
use HedgehoglabEngineering\DeclaredData\Contracts\ResolvableData;
use HedgehoglabEngineering\DeclaredData\Attributes\CollectionOf;
use HedgehoglabEngineering\DeclaredData\Attributes\DateTimeFromFormat;
use HedgehoglabEngineering\DeclaredData\Attributes\JsonDecode;
use HedgehoglabEngineering\DeclaredData\Attributes\MapArgumentName;
use Illuminate\Support\Collection;

class PostData extends AbstractDeclaredData implements ResolvableData
{
    public function __construct(
        #[MapArgumentName(name: 'post_title')]
        public string $title,

        #[DateTimeFromFormat('Y-m-d H:i:s')]
        public DateTimeInterface $createdAt,

        #[JsonDecode(associative: true)]
        public array $metadata,

        #[CollectionOf(class: CommentData::class)]
        public Collection $comments,
    ) {
        //
    }
}

$inputData = [
    'post_title' => 'Test Post',
    'createdAt' => '2023-10-01 12:00:00',
    'metadata' => '{"views": 100, "likes": 10}',
    'comments' => [
        ['content' => 'Great post!'],
    ],
];

$resolvedPostData = PostData::create($inputData);
bash
composer analyse