|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * League.Csv (https://csv.thephpleague.com) |
| 5 | + * |
| 6 | + * (c) Ignace Nyamagana Butera <nyamsprod@gmail.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace League\Csv\Inspection\Calculator; |
| 15 | + |
| 16 | +use DateTimeInterface; |
| 17 | +use League\Csv\Inspection\Strategy\DateFieldStrategy; |
| 18 | +use League\Csv\Inspection\Strategy\FieldStrategy; |
| 19 | +use League\Csv\Inspection\Strategy\NumericFieldStrategy; |
| 20 | +use ValueError; |
| 21 | + |
| 22 | +use function is_numeric; |
| 23 | +use function trim; |
| 24 | + |
| 25 | +final class MaxFieldCalculator implements FieldCalculator |
| 26 | +{ |
| 27 | + /** @var non-empty-string */ |
| 28 | + public readonly string $name; |
| 29 | + /** @var DateTimeInterface|float|null */ |
| 30 | + private mixed $value; |
| 31 | + private ?string $type; |
| 32 | + |
| 33 | + public function __construct(string $name = 'max') |
| 34 | + { |
| 35 | + '' !== ($name = trim($name)) || throw new ValueError('The calculator name cannot be empty.'); |
| 36 | + $this->name = $name; |
| 37 | + $this->reset(); |
| 38 | + } |
| 39 | + |
| 40 | + public function supports(FieldStrategy $strategy): bool |
| 41 | + { |
| 42 | + return match ($strategy::class) { |
| 43 | + NumericFieldStrategy::class, |
| 44 | + DateFieldStrategy::class => true, |
| 45 | + default => false, |
| 46 | + }; |
| 47 | + } |
| 48 | + |
| 49 | + public function reset(): void |
| 50 | + { |
| 51 | + $this->value = null; |
| 52 | + $this->type = null; |
| 53 | + } |
| 54 | + |
| 55 | + public function name(): string |
| 56 | + { |
| 57 | + return $this->name; |
| 58 | + } |
| 59 | + |
| 60 | + public function push(mixed $value): void |
| 61 | + { |
| 62 | + $type = null; |
| 63 | + if (is_numeric($value)) { |
| 64 | + $type = 'numeric'; |
| 65 | + $value = (float) $value; |
| 66 | + } elseif ($value instanceof DateTimeInterface) { |
| 67 | + $type = 'date'; |
| 68 | + } |
| 69 | + |
| 70 | + if (null === $type) { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + $this->type ??= $type; |
| 75 | + if ($type !== $this->type) { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + if (null === $this->value || $value > $this->value) { |
| 80 | + $this->value = $value; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * @return DateTimeInterface|float|null |
| 86 | + */ |
| 87 | + public function calculate(): mixed |
| 88 | + { |
| 89 | + return $this->value; |
| 90 | + } |
| 91 | +} |
0 commit comments