| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Controller for updating patterns based on their dependencies. |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Extendify\Shared\Controllers; |
| 8 |
|
| 9 |
defined('ABSPATH') || die('No direct access.'); |
| 10 |
|
| 11 |
use Extendify\Shared\Services\PluginDependencies\Forms\WPForms; |
| 12 |
use Extendify\Shared\Services\PluginDependencies\Forms\ContactForm7; |
| 13 |
use Extendify\Shared\Services\PluginDependencies\WooCommerce; |
| 14 |
use Extendify\Shared\Services\PluginDependencies\SimplyBook; |
| 15 |
|
| 16 |
/** |
| 17 |
* The controller for interacting with the pattern deps. |
| 18 |
*/ |
| 19 |
|
| 20 |
class PatternPlaceholderController |
| 21 |
{ |
| 22 |
// phpcs:ignore PSR12.Properties.ConstantVisibility.NotFound |
| 23 |
const PLUGIN_HANDLERS = [ |
| 24 |
'contact-form-7' => ContactForm7::class, |
| 25 |
'wpforms-lite' => WPForms::class, |
| 26 |
'woocommerce' => WooCommerce::class, |
| 27 |
'simplybook' => SimplyBook::class, |
| 28 |
]; |
| 29 |
|
| 30 |
/** |
| 31 |
* Replace all placeholders in the given content |
| 32 |
* |
| 33 |
* @param \WP_REST_Request $request - The request. |
| 34 |
* @return \WP_REST_Response |
| 35 |
*/ |
| 36 |
public static function processPlaceholders($request) |
| 37 |
{ |
| 38 |
$patterns = $request->get_param('patterns'); |
| 39 |
|
| 40 |
$patterns = array_map(function ($pattern) { |
| 41 |
$newCode = ($pattern['patternReplacementCode'] ?? null); |
| 42 |
$pluginDependency = ($pattern['pluginDependency'] ?? null); |
| 43 |
if (!$newCode || !$pluginDependency) { |
| 44 |
return $pattern; |
| 45 |
} |
| 46 |
|
| 47 |
$metadata = null; |
| 48 |
if (isset($pattern['patternMetadata'])) { |
| 49 |
$metadata = json_decode($pattern['patternMetadata'], true); |
| 50 |
} |
| 51 |
|
| 52 |
$handlerClass = isset(self::PLUGIN_HANDLERS[$pluginDependency]) |
| 53 |
? self::PLUGIN_HANDLERS[$pluginDependency] |
| 54 |
: null; |
| 55 |
if ($handlerClass && isset($metadata['key'])) { |
| 56 |
$pattern['code'] = $handlerClass::create($pattern['code'], $metadata['key'], $newCode); |
| 57 |
return $pattern; |
| 58 |
} |
| 59 |
|
| 60 |
// We added a feature this version doesn't yet support. |
| 61 |
return $pattern; |
| 62 |
}, $patterns); |
| 63 |
|
| 64 |
// if any of the pattern code is a wp_error, we need to fail. |
| 65 |
foreach ($patterns as $pattern) { |
| 66 |
if (is_wp_error($pattern['code'])) { |
| 67 |
return new \WP_REST_Response($pattern['code'], 422); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
return new \WP_REST_Response($patterns); |
| 72 |
} |
| 73 |
} |
| 74 |
|