PHP code example of ramasdev / simple-collection-transformer

1. Go to this page and download the library: Download ramasdev/simple-collection-transformer 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/ */

    

ramasdev / simple-collection-transformer example snippets


use Ramasdev\SimpleCollectionTransformer\Attributes\CollectionAttribute;
use Ramasdev\SimpleCollectionTransformer\Tests\Unit\Data\Collections\ChannelCollection;

#[CollectionAttribute(ChannelCollection::class)]
class Channel
{
    public function __construct(
        private string $channelId,
        private string $channelType,
        private Carbon $lastRegistration
    ) {
    }

    public function getChannelId(): string
    {
        return $this->channelId;
    }

    public function getChannelType(): string
    {
        return $this->channelType;
    }

    public function getLastRegistration(): Carbon
    {
        return $this->lastRegistration;
    }
}

use Ramasdev\SimpleCollectionTransformer\CollectionTransformer;

$actualCollection = $this->collectionTransformer->transform($data, function ($item) {
    if ($item['channel_id'] === 'b') {
        return false;
    }

    return new Channel($item['channel_id'], $item['channel_type'], new Carbon($item['last_registration']));
}); // Returns ChannelCollection

use Ramasdev\SimpleCollectionTransformer\CollectionTransformer;

$actualCollection = $this->collectionTransformer->transform($data, function ($item) {
    return $this->decoder->decodeArray((array) $item, Channel::class);
}); // Returns ChannelCollection