Skip to content

Commit

Permalink
reimplemented converter chain and introducd HEX to RGB Converter
Browse files Browse the repository at this point in the history
  • Loading branch information
scuben committed Dec 12, 2017
1 parent 003f3ea commit 5f1f5df
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 21 deletions.
34 changes: 13 additions & 21 deletions src/Converter.php
Expand Up @@ -29,42 +29,34 @@ private function addConverter(Convertible $converter)

public function convert(Color $color, string $fqcn): Color
{
foreach ($this->getConverterChain(get_class($color), $fqcn) as $converter) {
foreach ($this->getConverterChain([], \get_class($color), $fqcn) as $converter) {
$color = $converter->convert($color);
}

return $color;
}

/**
* @param string $fqcnFrom
* @param string $fqcnTo
* @param Convertible[] $converters
* @param string $fromFqcn
* @param string $toFqcn
*
* @return Convertible[]
*/
private function getConverterChain(string $fqcnFrom, string $fqcnTo): array
private function getConverterChain(array $converters, string $fromFqcn, string $toFqcn): array
{
/** @var Convertible[] $converters */
$converters = [];

do {
$converter = $this->getConverterTo($fqcnTo);
$fqcnTo = $converter::supportsFrom();
foreach ($this->converters as $converter) {
if ($converter::supportsFrom() === $fromFqcn) {
$converters[] = $converter;

$converters[] = $converter;
} while ($converter::supportsFrom() !== $fqcnFrom);
if ($converter::supportsTo() === $toFqcn) {
return $converters;
}

return array_reverse($converters);
}

private function getConverterTo(string $fqcn): Convertible
{
foreach ($this->converters as $converter) {
if ($converter::supportsTo() === $fqcn) {
return $converter;
return $this->getConverterChain($converters, $converter::supportsTo(), $toFqcn);
}
}

throw new \RuntimeException('no converter found getConverterTo');
return $converters;
}
}
35 changes: 35 additions & 0 deletions src/Converter/HEXToRGBConverter.php
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Artack\Color\Converter;

use Artack\Color\Color\Color;
use Artack\Color\Color\HEX;
use Artack\Color\Color\RGB;
use Webmozart\Assert\Assert;

class HEXToRGBConverter implements Convertible
{
public function convert(Color $color): Color
{
/* @var HEX $color */
Assert::isInstanceOf($color, HEX::class, sprintf('color should be an instance of [%s]', HEX::class));

$red = hexdec($color->getRed());
$green = hexdec($color->getGreen());
$blue = hexdec($color->getBlue());

return new RGB($red, $green, $blue);
}

public static function supportsFrom(): string
{
return HEX::class;
}

public static function supportsTo(): string
{
return RGB::class;
}
}

0 comments on commit 5f1f5df

Please sign in to comment.