TermProperty.php
43 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace AC\Formatter\Term; |
| 6 | |
| 7 | use AC\Exception\ValueNotFoundException; |
| 8 | use AC\Formatter; |
| 9 | use AC\Type\Value; |
| 10 | use WP_Term; |
| 11 | |
| 12 | class TermProperty implements Formatter |
| 13 | { |
| 14 | |
| 15 | private string $field; |
| 16 | |
| 17 | public function __construct(string $field) |
| 18 | { |
| 19 | $this->field = $field; |
| 20 | } |
| 21 | |
| 22 | public function format(Value $value): Value |
| 23 | { |
| 24 | $term = get_term($value->get_id()); |
| 25 | |
| 26 | if ( ! $term instanceof WP_Term) { |
| 27 | throw ValueNotFoundException::from_id($value->get_id()); |
| 28 | } |
| 29 | |
| 30 | $field = $term->{$this->field} ?? null; |
| 31 | |
| 32 | if (null === $field) { |
| 33 | throw ValueNotFoundException::from_id($value->get_id()); |
| 34 | } |
| 35 | |
| 36 | switch ($this->field) { |
| 37 | case 'parent': |
| 38 | return new Value((int)$field); |
| 39 | default: |
| 40 | return $value->with_value($field); |
| 41 | } |
| 42 | } |
| 43 | } |