PluginProbe
ElasticPress / 5.3.5
ElasticPress v5.3.5
5.3.5 5.3.4 3.6.5 3.6.6 4.0.0 4.0.1 4.1.0 4.2.0 4.2.1 4.2.2 4.3.0 4.3.1 4.4.0 4.4.1 4.5.0 4.5.1 4.5.2 4.6.0 4.6.1 4.7.0 4.7.1 4.7.2 5.0.0 5.0.1 5.0.2 All 108 releases
elasticpress / includes / classes / REST / Synonyms.php

Synonyms.php in ElasticPress 5.3.5, at includes/classes/REST/Synonyms.php

120 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Synonyms REST API Controller.
4 *
5 * @since 5.1.0
6 * @package elasticpress
7 */
8
9 namespace ElasticPress\REST;
10
11 use ElasticPress\Features;
12 use ElasticPress\Utils;
13
14 /**
15 * Synonyms API controller class.
16 *
17 * @since 5.1.0
18 * @package elasticpress
19 */
20 class Synonyms {
21
22 /**
23 * Register routes.
24 *
25 * @return void
26 */
27 public function register_routes() {
28 register_rest_route(
29 'elasticpress/v1',
30 'synonyms',
31 [
32 'args' => $this->get_args(),
33 'callback' => [ $this, 'update_synonyms' ],
34 'methods' => 'PUT',
35 'permission_callback' => [ $this, 'check_permission' ],
36 ]
37 );
38 }
39
40 /**
41 * Get args schema.
42 *
43 * @return array
44 */
45 public function get_args() {
46 $feature = Features::factory()->get_registered_feature( 'search' )->synonyms;
47
48 $args = [
49 'mode' => [
50 'default' => 'simple',
51 'description' => __( 'Synonyms editor mode.', 'elasticpress' ),
52 'enum' => [ 'advanced', 'simple' ],
53 ],
54 'solr' => [
55 'description' => __( 'Synonyms in Solr format.', 'elasticpress' ),
56 'type' => 'string',
57 'sanitize_callback' => [ $this, 'sanitize_solr' ],
58 ],
59 ];
60
61 return $args;
62 }
63
64 /**
65 * Check that the request has permission to save synonyms.
66 *
67 * @return boolean
68 */
69 public function check_permission() {
70 $capability = Utils\get_capability();
71
72 return current_user_can( $capability );
73 }
74
75 /**
76 * Sanitize Solr synonyms.
77 *
78 * @param string $value Solr synonyms,
79 * @return string
80 */
81 public function sanitize_solr( $value ) {
82 $solr = sanitize_textarea_field( $value );
83 $solr = preg_replace( '/\r\n|\r|\n/', PHP_EOL, $solr );
84
85 return $solr;
86 }
87
88 /**
89 * Update synonyms settings.
90 *
91 * @param \WP_REST_Request $request Full details about the request.
92 * @return array
93 */
94 public function update_synonyms( \WP_REST_Request $request ) {
95 $feature = Features::factory()->get_registered_feature( 'search' )->synonyms;
96
97 $mode = $request->get_param( 'mode' );
98 $solr = $request->get_param( 'solr' );
99
100 $post_id = $feature->update_synonym_post( $solr );
101
102 if ( ! $post_id || is_wp_error( $post_id ) ) {
103 return new \WP_Error( 'error-update-post' );
104 }
105
106 $updated = $feature->update_synonyms();
107
108 if ( ! $updated ) {
109 return new \WP_Error( 'error-update-index' );
110 }
111
112 $feature->save_editor_mode( $mode );
113
114 return [
115 'data' => $solr,
116 'success' => true,
117 ];
118 }
119 }
120