PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.5.4
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.5.4
1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 1.3.19 trunk All 48 releases
fluent-cart / api / Taxonomy.php

Taxonomy.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.5.4, at api/Taxonomy.php

318 lines 10.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCart\Api;
4
5 use FluentCart\App\CPT\FluentProducts;
6 use FluentCart\App\Models\WpModels\Term;
7 use FluentCart\Framework\Support\Arr;
8 use FluentCart\Framework\Support\Collection;
9 use FluentCart\Framework\Support\Str;
10
11 class Taxonomy
12 {
13 public static function getTaxonomies($objectType = 'fluent-products', $publicOnly = true): array
14 {
15 $args = [
16 'object_type' => [$objectType]
17 ];
18
19 if ($publicOnly) {
20 $args['public'] = true;
21 }
22
23 return get_taxonomies($args);
24 }
25
26 public static function syncTaxonomyTermsToProduct(
27 $productId, string $taxonomy, array $terms
28 )
29 {
30 if (!is_taxonomy_hierarchical($taxonomy)) {
31 $terms = Term::query()->find($terms)->pluck('name')->toArray();
32 }
33
34 return wp_set_post_terms($productId, $terms, $taxonomy);
35 }
36
37 public static function deleteTaxonomyTermFromProduct(
38 $productId, string $taxonomy, int $term
39 )
40 {
41 return wp_remove_object_terms($productId, $term, $taxonomy);
42 }
43
44 public static function deleteAllTermRelationshipsFromProduct($productId, string $taxonomy)
45 {
46 return wp_delete_object_term_relationships($productId, $taxonomy);
47 }
48
49 public static function getFormattedTerms(
50 $taxonomy,
51 $hideEmpty = false,
52 $parents = null,
53 $valueKey = 'value',
54 $labelKey = 'label',
55 $prefilled = null
56 ): array
57 {
58 $terms = get_terms([
59 'taxonomy' => $taxonomy,
60 'hide_empty' => $hideEmpty,
61 ]);
62
63 if (is_wp_error($terms)) {
64 return [];
65 }
66
67
68 // Stores all terms with an empty children array.
69 $termMap = [];
70
71 foreach ($terms as $term) {
72
73 $termMap[$term->term_id] = [
74 $valueKey => (string)$term->term_id,
75 $labelKey => $term->name,
76 'parent' => (string)$term->parent,
77 'children' => []
78 ];
79 }
80
81 // Organize terms into a nested parent-child structure
82 // Iterates through $termMap and attaches each child term to its parent’s children array.
83 $formattedTerms = [];
84
85 foreach ($termMap as &$term) {
86 // If the term has a parent and the parent exists in termMap, add it as a child
87 if ($term['parent'] != "0" && isset($termMap[$term['parent']])) {
88 $termMap[$term['parent']]['children'][] = &$term;
89 } else {
90 // Otherwise, add it to the top-level array (root categories)
91 $formattedTerms[] = &$term;
92 }
93 }
94
95 // Mark prefilled terms as selected
96 // Adds a selected key if the term ID is found in $prefilled.
97 if (!empty($prefilled)) {
98 foreach ($formattedTerms as &$term) {
99 // Check if the current term should be selected
100 if (isset($term['value'])) {
101 $term['selected'] = (is_array($prefilled) && in_array($term['value'], $prefilled)) || $term['value'] == $prefilled;
102 }
103
104 // If the term has children, apply the same logic recursively
105 if (!empty($term['children'])) {
106 foreach ($term['children'] as &$childTerm) {
107 // Check if the child term should be selected
108 if (isset($childTerm['value'])) {
109 $childTerm['selected'] = (is_array($prefilled) && in_array($childTerm['value'], $prefilled)) || $childTerm['value'] == $prefilled;
110 }
111 }
112 }
113 }
114
115 }
116
117 return $formattedTerms;
118 }
119
120 public static function getTermIdsFromTerms(array $terms): array
121 {
122 return Collection::make($terms)->pluck('term_id')->toArray();
123 }
124
125 public static function getTermIdsBySlugs($slugs, $taxonomy = 'product-categories'): array
126 {
127 if (is_string($slugs)) {
128 $slugs = array_map('trim', explode(',', $slugs));
129 }
130
131 $termIds = [];
132 foreach ($slugs as $slug) {
133 $slug = sanitize_text_field($slug);
134 if (empty($slug)) {
135 continue;
136 }
137 $term = get_term_by('slug', sanitize_title($slug), $taxonomy);
138 if (!$term || is_wp_error($term)) {
139 $term = get_term_by('name', $slug, $taxonomy);
140 }
141 if ($term && !is_wp_error($term)) {
142 $termIds[] = (int) $term->term_id;
143 }
144 }
145
146 return $termIds;
147 }
148
149 public static function addTaxonomyTerms(string $taxonomy, array $terms, array $args = [])
150 {
151 $taxonomies = static::getTaxonomies();
152 if (!Arr::has($taxonomies, $taxonomy)) {
153 return false;
154 }
155
156 $termIds = [];
157
158 foreach ($terms as $term) {
159 if (term_exists($term, $taxonomy)) {
160 $termIds[] = get_term_by('name', $term, $taxonomy)->term_id;
161 } else if (is_array($newTerm = wp_insert_term($term, $taxonomy, $args))) {
162 $termIds[] = $newTerm['term_id'];
163 }
164 }
165
166 return $termIds;
167 }
168
169 public static function getTaxonomyLabels($taxonomy, $keys = [])
170 {
171 $taxonomy_object = get_taxonomy($taxonomy);
172
173 if ($taxonomy_object) {
174 // Get all labels as an array
175 $all_labels = (array)get_taxonomy_labels($taxonomy_object);
176
177 $desired_keys = [
178 'all_items',
179 'add_new_item',
180 'edit_item',
181 'name',
182 'not_found',
183 'parent_item',
184 'search_items',
185 'update_item',
186 'view_item',
187 'singular_name',
188 'no_terms',
189 ];
190
191 $desired_keys = Arr::mergeMissingValues($desired_keys, $keys);
192
193 $collectionInstance = new Collection($all_labels);
194 $labels = $collectionInstance->only($desired_keys)->toArray();
195 } else {
196 $labels = $keys;
197 }
198
199 return $labels;
200 }
201
202
203 public static function fetchTaxonomies($data): ?array
204 {
205 $search = sanitize_text_field(Arr::get($data, 'search', ''));
206 $page = (int)sanitize_text_field(Arr::get($data, 'page', 1));
207 $per_page = (int)sanitize_text_field(Arr::get($data, 'per_page', 10));
208 $sort_by = sanitize_text_field(Arr::get($data, 'sort_by', 'name'));
209 $sort_type = sanitize_text_field(Arr::get($data, 'sort_type', 'DESC'));
210 $taxonomy = sanitize_text_field(Arr::get($data, 'taxonomy', 'product-categories'));
211
212 $offset = ($page - 1) * $per_page;
213
214 $total = (int)wp_count_terms(['taxonomy' => $taxonomy, 'hide_empty' => false]);
215
216 if (!empty($search)) {
217 $search_results = get_terms([
218 'taxonomy' => $taxonomy,
219 'hide_empty' => false,
220 'search' => $search,
221 'fields' => 'ids',
222 ]);
223
224 if (is_wp_error($search_results)) {
225 wp_send_json([
226 'message' => __('Failed to fetch search results.', 'fluent-cart'),
227 ], 500);
228 }
229
230 $total = count($search_results);
231 }
232
233 $labels = self::getTaxonomyLabels($taxonomy);
234
235 $terms = get_terms([
236 'taxonomy' => $taxonomy,
237 'hide_empty' => false,
238 'orderby' => $sort_by,
239 'order' => $sort_type,
240 'number' => $per_page,
241 'offset' => $offset,
242 'search' => $search
243 ]);
244
245 if (is_wp_error($terms)) {
246 return wp_send_json([
247 /* translators: %s - taxonomy name */
248 'message' => sprintf(__('Failed to fetch %s.', 'fluent-cart'), Str::lower($labels['name'])),
249 ], 500);
250 }
251
252 // Initialize an array to hold the terms by their IDs
253 $terms_by_id = [];
254 foreach ($terms as $term) {
255 $terms_by_id[$term->term_id] = [
256 'term_id' => $term->term_id,
257 'name' => $term->name,
258 'description' => $term->description,
259 'slug' => $term->slug,
260 'parent' => $term->parent,
261 'count' => $term->count,
262 'children' => [],
263 'url' => get_term_link($term->term_id),
264 ];
265 }
266
267 // Build the hierarchy
268 $hierarchy = [];
269 foreach ($terms_by_id as $term_id => &$term_data) {
270 // If the term has a parent and the parent exists in the array, add it to the parent's children.
271 if ($term_data['parent'] && isset($terms_by_id[$term_data['parent']])) {
272 $terms_by_id[$term_data['parent']]['children'][] = &$term_data;
273 } else {
274 // If the term has no parent, it is added as a top-level category.
275 $hierarchy[] = &$term_data;
276 }
277 }
278
279 // Calculate total pages
280 $last_page = ceil($total / $per_page);
281
282 // Calculate "from" and "to"
283 $from = ($total > 0) ? (($page - 1) * $per_page) + 1 : 0;
284 $to = min($page * $per_page, $total);
285
286 return [
287 "taxonomies" => [
288 "data" => $hierarchy,
289 "total" => $total,
290 "current_page" => $page,
291 "last_page" => $last_page,
292 "per_page" => $per_page,
293 "from" => $from,
294 "to" => $to,
295 "labels" => $labels,
296 ],
297 ];
298 }
299
300
301 public static function taxonomyWithTerms(): Collection
302 {
303 $taxonomies = Taxonomy::getTaxonomies();
304
305 return Collection::make($taxonomies)
306 ->map(function ($taxonomy) {
307 return [
308 'name' => $taxonomy,
309 'label' => Str::headline($taxonomy),
310 'parent' => 0,
311 'terms' => Taxonomy::getFormattedTerms($taxonomy, false, null, 'value', 'label'),
312 ];
313 });
314
315 }
316
317 }
318