Skip to content
This repository was archived by the owner on Mar 22, 2019. It is now read-only.

Add support for 3 character HTML colors #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions library/ZendPdf/Color/Html.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,26 @@ public function getComponents()
* Creates a ColorInterface object from the HTML representation.
*
* @param string $color May either be a hexidecimal number of the form
* #rrggbb or one of the 140 well-known names (black, white, blue, etc.)
* #rrggbb, #rgb or one of the 140 well-known names (black, white, blue, etc.)
* @return ColorInterface
*/
public static function color($color)
{
$pattern = '/^#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})$/';
$pattern = '/^#([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})([A-Fa-f0-9]{2})$|^#([A-Fa-f0-9])([A-Fa-f0-9])([A-Fa-f0-9])$/';
if (preg_match($pattern, $color, $matches)) {
$r = round((hexdec($matches[1]) / 255), 3);
$g = round((hexdec($matches[2]) / 255), 3);
$b = round((hexdec($matches[3]) / 255), 3);
if (strlen($matches[1]) === 2) {
$r = $matches[1];
$g = $matches[2];
$b = $matches[3];
} else {
$r = $matches[4].$matches[4];
$g = $matches[5].$matches[5];
$b = $matches[6].$matches[6];
}
$r = round((hexdec($r) / 255), 3);
$g = round((hexdec($g) / 255), 3);
$b = round((hexdec($b) / 255), 3);

if (($r == $g) && ($g == $b)) {
return new GrayScale($r);
} else {
Expand Down
46 changes: 46 additions & 0 deletions tests/ZendPdf/Color/HtmlTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Pdf
*/

namespace ZendPdfTest\Color;

use ZendPdf\Color\Html;

/**
* @category Zend
* @package Zend_PDF
* @subpackage UnitTests
* @group Zend_PDF
*/
class HtmlTest extends \PHPUnit_Framework_TestCase
{
public function colorProvider()
{
return array(
array('#cccccc', array(0.8)),
array('#CCCCCC', array(0.8)),
array('#ffcc66', array(1.0, 0.8, 0.4)),
array('#FFCC66', array(1.0, 0.8, 0.4)),
array('#123456', array(0.071, 0.204, 0.337)),

array('#ccc', array(0.8)),
array('#CCC', array(0.8)),
array('#fc6', array(1.0, 0.8, 0.4)),
array('#FC6', array(1.0, 0.8, 0.4)),
);
}

/**
* @dataProvider colorProvider
*/
public function testColor($color, $components)
{
$this->assertSame($components, Html::color($color)->getComponents());
}
}