Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
24 / 24 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| TwigExtension | |
100.00% |
24 / 24 |
|
100.00% |
4 / 4 |
8 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| priceFilter | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
3 | |||
| formatRUC | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| intlDate | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Twig\Extension; |
| 6 | |
| 7 | use App\Entity\User; |
| 8 | use App\Service\TextFormatter; |
| 9 | use DateTime; |
| 10 | use Exception; |
| 11 | use IntlDateFormatter; |
| 12 | use Twig\Attribute\AsTwigFilter; |
| 13 | use Twig\Attribute\AsTwigFunction; |
| 14 | |
| 15 | class TwigExtension |
| 16 | { |
| 17 | public function __construct(private readonly TextFormatter $textFormatter) {} |
| 18 | |
| 19 | #[AsTwigFilter('price')] |
| 20 | public function priceFilter( |
| 21 | float|null $number, |
| 22 | int $decimals = 2, |
| 23 | string $decPoint = '.', |
| 24 | string $thousandsSep = ',' |
| 25 | ): string |
| 26 | { |
| 27 | $price = $number ? number_format( |
| 28 | $number, |
| 29 | $decimals, |
| 30 | $decPoint, |
| 31 | $thousandsSep |
| 32 | ) : 0; |
| 33 | |
| 34 | return sprintf( |
| 35 | '<span class="%s">%s</span>', |
| 36 | $price < 0 ? 'amount amount-red' : 'amount', |
| 37 | $price |
| 38 | ); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Cleanup a long number and make it readable. |
| 43 | */ |
| 44 | #[AsTwigFunction('formatRUC')] |
| 45 | public function formatRUC(User $user): string |
| 46 | { |
| 47 | return $this->textFormatter->formatRUC($user); |
| 48 | } |
| 49 | |
| 50 | #[AsTwigFunction('intlDate')] |
| 51 | public function intlDate( |
| 52 | string|DateTime $date, |
| 53 | string $format = "d 'de' MMMM YYYY", |
| 54 | string $lang = 'es_ES' |
| 55 | ): string |
| 56 | { |
| 57 | $formatter = new IntlDateFormatter( |
| 58 | 'es_ES', |
| 59 | IntlDateFormatter::LONG, |
| 60 | IntlDateFormatter::NONE |
| 61 | ); |
| 62 | |
| 63 | if ($date instanceof DateTime) { |
| 64 | $dateTime = $date; |
| 65 | } else { |
| 66 | try { |
| 67 | $dateTime = new DateTime($date); |
| 68 | } catch (Exception) { |
| 69 | return $date; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | return $formatter->formatObject($dateTime, $format, $lang); |
| 74 | } |
| 75 | } |