CustomerFieldsFactory.php
11 months ago
CustomerOrderFieldsFactory.php
1 year ago
CustomerReviewFieldsFactory.php
1 year ago
CustomerSubscriptionFieldsFactory.php
11 months ago
OrderFieldsFactory.php
2 months ago
TermOptionsBuilder.php
2 years ago
TermParentsLoader.php
1 year ago
index.php
3 years ago
TermOptionsBuilder.php
70 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Automation\Integrations\WooCommerce\Fields; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Automation\Engine\WordPress; |
| 9 | use WP_Error; |
| 10 | use WP_Term; |
| 11 | |
| 12 | class TermOptionsBuilder { |
| 13 | /** @var WordPress */ |
| 14 | private $wordPress; |
| 15 | |
| 16 | /** @var array<string, array<array{id: int, name: string}>> */ |
| 17 | private $cache = []; |
| 18 | |
| 19 | public function __construct( |
| 20 | WordPress $wordPress |
| 21 | ) { |
| 22 | $this->wordPress = $wordPress; |
| 23 | } |
| 24 | |
| 25 | /** @return array<array{id: int, name: string}> */ |
| 26 | public function getTermOptions(string $taxonomy): array { |
| 27 | if (!isset($this->cache[$taxonomy])) { |
| 28 | $this->cache[$taxonomy] = $this->fetchTermOptions($taxonomy); |
| 29 | } |
| 30 | return $this->cache[$taxonomy]; |
| 31 | } |
| 32 | |
| 33 | public function resetCache(): void { |
| 34 | $this->cache = []; |
| 35 | } |
| 36 | |
| 37 | /** @return array<array{id: int, name: string}> */ |
| 38 | private function fetchTermOptions(string $taxonomy): array { |
| 39 | /** @var WP_Term[]|WP_Error $terms */ |
| 40 | $terms = $this->wordPress->getTerms(['taxonomy' => $taxonomy, 'hide_empty' => false, 'orderby' => 'name']); |
| 41 | if ($terms instanceof WP_Error) { |
| 42 | return []; |
| 43 | } |
| 44 | |
| 45 | $termsMap = []; |
| 46 | foreach ($terms as $term) { |
| 47 | $termsMap[$term->parent][] = $term; |
| 48 | } |
| 49 | return $this->buildTermsList($termsMap); |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * @param array<int, array<WP_Term>> $termsMap |
| 54 | * @return array<array{id: int, name: string}> |
| 55 | */ |
| 56 | private function buildTermsList(array $termsMap, int $parentId = 0): array { |
| 57 | $list = []; |
| 58 | foreach ($termsMap[$parentId] ?? [] as $term) { |
| 59 | $id = $term->term_id; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps |
| 60 | $list[] = ['id' => $id, 'name' => $term->name]; |
| 61 | if (isset($termsMap[$id])) { |
| 62 | foreach ($this->buildTermsList($termsMap, $id) as $child) { |
| 63 | $list[] = ['id' => $child['id'], 'name' => "$term->name | {$child['name']}"]; |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | return $list; |
| 68 | } |
| 69 | } |
| 70 |