| 1 |
<?php |
| 2 |
|
| 3 |
namespace Templately\Modules\BlockPatterns\REST; |
| 4 |
|
| 5 |
use Templately\API\API; |
| 6 |
use Templately\Modules\BlockPatterns\PatternSync; |
| 7 |
use WP_REST_Request; |
| 8 |
|
| 9 |
/** |
| 10 |
* The editor's own catalog refresh — so the library does not depend on cron. |
| 11 |
* |
| 12 |
* Cron is the wrong single point of failure for this: WP-Cron only fires when |
| 13 |
* someone visits the site, a stalled loopback disables it entirely, and it runs |
| 14 |
* with no user, which is what made the sync silently no-op on a locally |
| 15 |
* connected site (see PatternSync::OWNER_OPTION). The editor, by contrast, is |
| 16 |
* exactly where an empty library is noticed — and it arrives with a logged-in |
| 17 |
* user whose connection resolves without any borrowing. |
| 18 |
* |
| 19 |
* This is NOT a violation of "no editor-facing request may touch the network" |
| 20 |
* (spec 051 FR-001): that rule governs pattern REGISTRATION, which still reads |
| 21 |
* the local cache only and is what the inserter blocks on. This is a separate, |
| 22 |
* explicit request the editor makes AFTER it has loaded, and its result is |
| 23 |
* applied by invalidating the client's pattern cache — never by holding up a |
| 24 |
* render. |
| 25 |
*/ |
| 26 |
class Sync extends API { |
| 27 |
private $endpoint = 'block-patterns/sync'; |
| 28 |
|
| 29 |
public function permission_check( WP_REST_Request $request ) { |
| 30 |
$this->request = $request; |
| 31 |
|
| 32 |
return is_user_logged_in() && current_user_can( 'edit_posts' ); |
| 33 |
} |
| 34 |
|
| 35 |
public function register_routes() { |
| 36 |
$this->post( $this->endpoint, [ $this, 'sync' ] ); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* A no-op when the cache is fresh, which is the common case — the editor |
| 41 |
* calls this on every load and must not re-fetch the catalog each time. |
| 42 |
* Concurrent editors collapse onto one fetch via the sync lock. |
| 43 |
*/ |
| 44 |
public function sync() { |
| 45 |
$result = PatternSync::get_instance()->sync_if_stale(); |
| 46 |
|
| 47 |
return $this->success( [ |
| 48 |
'status' => $result['status'], |
| 49 |
'count' => $result['count'], |
| 50 |
'plan_key' => $result['plan_key'], |
| 51 |
// The client only needs to refresh its pattern store when the set it |
| 52 |
// already loaded is out of date. |
| 53 |
'changed' => 'synced' === $result['status'], |
| 54 |
] ); |
| 55 |
} |
| 56 |
} |
| 57 |
|