Completed
Push — master ( 292abe...495771 )
by Naveen
01:12
created
recipe-maker/class-recipe-maker-entity-type-procedure.php 2 patches
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -11,35 +11,35 @@
 block discarded – undo
11 11
  */
12 12
 class Recipe_Maker_Entity_Type_Procedure {
13 13
 
14
-	/**
15
-	 * Run the procedure and set all wprecipe post type
16
-	 * to 'Recipe' in entity type.
17
-	 */
18
-	public function run_procedure() {
19
-		$posts = $this->get_all_published_recipe_maker_posts();
20
-		foreach ( $posts as $post_id ) {
21
-			// set entity type to Product.
22
-			\Wordlift_Entity_Type_Service::get_instance()
23
-										->set(
24
-											$post_id,
25
-											'http://schema.org/Recipe',
26
-											true
27
-										);
28
-		}
29
-	}
14
+    /**
15
+     * Run the procedure and set all wprecipe post type
16
+     * to 'Recipe' in entity type.
17
+     */
18
+    public function run_procedure() {
19
+        $posts = $this->get_all_published_recipe_maker_posts();
20
+        foreach ( $posts as $post_id ) {
21
+            // set entity type to Product.
22
+            \Wordlift_Entity_Type_Service::get_instance()
23
+                                        ->set(
24
+                                            $post_id,
25
+                                            'http://schema.org/Recipe',
26
+                                            true
27
+                                        );
28
+        }
29
+    }
30 30
 
31
-	/**
32
-	 * @return int[]|\WP_Post[]
33
-	 */
34
-	private function get_all_published_recipe_maker_posts() {
35
-		return get_posts(
36
-			array(
37
-				'post_type'      => Recipe_Maker_Post_Type_Hook::RECIPE_MAKER_POST_TYPE,
38
-				'posts_per_page' => - 1,
39
-				'post_status'    => 'publish',
40
-				'fields'         => 'ids',
41
-			)
42
-		);
43
-	}
31
+    /**
32
+     * @return int[]|\WP_Post[]
33
+     */
34
+    private function get_all_published_recipe_maker_posts() {
35
+        return get_posts(
36
+            array(
37
+                'post_type'      => Recipe_Maker_Post_Type_Hook::RECIPE_MAKER_POST_TYPE,
38
+                'posts_per_page' => - 1,
39
+                'post_status'    => 'publish',
40
+                'fields'         => 'ids',
41
+            )
42
+        );
43
+    }
44 44
 
45 45
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 	 */
18 18
 	public function run_procedure() {
19 19
 		$posts = $this->get_all_published_recipe_maker_posts();
20
-		foreach ( $posts as $post_id ) {
20
+		foreach ($posts as $post_id) {
21 21
 			// set entity type to Product.
22 22
 			\Wordlift_Entity_Type_Service::get_instance()
23 23
 										->set(
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 		return get_posts(
36 36
 			array(
37 37
 				'post_type'      => Recipe_Maker_Post_Type_Hook::RECIPE_MAKER_POST_TYPE,
38
-				'posts_per_page' => - 1,
38
+				'posts_per_page' => -1,
39 39
 				'post_status'    => 'publish',
40 40
 				'fields'         => 'ids',
41 41
 			)
Please login to merge, or discard this patch.
recipe-maker/class-recipe-maker-after-get-jsonld-hook.php 2 patches
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -16,60 +16,60 @@
 block discarded – undo
16 16
  */
17 17
 class Recipe_Maker_After_Get_Jsonld_Hook {
18 18
 
19
-	/**
20
-	 * @var Recipe_Maker_Validation_Service
21
-	 */
22
-	private $recipe_maker_validation_service;
19
+    /**
20
+     * @var Recipe_Maker_Validation_Service
21
+     */
22
+    private $recipe_maker_validation_service;
23 23
 
24
-	public function __construct( $recipe_maker_validation_service ) {
25
-		$this->recipe_maker_validation_service = $recipe_maker_validation_service;
26
-		// Add the filter to alter final jsonld.
27
-		add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
28
-	}
24
+    public function __construct( $recipe_maker_validation_service ) {
25
+        $this->recipe_maker_validation_service = $recipe_maker_validation_service;
26
+        // Add the filter to alter final jsonld.
27
+        add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
28
+    }
29 29
 
30
-	/**
31
-	 * Add isPartOf to all the recipes.
32
-	 *
33
-	 * @param $jsonld array
34
-	 *
35
-	 * @param $post_id int
36
-	 *
37
-	 * @return array The altered jsonld array.
38
-	 */
39
-	public function wl_after_get_jsonld( $jsonld, $post_id ) {
40
-		if ( ! is_array( $jsonld ) || count( $jsonld ) === 0 ) {
41
-			return $jsonld;
42
-		}
43
-		// If there are no recipes in the post then dont alter the jsonld.
44
-		if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post( $post_id ) ) {
45
-			return $jsonld;
46
-		}
30
+    /**
31
+     * Add isPartOf to all the recipes.
32
+     *
33
+     * @param $jsonld array
34
+     *
35
+     * @param $post_id int
36
+     *
37
+     * @return array The altered jsonld array.
38
+     */
39
+    public function wl_after_get_jsonld( $jsonld, $post_id ) {
40
+        if ( ! is_array( $jsonld ) || count( $jsonld ) === 0 ) {
41
+            return $jsonld;
42
+        }
43
+        // If there are no recipes in the post then dont alter the jsonld.
44
+        if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post( $post_id ) ) {
45
+            return $jsonld;
46
+        }
47 47
 
48
-		// We remove the current post jsonld.
49
-		$post_jsonld    = array_shift( $jsonld );
50
-		$post_jsonld_id = array_key_exists( '@id', $post_jsonld ) ? $post_jsonld['@id'] : false;
48
+        // We remove the current post jsonld.
49
+        $post_jsonld    = array_shift( $jsonld );
50
+        $post_jsonld_id = array_key_exists( '@id', $post_jsonld ) ? $post_jsonld['@id'] : false;
51 51
 
52
-		if ( ! $post_jsonld_id ) {
53
-			return $jsonld;
54
-		}
52
+        if ( ! $post_jsonld_id ) {
53
+            return $jsonld;
54
+        }
55 55
 
56
-		foreach ( $jsonld as $key => $value ) {
57
-			if ( ! array_key_exists( '@type', $value ) ) {
58
-				continue;
59
-			}
60
-			$type = $value['@type'];
61
-			if ( 'Recipe' === $type ) {
62
-				$value['isPartOf'] = array(
63
-					'@id' => $post_jsonld_id,
64
-				);
65
-				$jsonld[ $key ]    = $value;
66
-			}
67
-		}
56
+        foreach ( $jsonld as $key => $value ) {
57
+            if ( ! array_key_exists( '@type', $value ) ) {
58
+                continue;
59
+            }
60
+            $type = $value['@type'];
61
+            if ( 'Recipe' === $type ) {
62
+                $value['isPartOf'] = array(
63
+                    '@id' => $post_jsonld_id,
64
+                );
65
+                $jsonld[ $key ]    = $value;
66
+            }
67
+        }
68 68
 
69
-		// Add back the post jsonld to first of array.
70
-		array_unshift( $jsonld, $post_jsonld );
69
+        // Add back the post jsonld to first of array.
70
+        array_unshift( $jsonld, $post_jsonld );
71 71
 
72
-		return $jsonld;
73
-	}
72
+        return $jsonld;
73
+    }
74 74
 
75 75
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -21,10 +21,10 @@  discard block
 block discarded – undo
21 21
 	 */
22 22
 	private $recipe_maker_validation_service;
23 23
 
24
-	public function __construct( $recipe_maker_validation_service ) {
24
+	public function __construct($recipe_maker_validation_service) {
25 25
 		$this->recipe_maker_validation_service = $recipe_maker_validation_service;
26 26
 		// Add the filter to alter final jsonld.
27
-		add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
27
+		add_filter('wl_after_get_jsonld', array($this, 'wl_after_get_jsonld'), 10, 2);
28 28
 	}
29 29
 
30 30
 	/**
@@ -36,38 +36,38 @@  discard block
 block discarded – undo
36 36
 	 *
37 37
 	 * @return array The altered jsonld array.
38 38
 	 */
39
-	public function wl_after_get_jsonld( $jsonld, $post_id ) {
40
-		if ( ! is_array( $jsonld ) || count( $jsonld ) === 0 ) {
39
+	public function wl_after_get_jsonld($jsonld, $post_id) {
40
+		if ( ! is_array($jsonld) || count($jsonld) === 0) {
41 41
 			return $jsonld;
42 42
 		}
43 43
 		// If there are no recipes in the post then dont alter the jsonld.
44
-		if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post( $post_id ) ) {
44
+		if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post($post_id)) {
45 45
 			return $jsonld;
46 46
 		}
47 47
 
48 48
 		// We remove the current post jsonld.
49
-		$post_jsonld    = array_shift( $jsonld );
50
-		$post_jsonld_id = array_key_exists( '@id', $post_jsonld ) ? $post_jsonld['@id'] : false;
49
+		$post_jsonld    = array_shift($jsonld);
50
+		$post_jsonld_id = array_key_exists('@id', $post_jsonld) ? $post_jsonld['@id'] : false;
51 51
 
52
-		if ( ! $post_jsonld_id ) {
52
+		if ( ! $post_jsonld_id) {
53 53
 			return $jsonld;
54 54
 		}
55 55
 
56
-		foreach ( $jsonld as $key => $value ) {
57
-			if ( ! array_key_exists( '@type', $value ) ) {
56
+		foreach ($jsonld as $key => $value) {
57
+			if ( ! array_key_exists('@type', $value)) {
58 58
 				continue;
59 59
 			}
60 60
 			$type = $value['@type'];
61
-			if ( 'Recipe' === $type ) {
61
+			if ('Recipe' === $type) {
62 62
 				$value['isPartOf'] = array(
63 63
 					'@id' => $post_jsonld_id,
64 64
 				);
65
-				$jsonld[ $key ]    = $value;
65
+				$jsonld[$key]    = $value;
66 66
 			}
67 67
 		}
68 68
 
69 69
 		// Add back the post jsonld to first of array.
70
-		array_unshift( $jsonld, $post_jsonld );
70
+		array_unshift($jsonld, $post_jsonld);
71 71
 
72 72
 		return $jsonld;
73 73
 	}
Please login to merge, or discard this patch.
wordlift/external-plugin-hooks/recipe-maker/class-recipe-maker-warning.php 2 patches
Indentation   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -11,102 +11,102 @@
 block discarded – undo
11 11
  */
12 12
 class Recipe_Maker_Warning {
13 13
 
14
-	/**
15
-	 * @var Recipe_Maker_Validation_Service
16
-	 */
17
-	private $recipe_maker_validation_service;
18
-
19
-	public function __construct( $recipe_maker_validation_service ) {
20
-		$this->recipe_maker_validation_service = $recipe_maker_validation_service;
21
-		/**
22
-		 * Filter: wl_feature__enable__notices.
23
-		 *
24
-		 * @param bool whether the notices needs to be enabled or not.
25
-		 *
26
-		 * @return bool
27
-		 * @since 3.27.6
28
-		 */
29
-		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
30
-			add_action( 'admin_notices', array( $this, 'display_image_size_warning' ) );
31
-		}
32
-	}
33
-
34
-	/**
35
-	 * Show the warning after applying the conditions.
36
-	 */
37
-	public function display_image_size_warning() {
38
-
39
-		// Check if we are on the post.
40
-		if ( ! get_post() instanceof \WP_Post ) {
41
-			return false;
42
-		}
43
-		if ( ! $this->recipe_maker_validation_service->is_wp_recipe_maker_available() ) {
44
-			return false;
45
-		}
46
-		$post_id = get_the_ID();
47
-
48
-		// Dont show notification if there is no recipes referred by the post.
49
-		if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post( $post_id ) ) {
50
-			return false;
51
-		}
52
-
53
-		$recipe_with_image_warnings = $this->get_warnings( $post_id );
54
-
55
-		if ( count( $recipe_with_image_warnings ) > 0 ) {
56
-			// Show notification.
57
-			?>
14
+    /**
15
+     * @var Recipe_Maker_Validation_Service
16
+     */
17
+    private $recipe_maker_validation_service;
18
+
19
+    public function __construct( $recipe_maker_validation_service ) {
20
+        $this->recipe_maker_validation_service = $recipe_maker_validation_service;
21
+        /**
22
+         * Filter: wl_feature__enable__notices.
23
+         *
24
+         * @param bool whether the notices needs to be enabled or not.
25
+         *
26
+         * @return bool
27
+         * @since 3.27.6
28
+         */
29
+        if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
30
+            add_action( 'admin_notices', array( $this, 'display_image_size_warning' ) );
31
+        }
32
+    }
33
+
34
+    /**
35
+     * Show the warning after applying the conditions.
36
+     */
37
+    public function display_image_size_warning() {
38
+
39
+        // Check if we are on the post.
40
+        if ( ! get_post() instanceof \WP_Post ) {
41
+            return false;
42
+        }
43
+        if ( ! $this->recipe_maker_validation_service->is_wp_recipe_maker_available() ) {
44
+            return false;
45
+        }
46
+        $post_id = get_the_ID();
47
+
48
+        // Dont show notification if there is no recipes referred by the post.
49
+        if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post( $post_id ) ) {
50
+            return false;
51
+        }
52
+
53
+        $recipe_with_image_warnings = $this->get_warnings( $post_id );
54
+
55
+        if ( count( $recipe_with_image_warnings ) > 0 ) {
56
+            // Show notification.
57
+            ?>
58 58
 			<div class="notice notice-warning is-dismissible">
59 59
 				<p><?php echo wp_kses( __( 'The following recipes didnt have minimum image size of 1200 x 1200 px', 'wordlift' ), array() ); ?></p>
60 60
 				<ol>
61 61
 					<?php
62
-					foreach ( $recipe_with_image_warnings as $post_id ) {
63
-						echo '<li>' . esc_html( get_the_title( $post_id ) ) . '</li>';
64
-					}
65
-					?>
62
+                    foreach ( $recipe_with_image_warnings as $post_id ) {
63
+                        echo '<li>' . esc_html( get_the_title( $post_id ) ) . '</li>';
64
+                    }
65
+                    ?>
66 66
 				</ol>
67 67
 			</div>
68 68
 			<?php
69
-		}
70
-
71
-	}
72
-
73
-	/**
74
-	 * @param $post_id
75
-	 *
76
-	 * @return array
77
-	 */
78
-	private function get_warnings( $post_id ) {
79
-
80
-		$recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post( $post_id );
81
-
82
-		// Dont show duplicate warnings.
83
-		$recipe_ids = array_unique( $recipe_ids );
84
-
85
-		$recipe_with_image_warnings = array();
86
-
87
-		foreach ( $recipe_ids as $recipe_id ) {
88
-			$recipe = \WPRM_Recipe_Manager::get_recipe( $recipe_id );
89
-			if ( ! $recipe ) {
90
-				continue;
91
-			}
92
-			$image_id   = $recipe->image_id();
93
-			$image_data = wp_get_attachment_image_src( $image_id, array( 1200, 1200 ) );
94
-			if ( ! is_array( $image_data ) ) {
95
-				continue;
96
-			}
97
-			$image_width  = array_key_exists( 1, $image_data ) ? $image_data [1] : false;
98
-			$image_height = array_key_exists( 2, $image_data ) ? $image_data [2] : false;
99
-			if ( ! ( $image_height && $image_width ) ) {
100
-				continue;
101
-			}
102
-
103
-			if ( $image_height < 1200 || $image_width < 1200 ) {
104
-				// Image size not present in 1200 * 1200, show a warning.
105
-				$recipe_with_image_warnings[] = $recipe_id;
106
-			}
107
-		}
108
-
109
-		return $recipe_with_image_warnings;
110
-	}
69
+        }
70
+
71
+    }
72
+
73
+    /**
74
+     * @param $post_id
75
+     *
76
+     * @return array
77
+     */
78
+    private function get_warnings( $post_id ) {
79
+
80
+        $recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post( $post_id );
81
+
82
+        // Dont show duplicate warnings.
83
+        $recipe_ids = array_unique( $recipe_ids );
84
+
85
+        $recipe_with_image_warnings = array();
86
+
87
+        foreach ( $recipe_ids as $recipe_id ) {
88
+            $recipe = \WPRM_Recipe_Manager::get_recipe( $recipe_id );
89
+            if ( ! $recipe ) {
90
+                continue;
91
+            }
92
+            $image_id   = $recipe->image_id();
93
+            $image_data = wp_get_attachment_image_src( $image_id, array( 1200, 1200 ) );
94
+            if ( ! is_array( $image_data ) ) {
95
+                continue;
96
+            }
97
+            $image_width  = array_key_exists( 1, $image_data ) ? $image_data [1] : false;
98
+            $image_height = array_key_exists( 2, $image_data ) ? $image_data [2] : false;
99
+            if ( ! ( $image_height && $image_width ) ) {
100
+                continue;
101
+            }
102
+
103
+            if ( $image_height < 1200 || $image_width < 1200 ) {
104
+                // Image size not present in 1200 * 1200, show a warning.
105
+                $recipe_with_image_warnings[] = $recipe_id;
106
+            }
107
+        }
108
+
109
+        return $recipe_with_image_warnings;
110
+    }
111 111
 
112 112
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -16,7 +16,7 @@  discard block
 block discarded – undo
16 16
 	 */
17 17
 	private $recipe_maker_validation_service;
18 18
 
19
-	public function __construct( $recipe_maker_validation_service ) {
19
+	public function __construct($recipe_maker_validation_service) {
20 20
 		$this->recipe_maker_validation_service = $recipe_maker_validation_service;
21 21
 		/**
22 22
 		 * Filter: wl_feature__enable__notices.
@@ -26,8 +26,8 @@  discard block
 block discarded – undo
26 26
 		 * @return bool
27 27
 		 * @since 3.27.6
28 28
 		 */
29
-		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
30
-			add_action( 'admin_notices', array( $this, 'display_image_size_warning' ) );
29
+		if (apply_filters('wl_feature__enable__notices', true)) {
30
+			add_action('admin_notices', array($this, 'display_image_size_warning'));
31 31
 		}
32 32
 	}
33 33
 
@@ -37,30 +37,30 @@  discard block
 block discarded – undo
37 37
 	public function display_image_size_warning() {
38 38
 
39 39
 		// Check if we are on the post.
40
-		if ( ! get_post() instanceof \WP_Post ) {
40
+		if ( ! get_post() instanceof \WP_Post) {
41 41
 			return false;
42 42
 		}
43
-		if ( ! $this->recipe_maker_validation_service->is_wp_recipe_maker_available() ) {
43
+		if ( ! $this->recipe_maker_validation_service->is_wp_recipe_maker_available()) {
44 44
 			return false;
45 45
 		}
46 46
 		$post_id = get_the_ID();
47 47
 
48 48
 		// Dont show notification if there is no recipes referred by the post.
49
-		if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post( $post_id ) ) {
49
+		if ( ! $this->recipe_maker_validation_service->is_atleast_once_recipe_present_in_the_post($post_id)) {
50 50
 			return false;
51 51
 		}
52 52
 
53
-		$recipe_with_image_warnings = $this->get_warnings( $post_id );
53
+		$recipe_with_image_warnings = $this->get_warnings($post_id);
54 54
 
55
-		if ( count( $recipe_with_image_warnings ) > 0 ) {
55
+		if (count($recipe_with_image_warnings) > 0) {
56 56
 			// Show notification.
57 57
 			?>
58 58
 			<div class="notice notice-warning is-dismissible">
59
-				<p><?php echo wp_kses( __( 'The following recipes didnt have minimum image size of 1200 x 1200 px', 'wordlift' ), array() ); ?></p>
59
+				<p><?php echo wp_kses(__('The following recipes didnt have minimum image size of 1200 x 1200 px', 'wordlift'), array()); ?></p>
60 60
 				<ol>
61 61
 					<?php
62
-					foreach ( $recipe_with_image_warnings as $post_id ) {
63
-						echo '<li>' . esc_html( get_the_title( $post_id ) ) . '</li>';
62
+					foreach ($recipe_with_image_warnings as $post_id) {
63
+						echo '<li>'.esc_html(get_the_title($post_id)).'</li>';
64 64
 					}
65 65
 					?>
66 66
 				</ol>
@@ -75,32 +75,32 @@  discard block
 block discarded – undo
75 75
 	 *
76 76
 	 * @return array
77 77
 	 */
78
-	private function get_warnings( $post_id ) {
78
+	private function get_warnings($post_id) {
79 79
 
80
-		$recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post( $post_id );
80
+		$recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post($post_id);
81 81
 
82 82
 		// Dont show duplicate warnings.
83
-		$recipe_ids = array_unique( $recipe_ids );
83
+		$recipe_ids = array_unique($recipe_ids);
84 84
 
85 85
 		$recipe_with_image_warnings = array();
86 86
 
87
-		foreach ( $recipe_ids as $recipe_id ) {
88
-			$recipe = \WPRM_Recipe_Manager::get_recipe( $recipe_id );
89
-			if ( ! $recipe ) {
87
+		foreach ($recipe_ids as $recipe_id) {
88
+			$recipe = \WPRM_Recipe_Manager::get_recipe($recipe_id);
89
+			if ( ! $recipe) {
90 90
 				continue;
91 91
 			}
92 92
 			$image_id   = $recipe->image_id();
93
-			$image_data = wp_get_attachment_image_src( $image_id, array( 1200, 1200 ) );
94
-			if ( ! is_array( $image_data ) ) {
93
+			$image_data = wp_get_attachment_image_src($image_id, array(1200, 1200));
94
+			if ( ! is_array($image_data)) {
95 95
 				continue;
96 96
 			}
97
-			$image_width  = array_key_exists( 1, $image_data ) ? $image_data [1] : false;
98
-			$image_height = array_key_exists( 2, $image_data ) ? $image_data [2] : false;
99
-			if ( ! ( $image_height && $image_width ) ) {
97
+			$image_width  = array_key_exists(1, $image_data) ? $image_data [1] : false;
98
+			$image_height = array_key_exists(2, $image_data) ? $image_data [2] : false;
99
+			if ( ! ($image_height && $image_width)) {
100 100
 				continue;
101 101
 			}
102 102
 
103
-			if ( $image_height < 1200 || $image_width < 1200 ) {
103
+			if ($image_height < 1200 || $image_width < 1200) {
104 104
 				// Image size not present in 1200 * 1200, show a warning.
105 105
 				$recipe_with_image_warnings[] = $recipe_id;
106 106
 			}
Please login to merge, or discard this patch.
recipe-maker/class-recipe-maker-validation-service.php 2 patches
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -8,31 +8,31 @@
 block discarded – undo
8 8
  */
9 9
 class Recipe_Maker_Validation_Service {
10 10
 
11
-	public function is_atleast_once_recipe_present_in_the_post( $post_id ) {
12
-
13
-		if ( ! $this->is_wp_recipe_maker_available() ) {
14
-			return false;
15
-		}
16
-		$recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post( $post_id );
17
-
18
-		return is_array( $recipe_ids ) ? count( $recipe_ids ) > 0 : false;
19
-	}
20
-
21
-	public function is_wp_recipe_maker_available() {
22
-		/**
23
-		 * Dont alter the jsonld if the classes are not present.
24
-		 */
25
-		if ( ! class_exists( '\WPRM_Recipe_Manager' ) || ! class_exists( 'WPRM_Metadata' ) ) {
26
-			return false;
27
-		}
28
-		if ( ! method_exists( '\WPRM_Recipe_Manager', 'get_recipe_ids_from_post' ) ||
29
-			 ! method_exists( '\WPRM_Recipe_Manager', 'get_recipe' ) ||
30
-			 ! method_exists( '\WPRM_Metadata', 'get_metadata_details' )
31
-		) {
32
-			return false;
33
-		}
34
-
35
-		return true;
36
-	}
11
+    public function is_atleast_once_recipe_present_in_the_post( $post_id ) {
12
+
13
+        if ( ! $this->is_wp_recipe_maker_available() ) {
14
+            return false;
15
+        }
16
+        $recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post( $post_id );
17
+
18
+        return is_array( $recipe_ids ) ? count( $recipe_ids ) > 0 : false;
19
+    }
20
+
21
+    public function is_wp_recipe_maker_available() {
22
+        /**
23
+         * Dont alter the jsonld if the classes are not present.
24
+         */
25
+        if ( ! class_exists( '\WPRM_Recipe_Manager' ) || ! class_exists( 'WPRM_Metadata' ) ) {
26
+            return false;
27
+        }
28
+        if ( ! method_exists( '\WPRM_Recipe_Manager', 'get_recipe_ids_from_post' ) ||
29
+             ! method_exists( '\WPRM_Recipe_Manager', 'get_recipe' ) ||
30
+             ! method_exists( '\WPRM_Metadata', 'get_metadata_details' )
31
+        ) {
32
+            return false;
33
+        }
34
+
35
+        return true;
36
+    }
37 37
 
38 38
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -8,26 +8,26 @@
 block discarded – undo
8 8
  */
9 9
 class Recipe_Maker_Validation_Service {
10 10
 
11
-	public function is_atleast_once_recipe_present_in_the_post( $post_id ) {
11
+	public function is_atleast_once_recipe_present_in_the_post($post_id) {
12 12
 
13
-		if ( ! $this->is_wp_recipe_maker_available() ) {
13
+		if ( ! $this->is_wp_recipe_maker_available()) {
14 14
 			return false;
15 15
 		}
16
-		$recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post( $post_id );
16
+		$recipe_ids = \WPRM_Recipe_Manager::get_recipe_ids_from_post($post_id);
17 17
 
18
-		return is_array( $recipe_ids ) ? count( $recipe_ids ) > 0 : false;
18
+		return is_array($recipe_ids) ? count($recipe_ids) > 0 : false;
19 19
 	}
20 20
 
21 21
 	public function is_wp_recipe_maker_available() {
22 22
 		/**
23 23
 		 * Dont alter the jsonld if the classes are not present.
24 24
 		 */
25
-		if ( ! class_exists( '\WPRM_Recipe_Manager' ) || ! class_exists( 'WPRM_Metadata' ) ) {
25
+		if ( ! class_exists('\WPRM_Recipe_Manager') || ! class_exists('WPRM_Metadata')) {
26 26
 			return false;
27 27
 		}
28
-		if ( ! method_exists( '\WPRM_Recipe_Manager', 'get_recipe_ids_from_post' ) ||
29
-			 ! method_exists( '\WPRM_Recipe_Manager', 'get_recipe' ) ||
30
-			 ! method_exists( '\WPRM_Metadata', 'get_metadata_details' )
28
+		if ( ! method_exists('\WPRM_Recipe_Manager', 'get_recipe_ids_from_post') ||
29
+			 ! method_exists('\WPRM_Recipe_Manager', 'get_recipe') ||
30
+			 ! method_exists('\WPRM_Metadata', 'get_metadata_details')
31 31
 		) {
32 32
 			return false;
33 33
 		}
Please login to merge, or discard this patch.
src/wordlift/webhooks/class-webhooks-manager.php 2 patches
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -11,88 +11,88 @@
 block discarded – undo
11 11
 
12 12
 class Webhooks_Manager {
13 13
 
14
-	/**
15
-	 * Registering the actions to call up sync_many or sync_delete methods
16
-	 */
17
-	public function __construct() {
18
-		add_action( 'wl_sync__sync_many', array( $this, 'sync_many' ), 10 );
19
-		add_action( 'wl_sync__delete_one', array( $this, 'sync_delete' ), 10, 3 );
20
-	}
14
+    /**
15
+     * Registering the actions to call up sync_many or sync_delete methods
16
+     */
17
+    public function __construct() {
18
+        add_action( 'wl_sync__sync_many', array( $this, 'sync_many' ), 10 );
19
+        add_action( 'wl_sync__delete_one', array( $this, 'sync_delete' ), 10, 3 );
20
+    }
21 21
 
22
-	/**
23
-	 * Method to call up webhook with post requested
24
-	 *
25
-	 * @param array $hashes
26
-	 */
27
-	public function sync_many( $hashes ) {
22
+    /**
23
+     * Method to call up webhook with post requested
24
+     *
25
+     * @param array $hashes
26
+     */
27
+    public function sync_many( $hashes ) {
28 28
 
29
-		$urls = explode( "\n", get_option( Webhooks_Loader::URLS_OPTION_NAME, '' ) );
30
-		if ( empty( $urls ) ) {
31
-			return;
32
-		}
29
+        $urls = explode( "\n", get_option( Webhooks_Loader::URLS_OPTION_NAME, '' ) );
30
+        if ( empty( $urls ) ) {
31
+            return;
32
+        }
33 33
 
34
-		/**
35
-		 * Allow 3rd parties to filter out the objects that we want to send via webhooks.
36
-		 *
37
-		 * @since 3.34.0
38
-		 * @var Sync_Object_Adapter[] $filtered_objects
39
-		 */
40
-		$filtered_hashes = apply_filters( 'wl_webhooks__sync_many__objects', $hashes );
34
+        /**
35
+         * Allow 3rd parties to filter out the objects that we want to send via webhooks.
36
+         *
37
+         * @since 3.34.0
38
+         * @var Sync_Object_Adapter[] $filtered_objects
39
+         */
40
+        $filtered_hashes = apply_filters( 'wl_webhooks__sync_many__objects', $hashes );
41 41
 
42
-		foreach ( $urls as $url ) {
43
-			foreach ( $filtered_hashes as $hash ) {
44
-				$jsonld       = $hash[2];
45
-				$filtered_url = apply_filters( 'wl_webhooks__sync_many__url', $url, $hash );
46
-				wp_remote_request(
47
-					$filtered_url,
48
-					apply_filters(
49
-						'wl_webhooks__sync_many__args',
50
-						array(
51
-							'blocking' => false,
52
-							'method'   => 'PUT',
53
-							'headers'  => array( 'content-type' => 'application/json; ' . get_bloginfo( 'charset' ) ),
54
-							'body'     => $jsonld,
55
-						),
56
-						$hash
57
-					)
58
-				);
59
-			}
60
-		}
61
-	}
42
+        foreach ( $urls as $url ) {
43
+            foreach ( $filtered_hashes as $hash ) {
44
+                $jsonld       = $hash[2];
45
+                $filtered_url = apply_filters( 'wl_webhooks__sync_many__url', $url, $hash );
46
+                wp_remote_request(
47
+                    $filtered_url,
48
+                    apply_filters(
49
+                        'wl_webhooks__sync_many__args',
50
+                        array(
51
+                            'blocking' => false,
52
+                            'method'   => 'PUT',
53
+                            'headers'  => array( 'content-type' => 'application/json; ' . get_bloginfo( 'charset' ) ),
54
+                            'body'     => $jsonld,
55
+                        ),
56
+                        $hash
57
+                    )
58
+                );
59
+            }
60
+        }
61
+    }
62 62
 
63
-	/**
64
-	 * Method to call up webhook with delete requested
65
-	 *
66
-	 * @param string $type
67
-	 * @param int    $object_id
68
-	 * @param string $uri
69
-	 */
70
-	public function sync_delete( $type, $object_id, $uri ) {
63
+    /**
64
+     * Method to call up webhook with delete requested
65
+     *
66
+     * @param string $type
67
+     * @param int    $object_id
68
+     * @param string $uri
69
+     */
70
+    public function sync_delete( $type, $object_id, $uri ) {
71 71
 
72
-		$urls = explode( "\n", get_option( Webhooks_Loader::URLS_OPTION_NAME, '' ) );
73
-		if ( empty( $urls ) ) {
74
-			return;
75
-		}
72
+        $urls = explode( "\n", get_option( Webhooks_Loader::URLS_OPTION_NAME, '' ) );
73
+        if ( empty( $urls ) ) {
74
+            return;
75
+        }
76 76
 
77
-		if ( ! apply_filters( 'wl_webhooks__sync_delete', true, $type, $object_id, $uri ) ) {
78
-			return;
79
-		}
77
+        if ( ! apply_filters( 'wl_webhooks__sync_delete', true, $type, $object_id, $uri ) ) {
78
+            return;
79
+        }
80 80
 
81
-		foreach ( $urls as $template_url ) {
82
-			$url          = add_query_arg( array( 'uri' => $uri ), $template_url );
83
-			$filtered_url = apply_filters( 'wl_webhooks__sync_delete__url', $url, $type, $object_id, $uri );
84
-			wp_remote_request(
85
-				$filtered_url,
86
-				apply_filters(
87
-					'wl_webhooks__sync_delete__args',
88
-					array(
89
-						'blocking' => false,
90
-						'method'   => 'DELETE',
91
-					)
92
-				)
93
-			);
94
-		}
81
+        foreach ( $urls as $template_url ) {
82
+            $url          = add_query_arg( array( 'uri' => $uri ), $template_url );
83
+            $filtered_url = apply_filters( 'wl_webhooks__sync_delete__url', $url, $type, $object_id, $uri );
84
+            wp_remote_request(
85
+                $filtered_url,
86
+                apply_filters(
87
+                    'wl_webhooks__sync_delete__args',
88
+                    array(
89
+                        'blocking' => false,
90
+                        'method'   => 'DELETE',
91
+                    )
92
+                )
93
+            );
94
+        }
95 95
 
96
-	}
96
+    }
97 97
 
98 98
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -15,8 +15,8 @@  discard block
 block discarded – undo
15 15
 	 * Registering the actions to call up sync_many or sync_delete methods
16 16
 	 */
17 17
 	public function __construct() {
18
-		add_action( 'wl_sync__sync_many', array( $this, 'sync_many' ), 10 );
19
-		add_action( 'wl_sync__delete_one', array( $this, 'sync_delete' ), 10, 3 );
18
+		add_action('wl_sync__sync_many', array($this, 'sync_many'), 10);
19
+		add_action('wl_sync__delete_one', array($this, 'sync_delete'), 10, 3);
20 20
 	}
21 21
 
22 22
 	/**
@@ -24,10 +24,10 @@  discard block
 block discarded – undo
24 24
 	 *
25 25
 	 * @param array $hashes
26 26
 	 */
27
-	public function sync_many( $hashes ) {
27
+	public function sync_many($hashes) {
28 28
 
29
-		$urls = explode( "\n", get_option( Webhooks_Loader::URLS_OPTION_NAME, '' ) );
30
-		if ( empty( $urls ) ) {
29
+		$urls = explode("\n", get_option(Webhooks_Loader::URLS_OPTION_NAME, ''));
30
+		if (empty($urls)) {
31 31
 			return;
32 32
 		}
33 33
 
@@ -37,12 +37,12 @@  discard block
 block discarded – undo
37 37
 		 * @since 3.34.0
38 38
 		 * @var Sync_Object_Adapter[] $filtered_objects
39 39
 		 */
40
-		$filtered_hashes = apply_filters( 'wl_webhooks__sync_many__objects', $hashes );
40
+		$filtered_hashes = apply_filters('wl_webhooks__sync_many__objects', $hashes);
41 41
 
42
-		foreach ( $urls as $url ) {
43
-			foreach ( $filtered_hashes as $hash ) {
42
+		foreach ($urls as $url) {
43
+			foreach ($filtered_hashes as $hash) {
44 44
 				$jsonld       = $hash[2];
45
-				$filtered_url = apply_filters( 'wl_webhooks__sync_many__url', $url, $hash );
45
+				$filtered_url = apply_filters('wl_webhooks__sync_many__url', $url, $hash);
46 46
 				wp_remote_request(
47 47
 					$filtered_url,
48 48
 					apply_filters(
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 						array(
51 51
 							'blocking' => false,
52 52
 							'method'   => 'PUT',
53
-							'headers'  => array( 'content-type' => 'application/json; ' . get_bloginfo( 'charset' ) ),
53
+							'headers'  => array('content-type' => 'application/json; '.get_bloginfo('charset')),
54 54
 							'body'     => $jsonld,
55 55
 						),
56 56
 						$hash
@@ -67,20 +67,20 @@  discard block
 block discarded – undo
67 67
 	 * @param int    $object_id
68 68
 	 * @param string $uri
69 69
 	 */
70
-	public function sync_delete( $type, $object_id, $uri ) {
70
+	public function sync_delete($type, $object_id, $uri) {
71 71
 
72
-		$urls = explode( "\n", get_option( Webhooks_Loader::URLS_OPTION_NAME, '' ) );
73
-		if ( empty( $urls ) ) {
72
+		$urls = explode("\n", get_option(Webhooks_Loader::URLS_OPTION_NAME, ''));
73
+		if (empty($urls)) {
74 74
 			return;
75 75
 		}
76 76
 
77
-		if ( ! apply_filters( 'wl_webhooks__sync_delete', true, $type, $object_id, $uri ) ) {
77
+		if ( ! apply_filters('wl_webhooks__sync_delete', true, $type, $object_id, $uri)) {
78 78
 			return;
79 79
 		}
80 80
 
81
-		foreach ( $urls as $template_url ) {
82
-			$url          = add_query_arg( array( 'uri' => $uri ), $template_url );
83
-			$filtered_url = apply_filters( 'wl_webhooks__sync_delete__url', $url, $type, $object_id, $uri );
81
+		foreach ($urls as $template_url) {
82
+			$url          = add_query_arg(array('uri' => $uri), $template_url);
83
+			$filtered_url = apply_filters('wl_webhooks__sync_delete__url', $url, $type, $object_id, $uri);
84 84
 			wp_remote_request(
85 85
 				$filtered_url,
86 86
 				apply_filters(
Please login to merge, or discard this patch.
src/wordlift/post-excerpt/class-post-excerpt-meta-box-adapter.php 2 patches
Indentation   +161 added lines, -161 removed lines patch added patch discarded remove patch
@@ -16,166 +16,166 @@
 block discarded – undo
16 16
 
17 17
 final class Post_Excerpt_Meta_Box_Adapter {
18 18
 
19
-	/**
20
-	 * Key used by WordPress to add the excerpt meta box in
21
-	 * the $wp_meta_boxes global variable.
22
-	 */
23
-	const POST_EXCERPT_META_BOX_KEY = 'postexcerpt';
24
-
25
-	/**
26
-	 * Div id used for adding the additional content
27
-	 * to the WordPress excerpt meta box.
28
-	 */
29
-	const WORDLIFT_EXCERPT_DIV_ID = 'wl-custom-excerpt-wrapper';
30
-
31
-	/**
32
-	 * @var callable|null The default callback used by WordPress to
33
-	 * echo the post_excerpt contents, defaults to null.
34
-	 */
35
-	public $wordpress_excerpt_callback = null;
36
-
37
-	/**
38
-	 * Invokes the default callback inside our custom template callback
39
-	 *
40
-	 * @param $post array The post array.
41
-	 */
42
-	public function print_wordlift_custom_post_excerpt_box( $post ) {
43
-		call_user_func( $this->wordpress_excerpt_callback, $post );
44
-		// Invoke our call back to add additional html, the react script will find this id and render the component there.
45
-		echo "<div id='" . esc_html( self::WORDLIFT_EXCERPT_DIV_ID ) . "'></div>";
46
-	}
47
-
48
-	/**
49
-	 * Replaces the default post excerpt meta box with custom post excerpt meta box.
50
-	 */
51
-	public function replace_post_excerpt_meta_box() {
52
-		global $wp_meta_boxes;
53
-		$post_type = get_post_type();
54
-
55
-		// Bail out if feature is turned off
56
-		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
57
-		if ( ! apply_filters( 'wl_feature__enable__post-excerpt', true ) ) {
58
-			return;
59
-		}
60
-
61
-		/**
62
-		 * @since 3.27.6
63
-		 *
64
-		 * @see https://github.com/insideout10/wordlift-plugin/issues/1188
65
-		 */
66
-		if ( ! isset( $wp_meta_boxes[ $post_type ] ) ) {
67
-			return;
68
-		}
69
-
70
-		$core_meta_boxes = $wp_meta_boxes[ $post_type ]['normal']['core'];
71
-
72
-		if ( ! isset( $core_meta_boxes[ self::POST_EXCERPT_META_BOX_KEY ] ) ) {
73
-			return;
74
-		}
75
-
76
-		$post_excerpt_meta_box = $core_meta_boxes[ self::POST_EXCERPT_META_BOX_KEY ];
77
-		$callback              = $post_excerpt_meta_box['callback'];
78
-		/**
79
-		 * do_meta_boxes action is called 3 times by WordPress for
80
-		 * different set of metaboxes, so to prevent overwriting our
81
-		 * callback with null, this check is necessary.
82
-		 */
83
-		if ( null !== $callback && array( $this, 'print_wordlift_custom_post_excerpt_box' ) !== $callback ) {
84
-			$this->wordpress_excerpt_callback = $callback;
85
-			$this->remove_default_post_excerpt_meta_box();
86
-			$this->add_custom_post_excerpt_meta_box();
87
-			$this->enqueue_post_excerpt_scripts();
88
-		}
89
-	}
90
-
91
-	/**
92
-	 * Removes the registered post excerpt metabox.
93
-	 */
94
-	private function remove_default_post_excerpt_meta_box() {
95
-
96
-		remove_meta_box( self::POST_EXCERPT_META_BOX_KEY, get_current_screen(), 'normal' );
97
-
98
-	}
99
-
100
-	/**
101
-	 * Deserializes the string, and rewrite the order for post excerpt.
102
-	 *
103
-	 * @param $order array
104
-	 *
105
-	 * @return array
106
-	 */
107
-	private function deserialize_and_rewrite_order( $order ) {
108
-		$side         = explode( ',', $order['side'] );
109
-		$normal       = explode( ',', $order['normal'] );
110
-		$advanced     = explode( ',', $order['advanced'] );
111
-		$remove_array = array( self::POST_EXCERPT_META_BOX_KEY );
112
-
113
-		// We first remove from the side category if it is previously present.
114
-		$side = array_diff( $side, $remove_array );
115
-		if ( count( $side ) === 0 ) {
116
-			// No boxes present, so add our excerpt box at o th position.
117
-			array_push( $side, self::POST_EXCERPT_META_BOX_KEY );
118
-		} else {
119
-			// Add custom excerpt metabox at second position
120
-			array_splice( $side, 1, 0, $remove_array );
121
-		}
122
-
123
-		// We remove postexcerpt from all other metaboxes category.
124
-		$normal   = array_diff( $normal, $remove_array );
125
-		$advanced = array_diff( $advanced, $remove_array );
126
-
127
-		return array(
128
-			'normal'   => $normal,
129
-			'side'     => $side,
130
-			'advanced' => $advanced,
131
-		);
132
-	}
133
-
134
-	/**
135
-	 * Adds the custom post excerpt metabox.
136
-	 */
137
-	private function add_custom_post_excerpt_meta_box() {
138
-		add_meta_box(
139
-			self::POST_EXCERPT_META_BOX_KEY,
140
-			// phpcs:ignore WordPress.WP.I18n.MissingArgDomainDefault
141
-			__( 'Excerpt' ),
142
-			array( $this, 'print_wordlift_custom_post_excerpt_box' ),
143
-			// Mimic the settings of the default metabox.
144
-			null,
145
-			'normal',
146
-			'high'
147
-		);
148
-	}
149
-
150
-	private function enqueue_post_excerpt_scripts() {
151
-		Scripts_Helper::enqueue_based_on_wordpress_version(
152
-			'wl-post-excerpt',
153
-			plugin_dir_url( dirname( __DIR__ ) ) . 'js/dist/post-excerpt',
154
-			array( 'react', 'react-dom', 'wp-polyfill' ),
155
-			true
156
-		);
157
-		wp_enqueue_style(
158
-			'wl-post-excerpt',
159
-			plugin_dir_url( dirname( __DIR__ ) ) . 'js/dist/post-excerpt.css',
160
-			array(),
161
-			WORDLIFT_VERSION
162
-		);
163
-		wp_localize_script(
164
-			'wl-post-excerpt',
165
-			'_wlExcerptSettings',
166
-			$this->get_post_excerpt_translations()
167
-		);
168
-	}
169
-
170
-	public function get_post_excerpt_translations() {
171
-
172
-		return array(
173
-			'orText'         => __( 'Or use WordLift suggested post excerpt:', 'wordlift' ),
174
-			'generatingText' => __( 'Generating excerpt...', 'wordlift' ),
175
-			'restUrl'        => get_rest_url( null, WL_REST_ROUTE_DEFAULT_NAMESPACE . '/post-excerpt' ),
176
-			'nonce'          => wp_create_nonce( 'wp_rest' ),
177
-			'postId'         => get_the_ID(),
178
-		);
179
-	}
19
+    /**
20
+     * Key used by WordPress to add the excerpt meta box in
21
+     * the $wp_meta_boxes global variable.
22
+     */
23
+    const POST_EXCERPT_META_BOX_KEY = 'postexcerpt';
24
+
25
+    /**
26
+     * Div id used for adding the additional content
27
+     * to the WordPress excerpt meta box.
28
+     */
29
+    const WORDLIFT_EXCERPT_DIV_ID = 'wl-custom-excerpt-wrapper';
30
+
31
+    /**
32
+     * @var callable|null The default callback used by WordPress to
33
+     * echo the post_excerpt contents, defaults to null.
34
+     */
35
+    public $wordpress_excerpt_callback = null;
36
+
37
+    /**
38
+     * Invokes the default callback inside our custom template callback
39
+     *
40
+     * @param $post array The post array.
41
+     */
42
+    public function print_wordlift_custom_post_excerpt_box( $post ) {
43
+        call_user_func( $this->wordpress_excerpt_callback, $post );
44
+        // Invoke our call back to add additional html, the react script will find this id and render the component there.
45
+        echo "<div id='" . esc_html( self::WORDLIFT_EXCERPT_DIV_ID ) . "'></div>";
46
+    }
47
+
48
+    /**
49
+     * Replaces the default post excerpt meta box with custom post excerpt meta box.
50
+     */
51
+    public function replace_post_excerpt_meta_box() {
52
+        global $wp_meta_boxes;
53
+        $post_type = get_post_type();
54
+
55
+        // Bail out if feature is turned off
56
+        // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
57
+        if ( ! apply_filters( 'wl_feature__enable__post-excerpt', true ) ) {
58
+            return;
59
+        }
60
+
61
+        /**
62
+         * @since 3.27.6
63
+         *
64
+         * @see https://github.com/insideout10/wordlift-plugin/issues/1188
65
+         */
66
+        if ( ! isset( $wp_meta_boxes[ $post_type ] ) ) {
67
+            return;
68
+        }
69
+
70
+        $core_meta_boxes = $wp_meta_boxes[ $post_type ]['normal']['core'];
71
+
72
+        if ( ! isset( $core_meta_boxes[ self::POST_EXCERPT_META_BOX_KEY ] ) ) {
73
+            return;
74
+        }
75
+
76
+        $post_excerpt_meta_box = $core_meta_boxes[ self::POST_EXCERPT_META_BOX_KEY ];
77
+        $callback              = $post_excerpt_meta_box['callback'];
78
+        /**
79
+         * do_meta_boxes action is called 3 times by WordPress for
80
+         * different set of metaboxes, so to prevent overwriting our
81
+         * callback with null, this check is necessary.
82
+         */
83
+        if ( null !== $callback && array( $this, 'print_wordlift_custom_post_excerpt_box' ) !== $callback ) {
84
+            $this->wordpress_excerpt_callback = $callback;
85
+            $this->remove_default_post_excerpt_meta_box();
86
+            $this->add_custom_post_excerpt_meta_box();
87
+            $this->enqueue_post_excerpt_scripts();
88
+        }
89
+    }
90
+
91
+    /**
92
+     * Removes the registered post excerpt metabox.
93
+     */
94
+    private function remove_default_post_excerpt_meta_box() {
95
+
96
+        remove_meta_box( self::POST_EXCERPT_META_BOX_KEY, get_current_screen(), 'normal' );
97
+
98
+    }
99
+
100
+    /**
101
+     * Deserializes the string, and rewrite the order for post excerpt.
102
+     *
103
+     * @param $order array
104
+     *
105
+     * @return array
106
+     */
107
+    private function deserialize_and_rewrite_order( $order ) {
108
+        $side         = explode( ',', $order['side'] );
109
+        $normal       = explode( ',', $order['normal'] );
110
+        $advanced     = explode( ',', $order['advanced'] );
111
+        $remove_array = array( self::POST_EXCERPT_META_BOX_KEY );
112
+
113
+        // We first remove from the side category if it is previously present.
114
+        $side = array_diff( $side, $remove_array );
115
+        if ( count( $side ) === 0 ) {
116
+            // No boxes present, so add our excerpt box at o th position.
117
+            array_push( $side, self::POST_EXCERPT_META_BOX_KEY );
118
+        } else {
119
+            // Add custom excerpt metabox at second position
120
+            array_splice( $side, 1, 0, $remove_array );
121
+        }
122
+
123
+        // We remove postexcerpt from all other metaboxes category.
124
+        $normal   = array_diff( $normal, $remove_array );
125
+        $advanced = array_diff( $advanced, $remove_array );
126
+
127
+        return array(
128
+            'normal'   => $normal,
129
+            'side'     => $side,
130
+            'advanced' => $advanced,
131
+        );
132
+    }
133
+
134
+    /**
135
+     * Adds the custom post excerpt metabox.
136
+     */
137
+    private function add_custom_post_excerpt_meta_box() {
138
+        add_meta_box(
139
+            self::POST_EXCERPT_META_BOX_KEY,
140
+            // phpcs:ignore WordPress.WP.I18n.MissingArgDomainDefault
141
+            __( 'Excerpt' ),
142
+            array( $this, 'print_wordlift_custom_post_excerpt_box' ),
143
+            // Mimic the settings of the default metabox.
144
+            null,
145
+            'normal',
146
+            'high'
147
+        );
148
+    }
149
+
150
+    private function enqueue_post_excerpt_scripts() {
151
+        Scripts_Helper::enqueue_based_on_wordpress_version(
152
+            'wl-post-excerpt',
153
+            plugin_dir_url( dirname( __DIR__ ) ) . 'js/dist/post-excerpt',
154
+            array( 'react', 'react-dom', 'wp-polyfill' ),
155
+            true
156
+        );
157
+        wp_enqueue_style(
158
+            'wl-post-excerpt',
159
+            plugin_dir_url( dirname( __DIR__ ) ) . 'js/dist/post-excerpt.css',
160
+            array(),
161
+            WORDLIFT_VERSION
162
+        );
163
+        wp_localize_script(
164
+            'wl-post-excerpt',
165
+            '_wlExcerptSettings',
166
+            $this->get_post_excerpt_translations()
167
+        );
168
+    }
169
+
170
+    public function get_post_excerpt_translations() {
171
+
172
+        return array(
173
+            'orText'         => __( 'Or use WordLift suggested post excerpt:', 'wordlift' ),
174
+            'generatingText' => __( 'Generating excerpt...', 'wordlift' ),
175
+            'restUrl'        => get_rest_url( null, WL_REST_ROUTE_DEFAULT_NAMESPACE . '/post-excerpt' ),
176
+            'nonce'          => wp_create_nonce( 'wp_rest' ),
177
+            'postId'         => get_the_ID(),
178
+        );
179
+    }
180 180
 
181 181
 }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -39,10 +39,10 @@  discard block
 block discarded – undo
39 39
 	 *
40 40
 	 * @param $post array The post array.
41 41
 	 */
42
-	public function print_wordlift_custom_post_excerpt_box( $post ) {
43
-		call_user_func( $this->wordpress_excerpt_callback, $post );
42
+	public function print_wordlift_custom_post_excerpt_box($post) {
43
+		call_user_func($this->wordpress_excerpt_callback, $post);
44 44
 		// Invoke our call back to add additional html, the react script will find this id and render the component there.
45
-		echo "<div id='" . esc_html( self::WORDLIFT_EXCERPT_DIV_ID ) . "'></div>";
45
+		echo "<div id='".esc_html(self::WORDLIFT_EXCERPT_DIV_ID)."'></div>";
46 46
 	}
47 47
 
48 48
 	/**
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 
55 55
 		// Bail out if feature is turned off
56 56
 		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
57
-		if ( ! apply_filters( 'wl_feature__enable__post-excerpt', true ) ) {
57
+		if ( ! apply_filters('wl_feature__enable__post-excerpt', true)) {
58 58
 			return;
59 59
 		}
60 60
 
@@ -63,24 +63,24 @@  discard block
 block discarded – undo
63 63
 		 *
64 64
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/1188
65 65
 		 */
66
-		if ( ! isset( $wp_meta_boxes[ $post_type ] ) ) {
66
+		if ( ! isset($wp_meta_boxes[$post_type])) {
67 67
 			return;
68 68
 		}
69 69
 
70
-		$core_meta_boxes = $wp_meta_boxes[ $post_type ]['normal']['core'];
70
+		$core_meta_boxes = $wp_meta_boxes[$post_type]['normal']['core'];
71 71
 
72
-		if ( ! isset( $core_meta_boxes[ self::POST_EXCERPT_META_BOX_KEY ] ) ) {
72
+		if ( ! isset($core_meta_boxes[self::POST_EXCERPT_META_BOX_KEY])) {
73 73
 			return;
74 74
 		}
75 75
 
76
-		$post_excerpt_meta_box = $core_meta_boxes[ self::POST_EXCERPT_META_BOX_KEY ];
76
+		$post_excerpt_meta_box = $core_meta_boxes[self::POST_EXCERPT_META_BOX_KEY];
77 77
 		$callback              = $post_excerpt_meta_box['callback'];
78 78
 		/**
79 79
 		 * do_meta_boxes action is called 3 times by WordPress for
80 80
 		 * different set of metaboxes, so to prevent overwriting our
81 81
 		 * callback with null, this check is necessary.
82 82
 		 */
83
-		if ( null !== $callback && array( $this, 'print_wordlift_custom_post_excerpt_box' ) !== $callback ) {
83
+		if (null !== $callback && array($this, 'print_wordlift_custom_post_excerpt_box') !== $callback) {
84 84
 			$this->wordpress_excerpt_callback = $callback;
85 85
 			$this->remove_default_post_excerpt_meta_box();
86 86
 			$this->add_custom_post_excerpt_meta_box();
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 	 */
94 94
 	private function remove_default_post_excerpt_meta_box() {
95 95
 
96
-		remove_meta_box( self::POST_EXCERPT_META_BOX_KEY, get_current_screen(), 'normal' );
96
+		remove_meta_box(self::POST_EXCERPT_META_BOX_KEY, get_current_screen(), 'normal');
97 97
 
98 98
 	}
99 99
 
@@ -104,25 +104,25 @@  discard block
 block discarded – undo
104 104
 	 *
105 105
 	 * @return array
106 106
 	 */
107
-	private function deserialize_and_rewrite_order( $order ) {
108
-		$side         = explode( ',', $order['side'] );
109
-		$normal       = explode( ',', $order['normal'] );
110
-		$advanced     = explode( ',', $order['advanced'] );
111
-		$remove_array = array( self::POST_EXCERPT_META_BOX_KEY );
107
+	private function deserialize_and_rewrite_order($order) {
108
+		$side         = explode(',', $order['side']);
109
+		$normal       = explode(',', $order['normal']);
110
+		$advanced     = explode(',', $order['advanced']);
111
+		$remove_array = array(self::POST_EXCERPT_META_BOX_KEY);
112 112
 
113 113
 		// We first remove from the side category if it is previously present.
114
-		$side = array_diff( $side, $remove_array );
115
-		if ( count( $side ) === 0 ) {
114
+		$side = array_diff($side, $remove_array);
115
+		if (count($side) === 0) {
116 116
 			// No boxes present, so add our excerpt box at o th position.
117
-			array_push( $side, self::POST_EXCERPT_META_BOX_KEY );
117
+			array_push($side, self::POST_EXCERPT_META_BOX_KEY);
118 118
 		} else {
119 119
 			// Add custom excerpt metabox at second position
120
-			array_splice( $side, 1, 0, $remove_array );
120
+			array_splice($side, 1, 0, $remove_array);
121 121
 		}
122 122
 
123 123
 		// We remove postexcerpt from all other metaboxes category.
124
-		$normal   = array_diff( $normal, $remove_array );
125
-		$advanced = array_diff( $advanced, $remove_array );
124
+		$normal   = array_diff($normal, $remove_array);
125
+		$advanced = array_diff($advanced, $remove_array);
126 126
 
127 127
 		return array(
128 128
 			'normal'   => $normal,
@@ -138,8 +138,8 @@  discard block
 block discarded – undo
138 138
 		add_meta_box(
139 139
 			self::POST_EXCERPT_META_BOX_KEY,
140 140
 			// phpcs:ignore WordPress.WP.I18n.MissingArgDomainDefault
141
-			__( 'Excerpt' ),
142
-			array( $this, 'print_wordlift_custom_post_excerpt_box' ),
141
+			__('Excerpt'),
142
+			array($this, 'print_wordlift_custom_post_excerpt_box'),
143 143
 			// Mimic the settings of the default metabox.
144 144
 			null,
145 145
 			'normal',
@@ -150,13 +150,13 @@  discard block
 block discarded – undo
150 150
 	private function enqueue_post_excerpt_scripts() {
151 151
 		Scripts_Helper::enqueue_based_on_wordpress_version(
152 152
 			'wl-post-excerpt',
153
-			plugin_dir_url( dirname( __DIR__ ) ) . 'js/dist/post-excerpt',
154
-			array( 'react', 'react-dom', 'wp-polyfill' ),
153
+			plugin_dir_url(dirname(__DIR__)).'js/dist/post-excerpt',
154
+			array('react', 'react-dom', 'wp-polyfill'),
155 155
 			true
156 156
 		);
157 157
 		wp_enqueue_style(
158 158
 			'wl-post-excerpt',
159
-			plugin_dir_url( dirname( __DIR__ ) ) . 'js/dist/post-excerpt.css',
159
+			plugin_dir_url(dirname(__DIR__)).'js/dist/post-excerpt.css',
160 160
 			array(),
161 161
 			WORDLIFT_VERSION
162 162
 		);
@@ -170,10 +170,10 @@  discard block
 block discarded – undo
170 170
 	public function get_post_excerpt_translations() {
171 171
 
172 172
 		return array(
173
-			'orText'         => __( 'Or use WordLift suggested post excerpt:', 'wordlift' ),
174
-			'generatingText' => __( 'Generating excerpt...', 'wordlift' ),
175
-			'restUrl'        => get_rest_url( null, WL_REST_ROUTE_DEFAULT_NAMESPACE . '/post-excerpt' ),
176
-			'nonce'          => wp_create_nonce( 'wp_rest' ),
173
+			'orText'         => __('Or use WordLift suggested post excerpt:', 'wordlift'),
174
+			'generatingText' => __('Generating excerpt...', 'wordlift'),
175
+			'restUrl'        => get_rest_url(null, WL_REST_ROUTE_DEFAULT_NAMESPACE.'/post-excerpt'),
176
+			'nonce'          => wp_create_nonce('wp_rest'),
177 177
 			'postId'         => get_the_ID(),
178 178
 		);
179 179
 	}
Please login to merge, or discard this patch.
src/wordlift/post-excerpt/class-post-excerpt-rest-controller.php 2 patches
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -18,212 +18,212 @@
 block discarded – undo
18 18
 
19 19
 class Post_Excerpt_Rest_Controller {
20 20
 
21
-	const POST_EXCERPT_NAMESPACE = 'post-excerpt';
22
-	/**
23
-	 * Key for storing the meta data for the wordlift post excerpt.
24
-	 */
25
-	const POST_EXCERPT_META_KEY = '_wl_post_excerpt_meta';
26
-
27
-	/**
28
-	 * Url for getting the post excerpt data from wordlift api.
29
-	 */
30
-	const WORDLIFT_POST_EXCERPT_ENDPOINT = '/summarize';
31
-
32
-	/**
33
-	 * Wordlift returns excerpt in response using this key..
34
-	 */
35
-	const WORDLIFT_POST_EXCERPT_RESPONSE_KEY = 'summary';
36
-
37
-	public static function register_routes() {
38
-		add_action( 'rest_api_init', 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::register_route_callback' );
39
-	}
40
-
41
-	/**
42
-	 * Determines whether we need to get the excerpt from wordlift api,
43
-	 * or just use the one we already obtained by generating the hash and comparing it
44
-	 * with the previous one.
45
-	 *
46
-	 * @param $request WP_REST_Request $request {@link WP_REST_Request instance}.
47
-	 *
48
-	 * @return array Post excerpt data.
49
-	 */
50
-	public static function get_post_excerpt( $request ) {
51
-		$data      = $request->get_params();
52
-		$post_id   = $data['post_id'];
53
-		$post_body = strip_shortcodes( $data['post_body'] );
54
-		/**
55
-		 * @param $post_body string The post content sent from WordPress editor.
56
-		 * @param $post_id int The post id.
57
-		 *
58
-		 * @since 3.33.5
59
-		 * Allow post content sent to excerpt api to be filtered.
60
-		 */
61
-		$post_body       = apply_filters( 'wl_post_excerpt_post_content', $post_body, $post_id );
62
-		$current_hash    = md5( $post_body );
63
-		$server_response = self::get_post_excerpt_conditionally( $post_id, $post_body, $current_hash );
64
-		if ( empty( $server_response ) || ! array_key_exists( 'post_excerpt', $server_response ) ) {
65
-			return array(
66
-				'status'  => 'error',
67
-				'message' => __( 'Unable to contact WordLift API', 'wordlift' ),
68
-			);
69
-		} else {
70
-			return array(
71
-				'status'       => 'success',
72
-				'post_excerpt' => $server_response['post_excerpt'],
73
-				'from_cache'   => $server_response['from_cache'],
74
-				'message'      => __( 'Excerpt successfully generated.', 'wordlift' ),
75
-			);
76
-		}
77
-
78
-	}
79
-
80
-	/**
81
-	 * This function determines whether to get the excerpt from the server or from the meta cache.
82
-	 *
83
-	 * @param $post_id int The Post id.
84
-	 * @param $post_body string The post content
85
-	 * @param $current_hash string md5 hash of the current post body.
86
-	 *
87
-	 * @return array|bool|null
88
-	 */
89
-	public static function get_post_excerpt_conditionally( $post_id, $post_body, $current_hash ) {
90
-		$previous_data   = get_post_meta( $post_id, self::POST_EXCERPT_META_KEY, true );
91
-		$server_response = null;
92
-		if ( '' === $previous_data ) {
93
-			// There is no data in meta, so just fetch the data from remote server.
94
-			$server_response = self::get_post_excerpt_from_remote_server( $post_id, $post_body );
95
-		} else {
96
-			// If there is data in meta, get the previous hash and compare.
97
-			$previous_hash = $previous_data['post_body_hash'];
98
-
99
-			if ( $current_hash === $previous_hash ) {
100
-				// then return the previous value.
101
-				$server_response = array(
102
-					'post_excerpt' => $previous_data['post_excerpt'],
103
-					'from_cache'   => true,
104
-				);
105
-			} else {
106
-				// send the request to external API and then send the response.
107
-				$server_response = self::get_post_excerpt_from_remote_server( $post_id, $post_body );
108
-			}
109
-		}
110
-
111
-		return $server_response;
112
-	}
113
-
114
-	/**
115
-	 * Sends the remote request to the wordlift API and saves the response in meta for
116
-	 * future use.
117
-	 *
118
-	 * @param $post_id int Post id which the post excerpt belongs to
119
-	 * @param $post_body string Total text content of the post body.
120
-	 *
121
-	 * @return array|bool
122
-	 */
123
-	public static function get_post_excerpt_from_remote_server( $post_id, $post_body ) {
124
-		// The configuration is constant for now, it might be changing in future.
125
-		$configuration = array(
126
-			'ratio'      => 0.0005,
127
-			'min_length' => 60,
128
-		);
129
-		// Construct the url with the configuration
130
-		$endpoint    = add_query_arg( $configuration, self::WORDLIFT_POST_EXCERPT_ENDPOINT );
131
-		$api_service = Default_Api_Service::get_instance();
132
-		$response    = $api_service->request(
133
-			'POST',
134
-			$endpoint,
135
-			array( 'Content-Type' => 'text/plain' ),
136
-			$post_body,
137
-			null,
138
-			null,
139
-			array( 'data_format' => 'body' )
140
-		);
141
-
142
-		return self::save_response_to_meta_on_success( $post_id, $post_body, $response );
143
-	}
144
-
145
-	/**
146
-	 * Save the post excerpt to meta if the response is successful.
147
-	 *
148
-	 * @param $post_id int The post id
149
-	 * @param $post_body string Full text content of the post.
150
-	 * @param $response Response instance
151
-	 *
152
-	 * @return array|bool
153
-	 */
154
-	public static function save_response_to_meta_on_success( $post_id, $post_body, $response ) {
155
-		// If body exists then decode the body.
156
-		$body = json_decode( $response->get_body(), true );
157
-		if ( empty( $body ) || ! array_key_exists( self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY, $body ) ) {
158
-			// Bail out if we get an incorrect response
159
-			return false;
160
-		} else {
161
-			$post_excerpt = (string) $body[ self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY ];
162
-			// Save it to meta.
163
-			self::save_post_excerpt_in_meta( $post_id, $post_excerpt, $post_body );
164
-
165
-			return array(
166
-				'post_excerpt' => $post_excerpt,
167
-				'from_cache'   => false,
168
-			);
169
-		}
170
-	}
171
-
172
-	/**
173
-	 * Saves the excerpt in the post meta.
174
-	 *
175
-	 * @param $post_id int Post id which the post excerpt belongs to
176
-	 * @param $post_excerpt string Post excerpt returned by the server
177
-	 * @param $post_body string Total text content of the post body.
178
-	 *
179
-	 * @return void
180
-	 */
181
-	public static function save_post_excerpt_in_meta( $post_id, $post_excerpt, $post_body ) {
182
-		// hash the post body and save it.
183
-		$data = array(
184
-			'post_body_hash' => md5( $post_body ),
185
-			'post_excerpt'   => $post_excerpt,
186
-		);
187
-		update_post_meta( $post_id, self::POST_EXCERPT_META_KEY, $data );
188
-	}
189
-
190
-	/**
191
-	 * This call back is invoked by the Rest api action.
192
-	 */
193
-	public static function register_route_callback() {
194
-		/** @var  $post_id_validation_settings array Settings used to validate post id */
195
-		$post_id_validation_settings   = array(
196
-			'required'          => true,
197
-			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
198
-			'validate_callback' => function ( $param, $request, $key ) {
199
-				return is_numeric( $param );
200
-			},
201
-		);
202
-		$post_body_validation_settings = array(
203
-			'required'          => true,
204
-			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
205
-			'validate_callback' => function ( $param, $request, $key ) {
206
-				return is_string( $param );
207
-			},
208
-		);
209
-		/**
210
-		 * Rest route for getting the excerpt from wordlift api.
211
-		 */
212
-		register_rest_route(
213
-			WL_REST_ROUTE_DEFAULT_NAMESPACE,
214
-			'/' . self::POST_EXCERPT_NAMESPACE . '/(?P<post_id>\d+)',
215
-			array(
216
-				'methods'             => \WP_REST_Server::CREATABLE,
217
-				'callback'            => 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::get_post_excerpt',
218
-				'permission_callback' => function () {
219
-					return current_user_can( 'publish_posts' );
220
-				},
221
-				'args'                => array(
222
-					'post_id'   => $post_id_validation_settings,
223
-					'post_body' => $post_body_validation_settings,
224
-				),
225
-			)
226
-		);
227
-	}
21
+    const POST_EXCERPT_NAMESPACE = 'post-excerpt';
22
+    /**
23
+     * Key for storing the meta data for the wordlift post excerpt.
24
+     */
25
+    const POST_EXCERPT_META_KEY = '_wl_post_excerpt_meta';
26
+
27
+    /**
28
+     * Url for getting the post excerpt data from wordlift api.
29
+     */
30
+    const WORDLIFT_POST_EXCERPT_ENDPOINT = '/summarize';
31
+
32
+    /**
33
+     * Wordlift returns excerpt in response using this key..
34
+     */
35
+    const WORDLIFT_POST_EXCERPT_RESPONSE_KEY = 'summary';
36
+
37
+    public static function register_routes() {
38
+        add_action( 'rest_api_init', 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::register_route_callback' );
39
+    }
40
+
41
+    /**
42
+     * Determines whether we need to get the excerpt from wordlift api,
43
+     * or just use the one we already obtained by generating the hash and comparing it
44
+     * with the previous one.
45
+     *
46
+     * @param $request WP_REST_Request $request {@link WP_REST_Request instance}.
47
+     *
48
+     * @return array Post excerpt data.
49
+     */
50
+    public static function get_post_excerpt( $request ) {
51
+        $data      = $request->get_params();
52
+        $post_id   = $data['post_id'];
53
+        $post_body = strip_shortcodes( $data['post_body'] );
54
+        /**
55
+         * @param $post_body string The post content sent from WordPress editor.
56
+         * @param $post_id int The post id.
57
+         *
58
+         * @since 3.33.5
59
+         * Allow post content sent to excerpt api to be filtered.
60
+         */
61
+        $post_body       = apply_filters( 'wl_post_excerpt_post_content', $post_body, $post_id );
62
+        $current_hash    = md5( $post_body );
63
+        $server_response = self::get_post_excerpt_conditionally( $post_id, $post_body, $current_hash );
64
+        if ( empty( $server_response ) || ! array_key_exists( 'post_excerpt', $server_response ) ) {
65
+            return array(
66
+                'status'  => 'error',
67
+                'message' => __( 'Unable to contact WordLift API', 'wordlift' ),
68
+            );
69
+        } else {
70
+            return array(
71
+                'status'       => 'success',
72
+                'post_excerpt' => $server_response['post_excerpt'],
73
+                'from_cache'   => $server_response['from_cache'],
74
+                'message'      => __( 'Excerpt successfully generated.', 'wordlift' ),
75
+            );
76
+        }
77
+
78
+    }
79
+
80
+    /**
81
+     * This function determines whether to get the excerpt from the server or from the meta cache.
82
+     *
83
+     * @param $post_id int The Post id.
84
+     * @param $post_body string The post content
85
+     * @param $current_hash string md5 hash of the current post body.
86
+     *
87
+     * @return array|bool|null
88
+     */
89
+    public static function get_post_excerpt_conditionally( $post_id, $post_body, $current_hash ) {
90
+        $previous_data   = get_post_meta( $post_id, self::POST_EXCERPT_META_KEY, true );
91
+        $server_response = null;
92
+        if ( '' === $previous_data ) {
93
+            // There is no data in meta, so just fetch the data from remote server.
94
+            $server_response = self::get_post_excerpt_from_remote_server( $post_id, $post_body );
95
+        } else {
96
+            // If there is data in meta, get the previous hash and compare.
97
+            $previous_hash = $previous_data['post_body_hash'];
98
+
99
+            if ( $current_hash === $previous_hash ) {
100
+                // then return the previous value.
101
+                $server_response = array(
102
+                    'post_excerpt' => $previous_data['post_excerpt'],
103
+                    'from_cache'   => true,
104
+                );
105
+            } else {
106
+                // send the request to external API and then send the response.
107
+                $server_response = self::get_post_excerpt_from_remote_server( $post_id, $post_body );
108
+            }
109
+        }
110
+
111
+        return $server_response;
112
+    }
113
+
114
+    /**
115
+     * Sends the remote request to the wordlift API and saves the response in meta for
116
+     * future use.
117
+     *
118
+     * @param $post_id int Post id which the post excerpt belongs to
119
+     * @param $post_body string Total text content of the post body.
120
+     *
121
+     * @return array|bool
122
+     */
123
+    public static function get_post_excerpt_from_remote_server( $post_id, $post_body ) {
124
+        // The configuration is constant for now, it might be changing in future.
125
+        $configuration = array(
126
+            'ratio'      => 0.0005,
127
+            'min_length' => 60,
128
+        );
129
+        // Construct the url with the configuration
130
+        $endpoint    = add_query_arg( $configuration, self::WORDLIFT_POST_EXCERPT_ENDPOINT );
131
+        $api_service = Default_Api_Service::get_instance();
132
+        $response    = $api_service->request(
133
+            'POST',
134
+            $endpoint,
135
+            array( 'Content-Type' => 'text/plain' ),
136
+            $post_body,
137
+            null,
138
+            null,
139
+            array( 'data_format' => 'body' )
140
+        );
141
+
142
+        return self::save_response_to_meta_on_success( $post_id, $post_body, $response );
143
+    }
144
+
145
+    /**
146
+     * Save the post excerpt to meta if the response is successful.
147
+     *
148
+     * @param $post_id int The post id
149
+     * @param $post_body string Full text content of the post.
150
+     * @param $response Response instance
151
+     *
152
+     * @return array|bool
153
+     */
154
+    public static function save_response_to_meta_on_success( $post_id, $post_body, $response ) {
155
+        // If body exists then decode the body.
156
+        $body = json_decode( $response->get_body(), true );
157
+        if ( empty( $body ) || ! array_key_exists( self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY, $body ) ) {
158
+            // Bail out if we get an incorrect response
159
+            return false;
160
+        } else {
161
+            $post_excerpt = (string) $body[ self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY ];
162
+            // Save it to meta.
163
+            self::save_post_excerpt_in_meta( $post_id, $post_excerpt, $post_body );
164
+
165
+            return array(
166
+                'post_excerpt' => $post_excerpt,
167
+                'from_cache'   => false,
168
+            );
169
+        }
170
+    }
171
+
172
+    /**
173
+     * Saves the excerpt in the post meta.
174
+     *
175
+     * @param $post_id int Post id which the post excerpt belongs to
176
+     * @param $post_excerpt string Post excerpt returned by the server
177
+     * @param $post_body string Total text content of the post body.
178
+     *
179
+     * @return void
180
+     */
181
+    public static function save_post_excerpt_in_meta( $post_id, $post_excerpt, $post_body ) {
182
+        // hash the post body and save it.
183
+        $data = array(
184
+            'post_body_hash' => md5( $post_body ),
185
+            'post_excerpt'   => $post_excerpt,
186
+        );
187
+        update_post_meta( $post_id, self::POST_EXCERPT_META_KEY, $data );
188
+    }
189
+
190
+    /**
191
+     * This call back is invoked by the Rest api action.
192
+     */
193
+    public static function register_route_callback() {
194
+        /** @var  $post_id_validation_settings array Settings used to validate post id */
195
+        $post_id_validation_settings   = array(
196
+            'required'          => true,
197
+            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
198
+            'validate_callback' => function ( $param, $request, $key ) {
199
+                return is_numeric( $param );
200
+            },
201
+        );
202
+        $post_body_validation_settings = array(
203
+            'required'          => true,
204
+            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
205
+            'validate_callback' => function ( $param, $request, $key ) {
206
+                return is_string( $param );
207
+            },
208
+        );
209
+        /**
210
+         * Rest route for getting the excerpt from wordlift api.
211
+         */
212
+        register_rest_route(
213
+            WL_REST_ROUTE_DEFAULT_NAMESPACE,
214
+            '/' . self::POST_EXCERPT_NAMESPACE . '/(?P<post_id>\d+)',
215
+            array(
216
+                'methods'             => \WP_REST_Server::CREATABLE,
217
+                'callback'            => 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::get_post_excerpt',
218
+                'permission_callback' => function () {
219
+                    return current_user_can( 'publish_posts' );
220
+                },
221
+                'args'                => array(
222
+                    'post_id'   => $post_id_validation_settings,
223
+                    'post_body' => $post_body_validation_settings,
224
+                ),
225
+            )
226
+        );
227
+    }
228 228
 
229 229
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	const WORDLIFT_POST_EXCERPT_RESPONSE_KEY = 'summary';
36 36
 
37 37
 	public static function register_routes() {
38
-		add_action( 'rest_api_init', 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::register_route_callback' );
38
+		add_action('rest_api_init', 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::register_route_callback');
39 39
 	}
40 40
 
41 41
 	/**
@@ -47,10 +47,10 @@  discard block
 block discarded – undo
47 47
 	 *
48 48
 	 * @return array Post excerpt data.
49 49
 	 */
50
-	public static function get_post_excerpt( $request ) {
50
+	public static function get_post_excerpt($request) {
51 51
 		$data      = $request->get_params();
52 52
 		$post_id   = $data['post_id'];
53
-		$post_body = strip_shortcodes( $data['post_body'] );
53
+		$post_body = strip_shortcodes($data['post_body']);
54 54
 		/**
55 55
 		 * @param $post_body string The post content sent from WordPress editor.
56 56
 		 * @param $post_id int The post id.
@@ -58,20 +58,20 @@  discard block
 block discarded – undo
58 58
 		 * @since 3.33.5
59 59
 		 * Allow post content sent to excerpt api to be filtered.
60 60
 		 */
61
-		$post_body       = apply_filters( 'wl_post_excerpt_post_content', $post_body, $post_id );
62
-		$current_hash    = md5( $post_body );
63
-		$server_response = self::get_post_excerpt_conditionally( $post_id, $post_body, $current_hash );
64
-		if ( empty( $server_response ) || ! array_key_exists( 'post_excerpt', $server_response ) ) {
61
+		$post_body       = apply_filters('wl_post_excerpt_post_content', $post_body, $post_id);
62
+		$current_hash    = md5($post_body);
63
+		$server_response = self::get_post_excerpt_conditionally($post_id, $post_body, $current_hash);
64
+		if (empty($server_response) || ! array_key_exists('post_excerpt', $server_response)) {
65 65
 			return array(
66 66
 				'status'  => 'error',
67
-				'message' => __( 'Unable to contact WordLift API', 'wordlift' ),
67
+				'message' => __('Unable to contact WordLift API', 'wordlift'),
68 68
 			);
69 69
 		} else {
70 70
 			return array(
71 71
 				'status'       => 'success',
72 72
 				'post_excerpt' => $server_response['post_excerpt'],
73 73
 				'from_cache'   => $server_response['from_cache'],
74
-				'message'      => __( 'Excerpt successfully generated.', 'wordlift' ),
74
+				'message'      => __('Excerpt successfully generated.', 'wordlift'),
75 75
 			);
76 76
 		}
77 77
 
@@ -86,17 +86,17 @@  discard block
 block discarded – undo
86 86
 	 *
87 87
 	 * @return array|bool|null
88 88
 	 */
89
-	public static function get_post_excerpt_conditionally( $post_id, $post_body, $current_hash ) {
90
-		$previous_data   = get_post_meta( $post_id, self::POST_EXCERPT_META_KEY, true );
89
+	public static function get_post_excerpt_conditionally($post_id, $post_body, $current_hash) {
90
+		$previous_data   = get_post_meta($post_id, self::POST_EXCERPT_META_KEY, true);
91 91
 		$server_response = null;
92
-		if ( '' === $previous_data ) {
92
+		if ('' === $previous_data) {
93 93
 			// There is no data in meta, so just fetch the data from remote server.
94
-			$server_response = self::get_post_excerpt_from_remote_server( $post_id, $post_body );
94
+			$server_response = self::get_post_excerpt_from_remote_server($post_id, $post_body);
95 95
 		} else {
96 96
 			// If there is data in meta, get the previous hash and compare.
97 97
 			$previous_hash = $previous_data['post_body_hash'];
98 98
 
99
-			if ( $current_hash === $previous_hash ) {
99
+			if ($current_hash === $previous_hash) {
100 100
 				// then return the previous value.
101 101
 				$server_response = array(
102 102
 					'post_excerpt' => $previous_data['post_excerpt'],
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 				);
105 105
 			} else {
106 106
 				// send the request to external API and then send the response.
107
-				$server_response = self::get_post_excerpt_from_remote_server( $post_id, $post_body );
107
+				$server_response = self::get_post_excerpt_from_remote_server($post_id, $post_body);
108 108
 			}
109 109
 		}
110 110
 
@@ -120,26 +120,26 @@  discard block
 block discarded – undo
120 120
 	 *
121 121
 	 * @return array|bool
122 122
 	 */
123
-	public static function get_post_excerpt_from_remote_server( $post_id, $post_body ) {
123
+	public static function get_post_excerpt_from_remote_server($post_id, $post_body) {
124 124
 		// The configuration is constant for now, it might be changing in future.
125 125
 		$configuration = array(
126 126
 			'ratio'      => 0.0005,
127 127
 			'min_length' => 60,
128 128
 		);
129 129
 		// Construct the url with the configuration
130
-		$endpoint    = add_query_arg( $configuration, self::WORDLIFT_POST_EXCERPT_ENDPOINT );
130
+		$endpoint    = add_query_arg($configuration, self::WORDLIFT_POST_EXCERPT_ENDPOINT);
131 131
 		$api_service = Default_Api_Service::get_instance();
132 132
 		$response    = $api_service->request(
133 133
 			'POST',
134 134
 			$endpoint,
135
-			array( 'Content-Type' => 'text/plain' ),
135
+			array('Content-Type' => 'text/plain'),
136 136
 			$post_body,
137 137
 			null,
138 138
 			null,
139
-			array( 'data_format' => 'body' )
139
+			array('data_format' => 'body')
140 140
 		);
141 141
 
142
-		return self::save_response_to_meta_on_success( $post_id, $post_body, $response );
142
+		return self::save_response_to_meta_on_success($post_id, $post_body, $response);
143 143
 	}
144 144
 
145 145
 	/**
@@ -151,16 +151,16 @@  discard block
 block discarded – undo
151 151
 	 *
152 152
 	 * @return array|bool
153 153
 	 */
154
-	public static function save_response_to_meta_on_success( $post_id, $post_body, $response ) {
154
+	public static function save_response_to_meta_on_success($post_id, $post_body, $response) {
155 155
 		// If body exists then decode the body.
156
-		$body = json_decode( $response->get_body(), true );
157
-		if ( empty( $body ) || ! array_key_exists( self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY, $body ) ) {
156
+		$body = json_decode($response->get_body(), true);
157
+		if (empty($body) || ! array_key_exists(self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY, $body)) {
158 158
 			// Bail out if we get an incorrect response
159 159
 			return false;
160 160
 		} else {
161
-			$post_excerpt = (string) $body[ self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY ];
161
+			$post_excerpt = (string) $body[self::WORDLIFT_POST_EXCERPT_RESPONSE_KEY];
162 162
 			// Save it to meta.
163
-			self::save_post_excerpt_in_meta( $post_id, $post_excerpt, $post_body );
163
+			self::save_post_excerpt_in_meta($post_id, $post_excerpt, $post_body);
164 164
 
165 165
 			return array(
166 166
 				'post_excerpt' => $post_excerpt,
@@ -178,13 +178,13 @@  discard block
 block discarded – undo
178 178
 	 *
179 179
 	 * @return void
180 180
 	 */
181
-	public static function save_post_excerpt_in_meta( $post_id, $post_excerpt, $post_body ) {
181
+	public static function save_post_excerpt_in_meta($post_id, $post_excerpt, $post_body) {
182 182
 		// hash the post body and save it.
183 183
 		$data = array(
184
-			'post_body_hash' => md5( $post_body ),
184
+			'post_body_hash' => md5($post_body),
185 185
 			'post_excerpt'   => $post_excerpt,
186 186
 		);
187
-		update_post_meta( $post_id, self::POST_EXCERPT_META_KEY, $data );
187
+		update_post_meta($post_id, self::POST_EXCERPT_META_KEY, $data);
188 188
 	}
189 189
 
190 190
 	/**
@@ -192,18 +192,18 @@  discard block
 block discarded – undo
192 192
 	 */
193 193
 	public static function register_route_callback() {
194 194
 		/** @var  $post_id_validation_settings array Settings used to validate post id */
195
-		$post_id_validation_settings   = array(
195
+		$post_id_validation_settings = array(
196 196
 			'required'          => true,
197 197
 			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
198
-			'validate_callback' => function ( $param, $request, $key ) {
199
-				return is_numeric( $param );
198
+			'validate_callback' => function($param, $request, $key) {
199
+				return is_numeric($param);
200 200
 			},
201 201
 		);
202 202
 		$post_body_validation_settings = array(
203 203
 			'required'          => true,
204 204
 			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
205
-			'validate_callback' => function ( $param, $request, $key ) {
206
-				return is_string( $param );
205
+			'validate_callback' => function($param, $request, $key) {
206
+				return is_string($param);
207 207
 			},
208 208
 		);
209 209
 		/**
@@ -211,12 +211,12 @@  discard block
 block discarded – undo
211 211
 		 */
212 212
 		register_rest_route(
213 213
 			WL_REST_ROUTE_DEFAULT_NAMESPACE,
214
-			'/' . self::POST_EXCERPT_NAMESPACE . '/(?P<post_id>\d+)',
214
+			'/'.self::POST_EXCERPT_NAMESPACE.'/(?P<post_id>\d+)',
215 215
 			array(
216 216
 				'methods'             => \WP_REST_Server::CREATABLE,
217 217
 				'callback'            => 'Wordlift\Post_Excerpt\Post_Excerpt_Rest_Controller::get_post_excerpt',
218
-				'permission_callback' => function () {
219
-					return current_user_can( 'publish_posts' );
218
+				'permission_callback' => function() {
219
+					return current_user_can('publish_posts');
220 220
 				},
221 221
 				'args'                => array(
222 222
 					'post_id'   => $post_id_validation_settings,
Please login to merge, or discard this patch.
src/wordlift/autocomplete/class-linked-data-autocomplete-service.php 2 patches
Indentation   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -18,168 +18,168 @@
 block discarded – undo
18 18
 
19 19
 class Linked_Data_Autocomplete_Service implements Autocomplete_Service {
20 20
 
21
-	/**
22
-	 * A {@link Wordlift_Log_Service} instance.
23
-	 *
24
-	 * @since  3.15.0
25
-	 * @access private
26
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
27
-	 */
28
-	private $log;
29
-	private $entity_helper;
30
-	private $entity_uri_service;
31
-	/**
32
-	 * @var \Wordlift_Entity_Service
33
-	 */
34
-	private $entity_service;
35
-
36
-	/**
37
-	 * The {@link Class_Wordlift_Autocomplete_Service} instance.
38
-	 *
39
-	 * @param Entity_Helper                $entity_helper
40
-	 * @param \Wordlift_Entity_Uri_Service $entity_uri_service
41
-	 * @param \Wordlift_Entity_Service     $entity_service
42
-	 *
43
-	 * @since 3.15.0
44
-	 */
45
-	public function __construct( $entity_helper, $entity_uri_service, $entity_service ) {
46
-
47
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Autocomplete_Service' );
48
-
49
-		$this->entity_helper      = $entity_helper;
50
-		$this->entity_uri_service = $entity_uri_service;
51
-		$this->entity_service     = $entity_service;
52
-
53
-	}
54
-
55
-	/**
56
-	 * Make request to external API and return the response.
57
-	 *
58
-	 * @param string       $query The search string.
59
-	 * @param string       $scope The search scope: "local" will search only in the local dataset; "cloud" will search also
60
-	 *                            in Wikipedia. By default is "cloud".
61
-	 * @param array|string $excludes The exclude parameter string.
62
-	 *
63
-	 * @return array $response The API response.
64
-	 * @since 3.15.0
65
-	 */
66
-	public function query( $query, $scope = 'cloud', $excludes = array() ) {
67
-
68
-		$results = $this->do_query( $query, $scope, $excludes );
69
-
70
-		$uris = array_reduce(
71
-			$results,
72
-			function ( $carry, $result ) {
73
-
74
-				$carry[] = $result['id'];
75
-
76
-				return array_merge( $carry, $result['sameAss'] );
77
-			},
78
-			array()
79
-		);
80
-
81
-		$mappings = $this->entity_helper->map_many_to_local( $uris );
82
-
83
-		$that           = $this;
84
-		$mapped_results = array_map(
85
-			function ( $result ) use ( $that, $mappings ) {
86
-
87
-				if ( $that->entity_uri_service->is_internal( $result['id'] ) ) {
88
-					  return $result;
89
-				}
90
-
91
-				$uris = array_merge( (array) $result['id'], $result['sameAss'] );
92
-
93
-				foreach ( $uris as $uri ) {
94
-					if ( isset( $mappings[ $uri ] ) ) {
95
-						$local_entity = $that->entity_uri_service->get_entity( $mappings[ $uri ] );
96
-
97
-						return $that->post_to_autocomplete_result( $mappings[ $uri ], $local_entity );
98
-					}
99
-				}
100
-
101
-				return $result;
102
-			},
103
-			$results
104
-		);
105
-
106
-		return $mapped_results;
107
-	}
108
-
109
-	private function do_query( $query, $scope = 'cloud', $exclude = '' ) {
110
-		$url = $this->build_request_url( $query, $exclude, $scope );
111
-
112
-		// Return the response.
113
-		$response = Default_Api_Service::get_instance()->get( $url )->get_response();
114
-
115
-		// If the response is valid, then send the suggestions.
116
-		if ( ! is_wp_error( $response ) && 200 === (int) $response['response']['code'] ) {
117
-			// Echo the response.
118
-			return json_decode( wp_remote_retrieve_body( $response ), true );
119
-		} else {
120
-			// Default error message.
121
-			$error_message = 'Something went wrong.';
122
-
123
-			// Get the real error message if there is WP_Error.
124
-			if ( is_wp_error( $response ) ) {
125
-				$error_message = $response->get_error_message();
126
-			}
127
-
128
-			$this->log->error( $error_message );
129
-
130
-			return array();
131
-		}
132
-	}
133
-
134
-	/**
135
-	 * Build the autocomplete url.
136
-	 *
137
-	 * @param string       $query The search string.
138
-	 * @param array|string $exclude The exclude parameter.
139
-	 * @param string       $scope The search scope: "local" will search only in the local dataset; "cloud" will search also
140
-	 *                            in Wikipedia. By default is "cloud".
141
-	 *
142
-	 * @return string Built url.
143
-	 * @since 3.15.0
144
-	 */
145
-	private function build_request_url( $query, $exclude, $scope ) {
146
-		$configuration_service = Wordlift_Configuration_Service::get_instance();
147
-
148
-		$args = array(
149
-			'key'      => $configuration_service->get_key(),
150
-			'language' => $configuration_service->get_language_code(),
151
-			'query'    => $query,
152
-			'scope'    => $scope,
153
-			'limit'    => 10,
154
-		);
155
-
156
-		// Add args to URL.
157
-		$request_url = add_query_arg( urlencode_deep( $args ), '/autocomplete' );
158
-
159
-		// Add the exclude parameter.
160
-		if ( ! empty( $exclude ) ) {
161
-			$request_url .= '&exclude=' . implode( '&exclude=', array_map( 'urlencode', (array) $exclude ) );
162
-		}
163
-
164
-		// return the built url.
165
-		return $request_url;
166
-	}
167
-
168
-	private function post_to_autocomplete_result( $uri, $post ) {
169
-
170
-		return array(
171
-			'id'           => $uri,
172
-			'label'        => array( $post->post_title ),
173
-			'labels'       => $this->entity_service->get_alternative_labels( $post->ID ),
174
-			'descriptions' => array( Wordlift_Post_Excerpt_Helper::get_text_excerpt( $post ) ),
175
-			'scope'        => 'local',
176
-			'sameAss'      => get_post_meta( $post->ID, Wordlift_Schema_Service::FIELD_SAME_AS ),
177
-			// The following properties are less relevant because we're linking entities that exist already in the
178
-			// vocabulary. That's why we don't make an effort to load the real data.
179
-			'types'        => array( 'http://schema.org/Thing' ),
180
-			'urls'         => array(),
181
-			'images'       => array(),
182
-		);
183
-	}
21
+    /**
22
+     * A {@link Wordlift_Log_Service} instance.
23
+     *
24
+     * @since  3.15.0
25
+     * @access private
26
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
27
+     */
28
+    private $log;
29
+    private $entity_helper;
30
+    private $entity_uri_service;
31
+    /**
32
+     * @var \Wordlift_Entity_Service
33
+     */
34
+    private $entity_service;
35
+
36
+    /**
37
+     * The {@link Class_Wordlift_Autocomplete_Service} instance.
38
+     *
39
+     * @param Entity_Helper                $entity_helper
40
+     * @param \Wordlift_Entity_Uri_Service $entity_uri_service
41
+     * @param \Wordlift_Entity_Service     $entity_service
42
+     *
43
+     * @since 3.15.0
44
+     */
45
+    public function __construct( $entity_helper, $entity_uri_service, $entity_service ) {
46
+
47
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Autocomplete_Service' );
48
+
49
+        $this->entity_helper      = $entity_helper;
50
+        $this->entity_uri_service = $entity_uri_service;
51
+        $this->entity_service     = $entity_service;
52
+
53
+    }
54
+
55
+    /**
56
+     * Make request to external API and return the response.
57
+     *
58
+     * @param string       $query The search string.
59
+     * @param string       $scope The search scope: "local" will search only in the local dataset; "cloud" will search also
60
+     *                            in Wikipedia. By default is "cloud".
61
+     * @param array|string $excludes The exclude parameter string.
62
+     *
63
+     * @return array $response The API response.
64
+     * @since 3.15.0
65
+     */
66
+    public function query( $query, $scope = 'cloud', $excludes = array() ) {
67
+
68
+        $results = $this->do_query( $query, $scope, $excludes );
69
+
70
+        $uris = array_reduce(
71
+            $results,
72
+            function ( $carry, $result ) {
73
+
74
+                $carry[] = $result['id'];
75
+
76
+                return array_merge( $carry, $result['sameAss'] );
77
+            },
78
+            array()
79
+        );
80
+
81
+        $mappings = $this->entity_helper->map_many_to_local( $uris );
82
+
83
+        $that           = $this;
84
+        $mapped_results = array_map(
85
+            function ( $result ) use ( $that, $mappings ) {
86
+
87
+                if ( $that->entity_uri_service->is_internal( $result['id'] ) ) {
88
+                        return $result;
89
+                }
90
+
91
+                $uris = array_merge( (array) $result['id'], $result['sameAss'] );
92
+
93
+                foreach ( $uris as $uri ) {
94
+                    if ( isset( $mappings[ $uri ] ) ) {
95
+                        $local_entity = $that->entity_uri_service->get_entity( $mappings[ $uri ] );
96
+
97
+                        return $that->post_to_autocomplete_result( $mappings[ $uri ], $local_entity );
98
+                    }
99
+                }
100
+
101
+                return $result;
102
+            },
103
+            $results
104
+        );
105
+
106
+        return $mapped_results;
107
+    }
108
+
109
+    private function do_query( $query, $scope = 'cloud', $exclude = '' ) {
110
+        $url = $this->build_request_url( $query, $exclude, $scope );
111
+
112
+        // Return the response.
113
+        $response = Default_Api_Service::get_instance()->get( $url )->get_response();
114
+
115
+        // If the response is valid, then send the suggestions.
116
+        if ( ! is_wp_error( $response ) && 200 === (int) $response['response']['code'] ) {
117
+            // Echo the response.
118
+            return json_decode( wp_remote_retrieve_body( $response ), true );
119
+        } else {
120
+            // Default error message.
121
+            $error_message = 'Something went wrong.';
122
+
123
+            // Get the real error message if there is WP_Error.
124
+            if ( is_wp_error( $response ) ) {
125
+                $error_message = $response->get_error_message();
126
+            }
127
+
128
+            $this->log->error( $error_message );
129
+
130
+            return array();
131
+        }
132
+    }
133
+
134
+    /**
135
+     * Build the autocomplete url.
136
+     *
137
+     * @param string       $query The search string.
138
+     * @param array|string $exclude The exclude parameter.
139
+     * @param string       $scope The search scope: "local" will search only in the local dataset; "cloud" will search also
140
+     *                            in Wikipedia. By default is "cloud".
141
+     *
142
+     * @return string Built url.
143
+     * @since 3.15.0
144
+     */
145
+    private function build_request_url( $query, $exclude, $scope ) {
146
+        $configuration_service = Wordlift_Configuration_Service::get_instance();
147
+
148
+        $args = array(
149
+            'key'      => $configuration_service->get_key(),
150
+            'language' => $configuration_service->get_language_code(),
151
+            'query'    => $query,
152
+            'scope'    => $scope,
153
+            'limit'    => 10,
154
+        );
155
+
156
+        // Add args to URL.
157
+        $request_url = add_query_arg( urlencode_deep( $args ), '/autocomplete' );
158
+
159
+        // Add the exclude parameter.
160
+        if ( ! empty( $exclude ) ) {
161
+            $request_url .= '&exclude=' . implode( '&exclude=', array_map( 'urlencode', (array) $exclude ) );
162
+        }
163
+
164
+        // return the built url.
165
+        return $request_url;
166
+    }
167
+
168
+    private function post_to_autocomplete_result( $uri, $post ) {
169
+
170
+        return array(
171
+            'id'           => $uri,
172
+            'label'        => array( $post->post_title ),
173
+            'labels'       => $this->entity_service->get_alternative_labels( $post->ID ),
174
+            'descriptions' => array( Wordlift_Post_Excerpt_Helper::get_text_excerpt( $post ) ),
175
+            'scope'        => 'local',
176
+            'sameAss'      => get_post_meta( $post->ID, Wordlift_Schema_Service::FIELD_SAME_AS ),
177
+            // The following properties are less relevant because we're linking entities that exist already in the
178
+            // vocabulary. That's why we don't make an effort to load the real data.
179
+            'types'        => array( 'http://schema.org/Thing' ),
180
+            'urls'         => array(),
181
+            'images'       => array(),
182
+        );
183
+    }
184 184
 
185 185
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -42,9 +42,9 @@  discard block
 block discarded – undo
42 42
 	 *
43 43
 	 * @since 3.15.0
44 44
 	 */
45
-	public function __construct( $entity_helper, $entity_uri_service, $entity_service ) {
45
+	public function __construct($entity_helper, $entity_uri_service, $entity_service) {
46 46
 
47
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Autocomplete_Service' );
47
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Autocomplete_Service');
48 48
 
49 49
 		$this->entity_helper      = $entity_helper;
50 50
 		$this->entity_uri_service = $entity_uri_service;
@@ -63,38 +63,38 @@  discard block
 block discarded – undo
63 63
 	 * @return array $response The API response.
64 64
 	 * @since 3.15.0
65 65
 	 */
66
-	public function query( $query, $scope = 'cloud', $excludes = array() ) {
66
+	public function query($query, $scope = 'cloud', $excludes = array()) {
67 67
 
68
-		$results = $this->do_query( $query, $scope, $excludes );
68
+		$results = $this->do_query($query, $scope, $excludes);
69 69
 
70 70
 		$uris = array_reduce(
71 71
 			$results,
72
-			function ( $carry, $result ) {
72
+			function($carry, $result) {
73 73
 
74 74
 				$carry[] = $result['id'];
75 75
 
76
-				return array_merge( $carry, $result['sameAss'] );
76
+				return array_merge($carry, $result['sameAss']);
77 77
 			},
78 78
 			array()
79 79
 		);
80 80
 
81
-		$mappings = $this->entity_helper->map_many_to_local( $uris );
81
+		$mappings = $this->entity_helper->map_many_to_local($uris);
82 82
 
83 83
 		$that           = $this;
84 84
 		$mapped_results = array_map(
85
-			function ( $result ) use ( $that, $mappings ) {
85
+			function($result) use ($that, $mappings) {
86 86
 
87
-				if ( $that->entity_uri_service->is_internal( $result['id'] ) ) {
87
+				if ($that->entity_uri_service->is_internal($result['id'])) {
88 88
 					  return $result;
89 89
 				}
90 90
 
91
-				$uris = array_merge( (array) $result['id'], $result['sameAss'] );
91
+				$uris = array_merge((array) $result['id'], $result['sameAss']);
92 92
 
93
-				foreach ( $uris as $uri ) {
94
-					if ( isset( $mappings[ $uri ] ) ) {
95
-						$local_entity = $that->entity_uri_service->get_entity( $mappings[ $uri ] );
93
+				foreach ($uris as $uri) {
94
+					if (isset($mappings[$uri])) {
95
+						$local_entity = $that->entity_uri_service->get_entity($mappings[$uri]);
96 96
 
97
-						return $that->post_to_autocomplete_result( $mappings[ $uri ], $local_entity );
97
+						return $that->post_to_autocomplete_result($mappings[$uri], $local_entity);
98 98
 					}
99 99
 				}
100 100
 
@@ -106,26 +106,26 @@  discard block
 block discarded – undo
106 106
 		return $mapped_results;
107 107
 	}
108 108
 
109
-	private function do_query( $query, $scope = 'cloud', $exclude = '' ) {
110
-		$url = $this->build_request_url( $query, $exclude, $scope );
109
+	private function do_query($query, $scope = 'cloud', $exclude = '') {
110
+		$url = $this->build_request_url($query, $exclude, $scope);
111 111
 
112 112
 		// Return the response.
113
-		$response = Default_Api_Service::get_instance()->get( $url )->get_response();
113
+		$response = Default_Api_Service::get_instance()->get($url)->get_response();
114 114
 
115 115
 		// If the response is valid, then send the suggestions.
116
-		if ( ! is_wp_error( $response ) && 200 === (int) $response['response']['code'] ) {
116
+		if ( ! is_wp_error($response) && 200 === (int) $response['response']['code']) {
117 117
 			// Echo the response.
118
-			return json_decode( wp_remote_retrieve_body( $response ), true );
118
+			return json_decode(wp_remote_retrieve_body($response), true);
119 119
 		} else {
120 120
 			// Default error message.
121 121
 			$error_message = 'Something went wrong.';
122 122
 
123 123
 			// Get the real error message if there is WP_Error.
124
-			if ( is_wp_error( $response ) ) {
124
+			if (is_wp_error($response)) {
125 125
 				$error_message = $response->get_error_message();
126 126
 			}
127 127
 
128
-			$this->log->error( $error_message );
128
+			$this->log->error($error_message);
129 129
 
130 130
 			return array();
131 131
 		}
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 	 * @return string Built url.
143 143
 	 * @since 3.15.0
144 144
 	 */
145
-	private function build_request_url( $query, $exclude, $scope ) {
145
+	private function build_request_url($query, $exclude, $scope) {
146 146
 		$configuration_service = Wordlift_Configuration_Service::get_instance();
147 147
 
148 148
 		$args = array(
@@ -154,29 +154,29 @@  discard block
 block discarded – undo
154 154
 		);
155 155
 
156 156
 		// Add args to URL.
157
-		$request_url = add_query_arg( urlencode_deep( $args ), '/autocomplete' );
157
+		$request_url = add_query_arg(urlencode_deep($args), '/autocomplete');
158 158
 
159 159
 		// Add the exclude parameter.
160
-		if ( ! empty( $exclude ) ) {
161
-			$request_url .= '&exclude=' . implode( '&exclude=', array_map( 'urlencode', (array) $exclude ) );
160
+		if ( ! empty($exclude)) {
161
+			$request_url .= '&exclude='.implode('&exclude=', array_map('urlencode', (array) $exclude));
162 162
 		}
163 163
 
164 164
 		// return the built url.
165 165
 		return $request_url;
166 166
 	}
167 167
 
168
-	private function post_to_autocomplete_result( $uri, $post ) {
168
+	private function post_to_autocomplete_result($uri, $post) {
169 169
 
170 170
 		return array(
171 171
 			'id'           => $uri,
172
-			'label'        => array( $post->post_title ),
173
-			'labels'       => $this->entity_service->get_alternative_labels( $post->ID ),
174
-			'descriptions' => array( Wordlift_Post_Excerpt_Helper::get_text_excerpt( $post ) ),
172
+			'label'        => array($post->post_title),
173
+			'labels'       => $this->entity_service->get_alternative_labels($post->ID),
174
+			'descriptions' => array(Wordlift_Post_Excerpt_Helper::get_text_excerpt($post)),
175 175
 			'scope'        => 'local',
176
-			'sameAss'      => get_post_meta( $post->ID, Wordlift_Schema_Service::FIELD_SAME_AS ),
176
+			'sameAss'      => get_post_meta($post->ID, Wordlift_Schema_Service::FIELD_SAME_AS),
177 177
 			// The following properties are less relevant because we're linking entities that exist already in the
178 178
 			// vocabulary. That's why we don't make an effort to load the real data.
179
-			'types'        => array( 'http://schema.org/Thing' ),
179
+			'types'        => array('http://schema.org/Thing'),
180 180
 			'urls'         => array(),
181 181
 			'images'       => array(),
182 182
 		);
Please login to merge, or discard this patch.
src/wordlift/autocomplete/class-all-autocomplete-service.php 2 patches
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -12,62 +12,62 @@
 block discarded – undo
12 12
 
13 13
 class All_Autocomplete_Service implements Autocomplete_Service {
14 14
 
15
-	/**
16
-	 * One ore more {@link Autocomplete_Service} instances.
17
-	 *
18
-	 * @var Autocomplete_Service|Autocomplete_Service[] $autocomplete_services
19
-	 */
20
-	private $autocomplete_services;
15
+    /**
16
+     * One ore more {@link Autocomplete_Service} instances.
17
+     *
18
+     * @var Autocomplete_Service|Autocomplete_Service[] $autocomplete_services
19
+     */
20
+    private $autocomplete_services;
21 21
 
22
-	/**
23
-	 * All_Autocomplete_Service constructor.
24
-	 *
25
-	 * @param Autocomplete_Service|Autocomplete_Service[] $autocomplete_services
26
-	 */
27
-	public function __construct( $autocomplete_services ) {
22
+    /**
23
+     * All_Autocomplete_Service constructor.
24
+     *
25
+     * @param Autocomplete_Service|Autocomplete_Service[] $autocomplete_services
26
+     */
27
+    public function __construct( $autocomplete_services ) {
28 28
 
29
-		$this->autocomplete_services = (array) $autocomplete_services;
30
-	}
29
+        $this->autocomplete_services = (array) $autocomplete_services;
30
+    }
31 31
 
32
-	/**
33
-	 * {@inheritDoc}
34
-	 */
35
-	public function query( $query, $scope, $excludes ) {
32
+    /**
33
+     * {@inheritDoc}
34
+     */
35
+    public function query( $query, $scope, $excludes ) {
36 36
 
37
-		/**
38
-		 * Filter to show local entities on the entity autocompletion field.
39
-		 *
40
-		 * @param $state bool
41
-		 *
42
-		 * @return bool Whether to show local entities in the page or not.
43
-		 * @since 3.26.1
44
-		 */
45
-		$show_local_entities = apply_filters( 'wl_show_local_entities', false );
37
+        /**
38
+         * Filter to show local entities on the entity autocompletion field.
39
+         *
40
+         * @param $state bool
41
+         *
42
+         * @return bool Whether to show local entities in the page or not.
43
+         * @since 3.26.1
44
+         */
45
+        $show_local_entities = apply_filters( 'wl_show_local_entities', false );
46 46
 
47
-		$autocomplete_services = $this->autocomplete_services;
47
+        $autocomplete_services = $this->autocomplete_services;
48 48
 
49
-		// Remove the local autocomplete services.
50
-		if ( ! $show_local_entities ) {
51
-			$autocomplete_services = array_filter(
52
-				$autocomplete_services,
53
-				function ( $service ) {
54
-					return ! $service instanceof Local_Autocomplete_Service;
55
-				}
56
-			);
57
-		}
49
+        // Remove the local autocomplete services.
50
+        if ( ! $show_local_entities ) {
51
+            $autocomplete_services = array_filter(
52
+                $autocomplete_services,
53
+                function ( $service ) {
54
+                    return ! $service instanceof Local_Autocomplete_Service;
55
+                }
56
+            );
57
+        }
58 58
 
59
-		// Query each Autocomplete service and merge the results.
60
-		return array_reduce(
61
-			$autocomplete_services,
62
-			function ( $carry, $item ) use ( $query, $scope, $excludes ) {
59
+        // Query each Autocomplete service and merge the results.
60
+        return array_reduce(
61
+            $autocomplete_services,
62
+            function ( $carry, $item ) use ( $query, $scope, $excludes ) {
63 63
 
64
-				$results = $item->query( $query, $scope, $excludes );
64
+                $results = $item->query( $query, $scope, $excludes );
65 65
 
66
-				return array_merge( $carry, $results );
67
-			},
68
-			array()
69
-		);
66
+                return array_merge( $carry, $results );
67
+            },
68
+            array()
69
+        );
70 70
 
71
-	}
71
+    }
72 72
 
73 73
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
 	 *
25 25
 	 * @param Autocomplete_Service|Autocomplete_Service[] $autocomplete_services
26 26
 	 */
27
-	public function __construct( $autocomplete_services ) {
27
+	public function __construct($autocomplete_services) {
28 28
 
29 29
 		$this->autocomplete_services = (array) $autocomplete_services;
30 30
 	}
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
 	/**
33 33
 	 * {@inheritDoc}
34 34
 	 */
35
-	public function query( $query, $scope, $excludes ) {
35
+	public function query($query, $scope, $excludes) {
36 36
 
37 37
 		/**
38 38
 		 * Filter to show local entities on the entity autocompletion field.
@@ -42,15 +42,15 @@  discard block
 block discarded – undo
42 42
 		 * @return bool Whether to show local entities in the page or not.
43 43
 		 * @since 3.26.1
44 44
 		 */
45
-		$show_local_entities = apply_filters( 'wl_show_local_entities', false );
45
+		$show_local_entities = apply_filters('wl_show_local_entities', false);
46 46
 
47 47
 		$autocomplete_services = $this->autocomplete_services;
48 48
 
49 49
 		// Remove the local autocomplete services.
50
-		if ( ! $show_local_entities ) {
50
+		if ( ! $show_local_entities) {
51 51
 			$autocomplete_services = array_filter(
52 52
 				$autocomplete_services,
53
-				function ( $service ) {
53
+				function($service) {
54 54
 					return ! $service instanceof Local_Autocomplete_Service;
55 55
 				}
56 56
 			);
@@ -59,11 +59,11 @@  discard block
 block discarded – undo
59 59
 		// Query each Autocomplete service and merge the results.
60 60
 		return array_reduce(
61 61
 			$autocomplete_services,
62
-			function ( $carry, $item ) use ( $query, $scope, $excludes ) {
62
+			function($carry, $item) use ($query, $scope, $excludes) {
63 63
 
64
-				$results = $item->query( $query, $scope, $excludes );
64
+				$results = $item->query($query, $scope, $excludes);
65 65
 
66
-				return array_merge( $carry, $results );
66
+				return array_merge($carry, $results);
67 67
 			},
68 68
 			array()
69 69
 		);
Please login to merge, or discard this patch.