70 lines
2.6 KiB
PHP
70 lines
2.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Pcm\BadgeBundle\Twig\Component;
|
|
|
|
use Pcm\BadgeBundle\Enum\BadgeColour;
|
|
use Pcm\BadgeBundle\Interface\BadgeableInterface;
|
|
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;
|
|
use TailwindMerge\TailwindMerge;
|
|
|
|
#[AsTwigComponent(name: 'Pcm:Badge', template: '@PcmBadge/Badge.html.twig')]
|
|
final class Badge
|
|
{
|
|
public string $finalClasses;
|
|
public ?string $label = null;
|
|
|
|
public function __construct(private string $baseClasses)
|
|
{
|
|
}
|
|
|
|
/**
|
|
* @param ?BadgeableInterface $obj the object to be converted into a badge
|
|
* @param ?string $class Extra classes to add to the badge element.
|
|
* These will override the base classes in case
|
|
* of conflicts.
|
|
* @param ?string $colour specify the colour of an objectless badge
|
|
* @param bool $outline if the badge should be rendered as an outline
|
|
*/
|
|
public function mount(?BadgeableInterface $obj = null, ?string $class = null, ?string $colour = null, ?string $label = null, bool $outline = false): void
|
|
{
|
|
$this->label = $label;
|
|
|
|
if (!$obj && !$colour) {
|
|
throw new \RuntimeException(sprintf('You must specify either a colour an instance of "%s".', BadgeableInterface::class));
|
|
}
|
|
|
|
if ($obj && $colour) {
|
|
throw new \RuntimeException(sprintf('You have specified both the colour "%s" and an instance of "%s". Please use one or the other.', $colour, $obj::class));
|
|
}
|
|
|
|
if ($obj) {
|
|
$palette = $obj->getBadgeColour()->getPalette();
|
|
}
|
|
|
|
if ($colour) {
|
|
$cases = array_map(fn (BadgeColour $b) => strtolower($b->name), BadgeColour::cases());
|
|
|
|
if (!in_array($colour, $cases)) {
|
|
$formattedCases = implode(', ', array_map(fn (string $s) => '"'.$s.'"', $cases));
|
|
throw new \RuntimeException(sprintf('"%s" is not a valid badge colour. Available options are: %s.', $colour, $formattedCases));
|
|
}
|
|
|
|
$colour = strtoupper($colour);
|
|
$palette = BadgeColour::{$colour}->getPalette();
|
|
}
|
|
|
|
$merger = TailwindMerge::instance();
|
|
|
|
if (true === $outline) {
|
|
$classes = sprintf('bg-white %s %s %s %s', $palette->borderColourClass, $palette->textColourClass, $this->baseClasses, $class);
|
|
} else {
|
|
$classes = sprintf('text-white %s %s %s %s', $palette->borderColourClass, $palette->backgroundColourClass, $this->baseClasses, $class);
|
|
}
|
|
|
|
$this->finalClasses = $merger->merge(trim($classes));
|
|
}
|
|
}
|
|
|