| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* WooCommerce pattern replacement. |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Extendify\Shared\Services\PluginDependencies; |
| 8 |
|
| 9 |
defined('ABSPATH') || die('No direct access.'); |
| 10 |
|
| 11 |
/** |
| 12 |
* WooCommerce pattern replacement class. |
| 13 |
*/ |
| 14 |
|
| 15 |
class WooCommerce |
| 16 |
{ |
| 17 |
/** |
| 18 |
* The plugin slug. |
| 19 |
* |
| 20 |
* @var string |
| 21 |
*/ |
| 22 |
public static $slug = 'woocommerce/woocommerce.php'; |
| 23 |
|
| 24 |
/** |
| 25 |
* Replace the placeholder for WooCommerce. |
| 26 |
* |
| 27 |
* @param mixed $code - The code data. |
| 28 |
* @param string $key - The plugin key. |
| 29 |
* @param string $newCode - The plugin pattern code. |
| 30 |
* @return mixed |
| 31 |
*/ |
| 32 |
public static function create($code, $key, $newCode) |
| 33 |
{ |
| 34 |
if ($key !== 'simple' || !preg_match('/wp:woocommerce/m', $newCode)) { |
| 35 |
return $code; |
| 36 |
} |
| 37 |
|
| 38 |
require_once ABSPATH . 'wp-admin/includes/plugin.php'; |
| 39 |
|
| 40 |
// If the plugin is already installed and active, we don't need to install it again. |
| 41 |
if (!is_plugin_active(self::$slug)) { |
| 42 |
$response = PluginInstaller::installPlugin('woocommerce', self::$slug); |
| 43 |
if (is_wp_error($response)) { |
| 44 |
return $response; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
if (!preg_match_all('/"categoryId":\s?\"?(\d+)\"?/', $newCode, $matches, PREG_SET_ORDER)) { |
| 49 |
return $newCode; |
| 50 |
} |
| 51 |
|
| 52 |
$categories = array_map(function ($item) { |
| 53 |
return [ |
| 54 |
'id' => $item->term_id, |
| 55 |
'url' => get_term_link($item->term_id, 'product_cat'), |
| 56 |
]; |
| 57 |
}, get_terms(['taxonomy' => 'product_cat'])); |
| 58 |
|
| 59 |
foreach ($matches as $key => $value) { |
| 60 |
// Replace the temporary id with the category id. |
| 61 |
$newCode = preg_replace( |
| 62 |
'/' . preg_quote($value[0], '/') . '/', |
| 63 |
str_replace($value[1], $categories[$key]['id'], $value[0]), |
| 64 |
$newCode, |
| 65 |
1 |
| 66 |
); |
| 67 |
|
| 68 |
// Replace the temporary placeholder URL with the actual category URL. |
| 69 |
$newCode = preg_replace( |
| 70 |
'/' . preg_quote('http://patterns.test/?product_cat=accessories', '/') . '/', |
| 71 |
$categories[$key]['url'], |
| 72 |
$newCode, |
| 73 |
1 |
| 74 |
); |
| 75 |
} |
| 76 |
|
| 77 |
return $newCode; |
| 78 |
} |
| 79 |
} |
| 80 |
|