PHP code example of vjik / cycle-typecast

1. Go to this page and download the library: Download vjik/cycle-typecast 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/ */

    

vjik / cycle-typecast example snippets


use Vjik\CycleTypecast\AttributeTypecastHandler;
use Vjik\CycleTypecast\UuidString\UuidStringToBytesType;
use Vjik\CycleTypecast\DateTimeImmutable\DateTimeImmutableToIntegerType;

#[Entity(
    // ...
    typecast: AttributeTypecastHandler::class,
)]
final class User
{
    // ...

    #[Column(type: 'primary', primary: true)]
    #[UuidStringToBytesType]
    private string $id;

    #[Column(type: 'int')]
    #[DateTimeImmutableToIntegerType]
    private DateTimeImmutable $createDate;

use Vjik\CycleTypecast\ArrayToStringType;
use Vjik\CycleTypecast\DateTimeImmutable\DateTimeImmutableToIntegerType;
use Vjik\CycleTypecast\TypecastHandler;
use Vjik\CycleTypecast\UuidString\UuidStringToBytesType;

final class UserTypecastHandler extends Vjik\CycleTypecast\TypecastHandler
{
    protected function getConfig(): array
    {
        return [
            'id' => new UuidStringToBytesType(),
            'createDate' => new DateTimeImmutableToIntegerType(),
            'modifyDate' => new DateTimeImmutableToIntegerType(),
            'tags' => new ArrayToStringType(','),
        ];
    }
}

use Cycle\ORM\ORMInterface;
use Cycle\ORM\PromiseMapper\PromiseMapper;
use Vjik\CycleTypecast\Typecaster;
use Vjik\CycleTypecast\ArrayToStringType;
use Vjik\CycleTypecast\DateTimeImmutable\DateTimeImmutableToIntegerType;
use Vjik\CycleTypecast\UuidString\UuidStringToBytesType;

final class UserMapper extends PromiseMapper
{
    private Typecaster $typecaster;

    public function __construct(ORMInterface $orm, string $role)
    {
        // Typecast configuration
        $this->typecaster = new Typecaster([
            'id' => new UuidStringToBytesType(),
            'createDate' => new DateTimeImmutableToIntegerType(),
            'modifyDate' => new DateTimeImmutableToIntegerType(),
            'tags' => new ArrayToStringType(','),
        ]);
        
        parent::__construct($orm, $role);
    }

    public function extract($entity): array
    {
        $data = parent::extract($entity);
        
        // Typecast after extract from entity
        return $this->typecaster->prepareAfterExtract($data);
    }

    public function hydrate($entity, array $data)
    {
        // Typecast before hydrate entity
        $data = $this->typecaster->prepareBeforeHydrate($data);
        
        return parent::hydrate($entity, $data);
    }
}

new ArrayToStringType(',');

new DateTimeImmutableToIntegerType();

new IntegerEnumType(IntegerEnum::class);

new StringEnumType(StringEnum::class);

new UuidStringToBytesType();