PluginProbe
Extendify / 3.1.4
Extendify v3.1.4
3.2.1 3.2.0 3.1.6 3.1.5 3.1.4 3.1.3 3.1.2 3.1.1 3.1.0 3.0.6 3.0.5 3.0.4 trunk 0.1.0 0.10.0 0.10.1 0.10.2 0.11.0 0.11.1 0.2.0 0.3.0 0.3.1 0.4.0 0.5.0 0.6.0 All 127 releases
extendify / app / Shared / Controllers / SiteImagesController.php

SiteImagesController.php in Extendify 3.1.4, at app/Shared/Controllers/SiteImagesController.php

100 lines 2.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Controls cached site images
5 */
6
7 namespace Extendify\Shared\Controllers;
8
9 defined('ABSPATH') || die('No direct access.');
10
11 use Extendify\Constants;
12 use Extendify\Shared\Services\HttpClient;
13 use Extendify\Shared\Services\Sanitizer;
14
15 /**
16 * The controller for the persisted site images cache
17 */
18
19 class SiteImagesController
20 {
21 /**
22 * Return cached site images, lazy-fetching from the images service when missing.
23 *
24 * @return \WP_REST_Response
25 */
26 public static function get()
27 {
28 $siteImages = \get_option('extendify_site_images', []);
29
30 if (!empty($siteImages)) {
31 return new \WP_REST_Response(['siteImages' => $siteImages]);
32 }
33
34 return new \WP_REST_Response(['siteImages' => self::refresh()]);
35 }
36
37 /**
38 * Persist a provided site images array.
39 *
40 * @param \WP_REST_Request $request - The request.
41 * @return \WP_REST_Response
42 */
43 public static function store($request)
44 {
45 $siteImages = $request->get_param('siteImages');
46 if (!is_array($siteImages)) {
47 $siteImages = [];
48 }
49
50 \update_option('extendify_site_images', Sanitizer::sanitizeArray($siteImages));
51 return new \WP_REST_Response(['siteImages' => $siteImages]);
52 }
53
54 /**
55 * Delete the cached site images option.
56 *
57 * @return \WP_REST_Response
58 */
59 public static function clear()
60 {
61 \delete_option('extendify_site_images');
62 return new \WP_REST_Response(['siteImages' => []]);
63 }
64
65 /**
66 * Fetch fresh images from the images service using the stored site profile,
67 * persist them, and return the array. Returns [] when the profile is empty
68 * or the upstream call fails.
69 *
70 * @return array
71 */
72 private static function refresh()
73 {
74 $siteProfile = \get_option('extendify_site_profile', []);
75 if (empty($siteProfile)) {
76 return [];
77 }
78
79 $response = HttpClient::post(
80 Constants::IMAGES_HOST . '/api/search',
81 [
82 'params' => [
83 'siteProfile' => $siteProfile,
84 'source' => 'shared',
85 ],
86 ],
87 null,
88 true
89 );
90
91 $siteImages = $response['response']['siteImages'] ?? [];
92 if (!is_array($siteImages) || empty($siteImages)) {
93 return [];
94 }
95
96 \update_option('extendify_site_images', Sanitizer::sanitizeArray($siteImages));
97 return $siteImages;
98 }
99 }
100