Skip to content

Instantly share code, notes, and snippets.

@mateusjunges
Created May 27, 2022 02:17
Show Gist options
  • Save mateusjunges/ef0e3582277265ec4d8ee2d1b7e046be to your computer and use it in GitHub Desktop.
Save mateusjunges/ef0e3582277265ec4d8ee2d1b7e046be to your computer and use it in GitHub Desktop.
<?php
class Solution
{
protected Converter $converter;
public function __construct(
protected string $hexColorOne,
protected string $hexColorTwo
){
$this->converter = new Converter();
}
public function averageColor(): string
{
$colorOne = $this->converter->hex2Rgb($this->hexColorOne);
$colorTwo = $this->converter->hex2Rgb($this->hexColorTwo);
$rgbMean = [];
for ($i = 0; $i < 3; $i++) {
$rgbMean[] = ($colorOne[$i] + $colorTwo[$i]) / 2;
}
return $this->converter->rgbToHex($rgbMean);
}
}
class Converter
{
public function hex2Rgb(string $hexColorCode): array
{
return sscanf($hexColorCode, '%02x%02x%02x');
}
public function rgbToHex(array $rgb): string
{
$hex = [];
foreach ($rgb as $value) {
$hex[] = str_pad(dechex($value), 2,'0', STR_PAD_LEFT);
}
return implode('', $hex);
}
}
echo (new Solution('ffffff', 'ff00ff00'))->averageColor() . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment