| 1 |
<?php |
| 2 |
|
| 3 |
namespace Extendify\QuickEdit\Schemas; |
| 4 |
|
| 5 |
defined('ABSPATH') || die('No direct access.'); |
| 6 |
|
| 7 |
class Button implements Schema |
| 8 |
{ |
| 9 |
public function fields(): array |
| 10 |
{ |
| 11 |
return [ |
| 12 |
[ |
| 13 |
'key' => 'text', |
| 14 |
'control' => 'text', |
| 15 |
'label' => __('Button text', 'extendify-local'), |
| 16 |
], |
| 17 |
[ |
| 18 |
'key' => 'url', |
| 19 |
'control' => 'link', |
| 20 |
'label' => __('Link URL', 'extendify-local'), |
| 21 |
], |
| 22 |
]; |
| 23 |
} |
| 24 |
|
| 25 |
public function apply(array $block, string $fieldKey, $value): array |
| 26 |
{ |
| 27 |
$existing = (string) ($block['innerHTML'] ?? ''); |
| 28 |
|
| 29 |
switch ($fieldKey) { |
| 30 |
case 'text': |
| 31 |
$text = is_string($value) ? $value : ''; |
| 32 |
$escaped = wp_kses_post($text); |
| 33 |
// Replace inner text while preserving the anchor's attributes. |
| 34 |
// Callback (not a replacement string) so user text containing |
| 35 |
// $1 / \1 / $0 is spliced literally, not parsed as a backref. |
| 36 |
$newInner = preg_replace_callback( |
| 37 |
'/(<a\b[^>]*>)(.*?)(<\/a>)/is', |
| 38 |
static function ($m) use ($escaped) { |
| 39 |
return $m[1] . $escaped . $m[3]; |
| 40 |
}, |
| 41 |
$existing, |
| 42 |
1 |
| 43 |
); |
| 44 |
$block['innerHTML'] = $newInner ?: $existing; |
| 45 |
$block['innerContent'] = [$block['innerHTML']]; |
| 46 |
return $block; |
| 47 |
|
| 48 |
case 'url': |
| 49 |
$url = is_string($value) ? esc_url_raw($value) : ''; |
| 50 |
$tp = new \WP_HTML_Tag_Processor($existing); |
| 51 |
if ($tp->next_tag('a')) { |
| 52 |
if ($url === '') { |
| 53 |
$tp->remove_attribute('href'); |
| 54 |
} else { |
| 55 |
$tp->set_attribute('href', $url); |
| 56 |
} |
| 57 |
$existing = $tp->get_updated_html(); |
| 58 |
} |
| 59 |
$block['innerHTML'] = $existing; |
| 60 |
$block['innerContent'] = [$existing]; |
| 61 |
// The canonical link target is the inner anchor's href, not a block attribute. |
| 62 |
return $block; |
| 63 |
} |
| 64 |
return $block; |
| 65 |
} |
| 66 |
} |
| 67 |
|