| 1 |
<?php |
| 2 |
namespace ABlocks\Frontend\DynamicContent; |
| 3 |
|
| 4 |
if ( ! defined( 'ABSPATH' ) ) { |
| 5 |
exit; |
| 6 |
} |
| 7 |
class Interpreter { |
| 8 |
|
| 9 |
protected array $interpreters = [ |
| 10 |
'post-type' => Interpreters\PostType::class, |
| 11 |
'current' => Interpreters\CurrentPost::class, |
| 12 |
'current-date-time' => Interpreters\CurrentDateTime::class, |
| 13 |
'site-title' => Interpreters\SiteTitle::class, |
| 14 |
'site-tagline' => Interpreters\SiteTagline::class, |
| 15 |
'user-info' => Interpreters\UserInfo::class, |
| 16 |
'request-parameter' => Interpreters\RequestParams::class, |
| 17 |
'shortcode' => Interpreters\Shortcode::class, |
| 18 |
'link' => Interpreters\Link::class, |
| 19 |
'image' => Interpreters\Image::class, |
| 20 |
]; |
| 21 |
protected string $content; |
| 22 |
protected array $context; |
| 23 |
public function __construct( string $content, $context = [] ) { |
| 24 |
$this->content = $content; |
| 25 |
$this->context = $context; |
| 26 |
$this->parse();// exit; |
| 27 |
} |
| 28 |
public function parse() : void { |
| 29 |
$this->content = preg_replace_callback( |
| 30 |
'~ablocks_dc:(.+?):ablocks_dc|<span\s+(?=[^>]*\bclass=["\']ablocks-richtext-dynamic-content["\'])(?=[^>]*\bdata-source=["\']([^"\']+)["\'])(?=[^>]*\bdata-field=["\']([^"\']+)["\'])[^>]*>(.*?)<\/span>~ims', |
| 31 |
[ $this, 'apply_changes' ], |
| 32 |
$this->content |
| 33 |
); |
| 34 |
} |
| 35 |
public function apply_changes( array $matches ): string { |
| 36 |
$filtered = $this->filter( $matches ); // returns an array |
| 37 |
$args = array_merge( $filtered, [ $this->interpreters, $this->context ] ); |
| 38 |
$parser = new ArgumentParser( ...$args ); |
| 39 |
$ins = $parser->interpret(); |
| 40 |
return is_null( $ins ) ? '' : $ins->content(); |
| 41 |
} |
| 42 |
|
| 43 |
public function filter( array $matches ) : array { |
| 44 |
$is_richtext = false; |
| 45 |
array_shift( $matches ); |
| 46 |
if ( count( $matches ) > 2 ) { |
| 47 |
array_shift( $matches ); |
| 48 |
$is_richtext = true; |
| 49 |
} |
| 50 |
return [ |
| 51 |
implode( '|', $matches ), |
| 52 |
$is_richtext |
| 53 |
]; |
| 54 |
} |
| 55 |
|
| 56 |
public static function init( string $content, $block, $instance ) : string { |
| 57 |
// This filter runs for EVERY block on the page (including core and |
| 58 |
// third-party blocks). The regex in parse() is expensive, so skip it |
| 59 |
// unless the block actually contains a dynamic-content marker. |
| 60 |
if ( false === strpos( $content, 'ablocks_dc' ) |
| 61 |
&& false === strpos( $content, 'ablocks-richtext-dynamic-content' ) ) { |
| 62 |
return $content; |
| 63 |
} |
| 64 |
$ins = new self( $content, $instance->context ); |
| 65 |
return $ins->content; |
| 66 |
} |
| 67 |
} |
| 68 |
|