Skip to content

A flexible data coder for encoding and decoding formats like JSON, YAML, and more.

License

Notifications You must be signed in to change notification settings

sunrise-php/coder

Repository files navigation

Data Coder

A flexible data coder for encoding and decoding formats like JSON, YAML, and more.

Scrutinizer Code Quality Code Coverage Total Downloads

Installation

composer require sunrise/coder

How to use

Quick Start

use Sunrise\Coder\CodecManager;
use Sunrise\Coder\Codec\JsonCodec;
use Sunrise\Coder\Codec\UrlEncodedCodec;
use Sunrise\Coder\Dictionary\MediaType;

$codecManager = new CodecManager(codecs: [
    new JsonCodec(),
    new UrlEncodedCodec(),
]);

// Encoding result: {"foo": "bar"}
$codecManager->encode(MediaType::JSON, ['foo' => 'bar']);
// Decoding result: ['foo' => 'bar']
$codecManager->decode(MediaType::JSON, '{"foo": "bar"}');

// Encoding result: foo=bar
$codecManager->encode(MediaType::UrlEncoded, ['foo' => 'bar']);
// Decoding result: ['foo' => 'bar']
$codecManager->decode(MediaType::UrlEncoded, 'foo=bar');

PHP-DI definitions

use DI\ContainerBuilder;
use Sunrise\Coder\CodecManagerInterface;

$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinition(__DIR__ . '/../vendor/sunrise/coder/resources/definitions/coder.php');
$containerBuilder->addDefinition(__DIR__ . '/../vendor/sunrise/coder/resources/definitions/codecs/json_codec.php');
$containerBuilder->addDefinition(__DIR__ . '/../vendor/sunrise/coder/resources/definitions/codecs/url_encoded_codec.php');

$container = $containerBuilder->build();

// See above for usage examples.
$codecManager = $container->get(CodecManagerInterface::class);

Tests

composer test