ock/adaptism

Library to map adapter classes.

dev-main 2024-11-10 15:58 UTC

This package is auto-updated.

Last update: 2024-11-10 16:24:36 UTC


README

Build Status Coverage Status

Adaptism

Adaptism is a package that finds adapters for objects using a dispatch map.

Adapters can be annotated with attributes for discovery.

Convert objects

use Ock\Adaptism\Tests\Fixtures\Color\Hex\HexColorInterface;
use Ock\Adaptism\Tests\Fixtures\Color\Rgb\RgbColor;
use Ock\Adaptism\UniversalAdapter\UniversalAdapterInterface;

function f(UniversalAdapterInterface $universalAdapter): void {
  $rgb = new RgbColor(255, 0, 0);
  $hex = $universalAdapter->adapt($rgb, HexColorInterface::class);

  assert($hex instanceof HexColorInterface);
  assert($hex->getHexCode() === 'ff0000');
}

Declare adapters

use Ock\Adaptism\Attribute\Adapter;
use Ock\Adaptism\Attribute\Parameter\Adaptee;
use Ock\Adaptism\Tests\Fixtures\Color\Hex\HexColorInterface;
use Ock\Adaptism\Tests\Fixtures\Color\Rgb\RgbColor;
use Ock\Adaptism\Tests\Fixtures\Color\Rgb\RgbColorInterface;

class C {
  #[Adapter]
  public static function adapt(
    #[Adaptee] RgbColorInterface $rgb,
  ): HexColorInterface {
    return new RgbColor(
      sprintf(
        '%02x%02x%02x',
        $rgbColor->red(), $rgbColor->green(), $rgbColor->blue()));
  }
}

More examples?

Study the tests!