PluginProbe
Booktics – Appointment Booking Calendar for Service Businesses / 1.0.12
Booktics – Appointment Booking Calendar for Service Businesses v1.0.12
1.0.29 1.0.28 1.0.27 1.0.26 1.0.25 1.0.24 1.0.23 1.0.22 1.0.21 1.0.20 1.0.19 trunk 1.0.0 1.0.1 1.0.10 1.0.11 1.0.12 1.0.13 1.0.14 1.0.15 1.0.16 1.0.17 1.0.18 1.0.2 1.0.3 All 31 releases
booktics / core / category / category-hooks.php

category-hooks.php in Booktics – Appointment Booking Calendar for Service Businesses 1.0.12, at core/category/category-hooks.php

93 lines 2.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Booktics\Category;
4
5 use Booktics\Contracts\Hookable_Service_Contract;
6 use Booktics\Models\Service_Model;
7
8 class Category_Hooks implements Hookable_Service_Contract {
9
10 /**
11 * Register the hooks for the category service sync
12 *
13 * @return void
14 */
15 public function register() {
16 add_action(
17 'booktics_category_created', array(
18 $this,
19 'category_service_sync',
20 ), 10, 1
21 );
22 add_action(
23 'booktics_category_updated', array(
24 $this,
25 'category_service_sync',
26 ), 10, 1
27 );
28 }
29
30 /**
31 * Sync the services categories
32 *
33 * @param $category
34 * @return void
35 */
36 public function category_service_sync( $category ) {
37 $this->remove_category_from_unlinked_services( $category->id, $category->services );
38 $this->add_category_to_linked_services( $category->id, $category->services );
39 }
40
41 /**
42 * Remove the category from services that are no longer linked to it
43 *
44 * @param int $category_id
45 * @param array $new_service_ids
46 * @return void
47 */
48 private function remove_category_from_unlinked_services( $category_id, array $new_service_ids ) {
49 $args = array(
50 'meta_query' => array(
51 array(
52 'key' => 'categories',
53 'value' => sprintf( 'i:%d;', intval( $category_id ) ),
54 'compare' => 'LIKE',
55 ),
56 ),
57 );
58
59 $services = Service_Model::all( $args );
60 foreach ( $services as $service ) {
61 if ( $service && ! in_array( $service->id, $new_service_ids ) ) {
62 $categories = $service->categories;
63 $categories = array_diff( $categories, array( $category_id ) );
64 Service_Model::find( $service->id )->update(
65 array(
66 'categories' => array_values( $categories ),
67 )
68 );
69 }
70 }
71 }
72
73 /**
74 * Add the category to all linked services
75 *
76 * @param int $category_id
77 * @param array $service_ids
78 * @return void
79 */
80 private function add_category_to_linked_services( $category_id, array $service_ids ) {
81 foreach ( $service_ids as $service_id ) {
82 $service = Service_Model::find( $service_id );
83 if ( $service ) {
84 $service_categories = $service->categories;
85 if ( ! in_array( $category_id, $service_categories ) ) {
86 $service_categories[] = $category_id;
87 $service->update( array( 'categories' => $service_categories ) );
88 }
89 }
90 }
91 }
92 }
93