88 lines
2.4 KiB
PHP
88 lines
2.4 KiB
PHP
<?php
|
|
namespace YTKNS;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
final class Gradient {
|
|
private int $direction = 0;
|
|
private array $points = [];
|
|
|
|
public function getArray(): array {
|
|
$arr = [
|
|
'd' => $this->getDirection(),
|
|
'p' => [],
|
|
];
|
|
|
|
foreach($this->getPoints() as $point)
|
|
$arr['p'][] = $point->getArray();
|
|
|
|
return $arr;
|
|
}
|
|
|
|
public static function fromArray($array): ?self {
|
|
$gradient = new static;
|
|
|
|
if(!empty($array)) {
|
|
if(is_string($array))
|
|
$array = json_decode($array);
|
|
if(is_object($array))
|
|
$array = (array)$array;
|
|
if(is_array($array)) {
|
|
if(isset($array['d']) && is_int($array['d']))
|
|
$gradient->setDirection($array['d']);
|
|
|
|
if(isset($array['p']) && is_array($array['p'])) {
|
|
$gradient->resetPoints();
|
|
|
|
foreach($array['p'] as $point)
|
|
$gradient->addPoint(GradientPoint::fromArray($point));
|
|
}
|
|
}
|
|
}
|
|
|
|
if(count($gradient->points) < 2)
|
|
return null;
|
|
|
|
return $gradient;
|
|
}
|
|
|
|
public function getCSS(): string {
|
|
$points = [];
|
|
|
|
foreach($this->points as $point)
|
|
$points[] = $point->getCSS();
|
|
|
|
return sprintf('linear-gradient(%ddeg, %s)', $this->getDirection(), implode(', ', $points));
|
|
}
|
|
|
|
public function getDirection(): int {
|
|
return $this->direction;
|
|
}
|
|
public function setDirection(int $dir): self {
|
|
if($dir < 0 || $dir > 359)
|
|
throw new InvalidArgumentException('dir must be between 0 and 359.');
|
|
$this->direction = $dir;
|
|
return $this;
|
|
}
|
|
|
|
public function getPoints(): array {
|
|
return $this->points;
|
|
}
|
|
|
|
public function addPoint(GradientPoint $point): self {
|
|
if(!in_array($point, $this->points))
|
|
$this->points[] = $point;
|
|
return $this;
|
|
}
|
|
public function removePoint(GradientPoint $point): self {
|
|
$index = array_search($point, $this->points);
|
|
if($index !== null)
|
|
unset($this->points[$index]);
|
|
return $this;
|
|
}
|
|
public function resetPoints(): self {
|
|
$this->points = [];
|
|
return $this;
|
|
}
|
|
}
|