Skip to content

[CLEANUP] Extract method Color::renderAsHex #825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 27, 2025
Merged
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
32 changes: 24 additions & 8 deletions src/Value/Color.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,15 +230,9 @@ public function render(OutputFormat $outputFormat): string
&& \implode('', \array_keys($this->aComponents)) === 'rgb'
&& $this->allComponentsAreNumbers()
) {
$result = \sprintf(
'%02x%02x%02x',
$this->aComponents['r']->getSize(),
$this->aComponents['g']->getSize(),
$this->aComponents['b']->getSize()
);
return '#' . (($result[0] == $result[1]) && ($result[2] == $result[3]) && ($result[4] == $result[5])
? "$result[0]$result[2]$result[4]" : $result);
return $this->renderAsHex();
}

return parent::render($outputFormat);
}

Expand All @@ -256,4 +250,26 @@ private function allComponentsAreNumbers(): bool

return true;
}

/**
* Note that this method assumes the following:
* - The `aComponents` array has keys for `r`, `g` and `b`;
* - The values in the array are all instances of `Size`.
*
* Errors will be triggered or thrown if this is not the case.
*
* @return non-empty-string
*/
private function renderAsHex(): string
{
$result = \sprintf(
'%02x%02x%02x',
$this->aComponents['r']->getSize(),
$this->aComponents['g']->getSize(),
$this->aComponents['b']->getSize()
);
$canUseShortVariant = ($result[0] == $result[1]) && ($result[2] == $result[3]) && ($result[4] == $result[5]);

return '#' . ($canUseShortVariant ? $result[0] . $result[2] . $result[4] : $result);
}
}