| 1 |
<?php |
| 2 |
|
| 3 |
namespace Hurrytimer\Placeholders; |
| 4 |
|
| 5 |
use Hurrytimer\Campaign; |
| 6 |
|
| 7 |
class Placeholder_Factory |
| 8 |
{ |
| 9 |
|
| 10 |
/** |
| 11 |
* Parse placeholders in the given string. |
| 12 |
* |
| 13 |
* @param string $string |
| 14 |
* @param Campaign $campaign |
| 15 |
* @return string |
| 16 |
*/ |
| 17 |
public static function parse( $string, $campaign ) |
| 18 |
{ |
| 19 |
$replacements = []; |
| 20 |
|
| 21 |
$placeholders = static::find_placeholder( $string ); |
| 22 |
|
| 23 |
foreach ( $placeholders as $variabele => $placeholder ) { |
| 24 |
|
| 25 |
$options = static::parse_placeholder( $placeholder ); |
| 26 |
|
| 27 |
$class = __NAMESPACE__ . '\\' . ucfirst( $options[ 0 ] ) . '_Placeholder'; |
| 28 |
|
| 29 |
if ( class_exists( $class ) ) { |
| 30 |
|
| 31 |
/** |
| 32 |
* @var Placeholder $placeholder_object |
| 33 |
*/ |
| 34 |
$placeholder_object = ( new $class( $campaign ) ); |
| 35 |
$replacements[$variabele] = $placeholder_object->get_value( $options[ 1 ] ); |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
return str_replace( array_keys( $replacements ), array_values( $replacements ), $string ); |
| 40 |
|
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Parse placeholder and options. |
| 45 |
* |
| 46 |
* @param $placeholder |
| 47 |
* @return array |
| 48 |
*/ |
| 49 |
private static function parse_placeholder( $placeholder ) |
| 50 |
{ |
| 51 |
$options = explode( '|', $placeholder ); |
| 52 |
$name = $options[ 0 ]; |
| 53 |
array_shift( $options ); |
| 54 |
return [ $name, $options ]; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* @param string $string |
| 59 |
* @return array |
| 60 |
*/ |
| 61 |
private static function find_placeholder( $string ) |
| 62 |
{ |
| 63 |
preg_match_all( '/\{{1,2}([a-z\|?]+)\}{1,2}/', $string, $matches ); |
| 64 |
return array_combine($matches[0], $matches[1]); |
| 65 |
} |
| 66 |
|
| 67 |
} |