Skip to content

Commit

Permalink
Merge pull request #12 from mybandmarket/factory
Browse files Browse the repository at this point in the history
Add a color factory
  • Loading branch information
sebastiandedeyne committed Jan 12, 2017
2 parents 097b8bc + 4dd9355 commit 051affb
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Exceptions/InvalidColorValue.php
Expand Up @@ -42,4 +42,9 @@ public static function malformedRgbaColorString(string $string): self
{
return new static("Rgba color string `{$string}` is malformed. An rgba color contains 3 comma separated values between 0 and 255 with an alpha value between 0 and 1, wrapped in `rgba()`, e.g. `rgb(0,0,255,0.5)`.");
}

public static function malformedColorString(string $string): self
{
return new static("Color string `{$string}` doesn't match any of the available colors.");
}
}
35 changes: 35 additions & 0 deletions src/Factory.php
@@ -0,0 +1,35 @@
<?php

namespace Spatie\Color;

use ReflectionClass;
use Spatie\Color\Exceptions\InvalidColorValue;

class Factory
{
const EXCLUDED_FILES = ['.', '..'];

public static function fromString(string $string): Color
{
$colorClasses = self::getColorClasses();

foreach ($colorClasses as $colorClass) {
try {
return call_user_func("$colorClass::fromString", $string);
} catch (InvalidColorValue $e) {
// Catch the exception but never throw it.
}
}

throw InvalidColorValue::malformedColorString($string);
}

protected static function getColorClasses(): array
{
return [
Hex::class,
Rgb::class,
Rgba::class,
];
}
}
44 changes: 44 additions & 0 deletions tests/FactoryTest.php
@@ -0,0 +1,44 @@
<?php

namespace Spatie\Color\Test;

use Spatie\Color\Hex;
use Spatie\Color\Rgb;
use Spatie\Color\Rgba;
use Spatie\Color\Factory;
use Spatie\Color\Exceptions\InvalidColorValue;

class FactoryTest extends \PHPUnit_Framework_TestCase
{
/** @test */
public function it_can_create_a_hex_color_from_a_string()
{
$hex = Factory::fromString('#aabbcc');

$this->assertInstanceOf(Hex::class, $hex);
}

/** @test */
public function it_can_create_a_rgb_color_from_a_string()
{
$rgb = Factory::fromString('rgb(55,155,255)');

$this->assertInstanceOf(Rgb::class, $rgb);
}

/** @test */
public function it_can_create_a_rgba_color_from_a_string()
{
$rgba = Factory::fromString('rgba(55,155,255,0.5)');

$this->assertInstanceOf(Rgba::class, $rgba);
}

/** @test */
public function it_cant_create_a_color_from_malformed_string()
{
$this->expectException(InvalidColorValue::class);

Factory::fromString('abcd');
}
}

0 comments on commit 051affb

Please sign in to comment.