Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
46.28% covered (danger)
46.28%
56 / 121
90.00% covered (success)
90.00%
9 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
REST_Controller
46.28% covered (danger)
46.28%
56 / 121
90.00% covered (success)
90.00%
9 / 10
68.23
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 register_rest_routes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_routes
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
1
 permissions_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 get_items
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 get_item
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 get_item_schema
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 1
6
 get_visible_announcement
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 is_visible
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 to_record
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * REST routes of the announcements.
4 *
5 * @package automattic/jetpack-announcements
6 */
7
8namespace Automattic\Jetpack\Announcements;
9
10use WP_Error;
11use WP_REST_Controller;
12use WP_REST_Request;
13use WP_REST_Response;
14use WP_REST_Server;
15
16/**
17 * Serves the announcements the current user may see.
18 *
19 * The routes give a core-data entity what it needs: a collection of records that carry
20 * their key, and an item route.
21 */
22class REST_Controller extends WP_REST_Controller {
23
24    /**
25     * Sets the route names. `wpcom/v2` reaches connected sites and WordPress.com Simple.
26     */
27    public function __construct() {
28        $this->namespace = 'wpcom/v2';
29        $this->rest_base = 'jetpack-announcements';
30    }
31
32    /**
33     * Registers the routes. Hooked on `rest_api_init`.
34     *
35     * @return void
36     */
37    public static function register_rest_routes() {
38        ( new self() )->register_routes();
39    }
40
41    /**
42     * Registers the collection route and the item route.
43     *
44     * @return void
45     */
46    public function register_routes() {
47        register_rest_route(
48            $this->namespace,
49            '/' . $this->rest_base,
50            array(
51                array(
52                    // @phan-suppress-next-line PhanPluginMixedKeyNoKey -- register_rest_route() mixes the endpoint list with a route-level `schema` key.
53                    'methods'             => WP_REST_Server::READABLE,
54                    'callback'            => array( $this, 'get_items' ),
55                    'permission_callback' => array( $this, 'permissions_check' ),
56                ),
57                'schema' => array( $this, 'get_public_item_schema' ),
58            )
59        );
60
61        register_rest_route(
62            $this->namespace,
63            '/' . $this->rest_base . '/(?P<id>' . Announcement_Registry::ID_PATTERN . ')',
64            array(
65                array(
66                    // @phan-suppress-next-line PhanPluginMixedKeyNoKey -- register_rest_route() mixes the endpoint list with a route-level `schema` key.
67                    'methods'             => WP_REST_Server::READABLE,
68                    'callback'            => array( $this, 'get_item' ),
69                    'permission_callback' => array( $this, 'permissions_check' ),
70                ),
71                'schema' => array( $this, 'get_public_item_schema' ),
72            )
73        );
74    }
75
76    /**
77     * Requires a logged-in user. What each user may see is decided per announcement.
78     *
79     * @return true|WP_Error
80     */
81    public function permissions_check() {
82        if ( ! is_user_logged_in() ) {
83            return new WP_Error(
84                'rest_not_logged_in',
85                __( 'You are not currently logged in.', 'jetpack-announcements' ),
86                array( 'status' => 401 )
87            );
88        }
89
90        return true;
91    }
92
93    /**
94     * Retrieves the announcements the current user may see, of every channel.
95     *
96     * @param WP_REST_Request $request Unused.
97     * @return WP_REST_Response
98     */
99    public function get_items( $request ) {
100        unset( $request );
101
102        $records = array();
103
104        foreach ( Announcement_Registry::get_instance()->get_all_registered() as $announcement ) {
105            if ( self::is_visible( $announcement ) ) {
106                $records[] = self::to_record( $announcement );
107            }
108        }
109
110        return rest_ensure_response( $records );
111    }
112
113    /**
114     * Retrieves one announcement.
115     *
116     * @param WP_REST_Request $request Request carrying the id.
117     * @return WP_REST_Response|WP_Error
118     */
119    public function get_item( $request ) {
120        $announcement = self::get_visible_announcement( $request );
121        if ( is_wp_error( $announcement ) ) {
122            return $announcement;
123        }
124
125        return rest_ensure_response( self::to_record( $announcement ) );
126    }
127
128    /**
129     * Retrieves the schema of an announcement record.
130     *
131     * @return array
132     */
133    public function get_item_schema() {
134        if ( $this->schema ) {
135            return $this->add_additional_fields_schema( $this->schema );
136        }
137
138        $this->schema = array(
139            '$schema'    => 'http://json-schema.org/draft-04/schema#',
140            'title'      => 'jetpack-announcement',
141            'type'       => 'object',
142            'properties' => array(
143                'id'       => array(
144                    'description' => __( 'Namespaced identifier of the announcement.', 'jetpack-announcements' ),
145                    'type'        => 'string',
146                    'readonly'    => true,
147                ),
148                'date'     => array(
149                    'description' => __( 'The date the announcement was published, as GMT.', 'jetpack-announcements' ),
150                    'type'        => 'string',
151                    'format'      => 'date-time',
152                    'readonly'    => true,
153                ),
154                'title'    => array(
155                    'description' => __( 'The title of the announcement, as plain text.', 'jetpack-announcements' ),
156                    'type'        => 'string',
157                    'readonly'    => true,
158                ),
159                'excerpt'  => array(
160                    'description' => __( 'A summary of the announcement, as plain text.', 'jetpack-announcements' ),
161                    'type'        => 'string',
162                    'readonly'    => true,
163                ),
164                'content'  => array(
165                    'description' => __( 'The body of the announcement, as HTML.', 'jetpack-announcements' ),
166                    'type'        => 'string',
167                    'readonly'    => true,
168                ),
169                'media'    => array(
170                    'description' => __( 'An image or a video shown with the announcement.', 'jetpack-announcements' ),
171                    'type'        => array( 'object', 'null' ),
172                    'readonly'    => true,
173                    'properties'  => array(
174                        'type' => array(
175                            'type' => 'string',
176                            'enum' => Announcement_Registry::MEDIA_TYPES,
177                        ),
178                        'url'  => array(
179                            'type'   => 'string',
180                            'format' => 'uri',
181                        ),
182                        'alt'  => array(
183                            'type' => 'string',
184                        ),
185                    ),
186                ),
187                'link'     => array(
188                    'description' => __( 'URL of the full article, or an empty string.', 'jetpack-announcements' ),
189                    'type'        => 'string',
190                    'readonly'    => true,
191                ),
192                'channels' => array(
193                    'description' => __( 'The channels the announcement is published to.', 'jetpack-announcements' ),
194                    'type'        => 'array',
195                    'items'       => array( 'type' => 'string' ),
196                    'readonly'    => true,
197                ),
198            ),
199        );
200
201        return $this->add_additional_fields_schema( $this->schema );
202    }
203
204    /**
205     * Retrieves the announcement a request names, if the current user may see it.
206     *
207     * @param WP_REST_Request $request Request carrying the id.
208     * @return array|WP_Error The announcement, or a 404 error.
209     */
210    private static function get_visible_announcement( $request ) {
211        // Read from the URL alone: a query parameter of the same name would win.
212        $id           = $request->get_url_params()['id'] ?? '';
213        $announcement = Announcement_Registry::get_instance()->get_registered( $id );
214
215        if ( null === $announcement || ! self::is_visible( $announcement ) ) {
216            return new WP_Error(
217                'rest_announcement_not_found',
218                __( 'Announcement not found.', 'jetpack-announcements' ),
219                array( 'status' => 404 )
220            );
221        }
222
223        return $announcement;
224    }
225
226    /**
227     * Whether the current user may see an announcement.
228     *
229     * @param array $announcement A registered announcement.
230     * @return bool
231     */
232    private static function is_visible( array $announcement ) {
233        return '' === $announcement['capability'] || current_user_can( $announcement['capability'] );
234    }
235
236    /**
237     * Builds the record a client receives: the announcement minus its capability.
238     *
239     * @param array $announcement A registered announcement.
240     * @return array
241     */
242    private static function to_record( array $announcement ) {
243        unset( $announcement['capability'] );
244
245        return $announcement;
246    }
247}