- a colour read from a string is kept (Color is immutable, so one instance is shared): ~20 ns instead of ~170-235 ns per call, and 100 000 kept results take 2 MB instead of 14 MB; at most 1024 kept, the cache starts over when full - only clean hex strings are kept: hexdec() still warns about '#zz0000' each time, as before - [r, g, b, a] lists skip array_values() - ColorOfTest compares it with the old function over 3000+ strings and odd arrays Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01UZqwpHZaasov261cZ96aQf
58 lines
2.4 KiB
PHP
58 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Tests\Util;
|
|
|
|
use JumPHP\Util\Color;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
final class ColorOfTest extends TestCase
|
|
{
|
|
/** Color::of() before its cache: the reference the fast one must match, value for value */
|
|
private static function reference(Color|array|string $color): Color
|
|
{
|
|
if ($color instanceof Color) {
|
|
return $color;
|
|
}
|
|
if (is_string($color)) {
|
|
$hex = ltrim($color, '#');
|
|
if (strlen($hex) === 3) {
|
|
$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
|
|
}
|
|
return new Color(hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2)),
|
|
strlen($hex) >= 8 ? hexdec(substr($hex, 6, 2)) : 255);
|
|
}
|
|
$c = array_values($color);
|
|
return new Color((int)($c[0] ?? 0), (int)($c[1] ?? 0), (int)($c[2] ?? 0), (int)($c[3] ?? 255));
|
|
}
|
|
|
|
public function testEveryShapeGivesTheSameColourAsBefore(): void
|
|
{
|
|
$inputs = ['', '#', '##fff', '#f', '#ff', '#fff', '#FFF', '#ffff', '#fffff', '#1f2329', '1f2329', '#1F2329',
|
|
'#ffffff80', '#ffffff8', '#ffffff8000', '#abc123ef', 'red', '#zzzzzz', '#12g456', ' #fff', '#fff '];
|
|
for ($i = 0; $i < 3000; $i++) {
|
|
$inputs[] = '#' . substr(bin2hex(random_bytes(5)), 0, [3, 6, 8, 4, 7][$i % 5]);
|
|
}
|
|
$arrays = [[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5], ['r' => 1, 'g' => 2, 'b' => 3],
|
|
[3 => 9, 1 => 8], [1.9, '2', null, true], [0, 0, 0, 0], [300, -5, 7.5], [1 => 10, 2 => 20, 3 => 30]];
|
|
foreach ([...$inputs, ...$inputs, ...$arrays] as $input) { // twice: the second time comes from the cache
|
|
$old = @self::reference($input);
|
|
$new = @Color::of($input);
|
|
self::assertSame([$old->r, $old->g, $old->b, $old->a], [$new->r, $new->g, $new->b, $new->a], var_export($input, true));
|
|
}
|
|
$c = new Color(1, 2, 3);
|
|
self::assertSame($c, Color::of($c));
|
|
}
|
|
|
|
public function testAnInvalidStringStillWarnsEveryTime(): void
|
|
{
|
|
$warnings = 0;
|
|
set_error_handler(function () use (&$warnings): bool { $warnings++; return true; });
|
|
try {
|
|
Color::of('#zz0000');
|
|
Color::of('#zz0000');
|
|
} finally {
|
|
restore_error_handler();
|
|
}
|
|
self::assertSame(2, $warnings);
|
|
}
|
|
}
|