-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwigMarkers.php
76 lines (66 loc) · 1.76 KB
/
twigMarkers.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* @author Mihail Bubnov <bubnov.mihail@gmail.com>
*/
namespace bubnovKelnik\TwigMarkers;
abstract class TwigMarkers extends \Twig_Extension
{
/**
* Text's context
* @var Entity
*/
protected $context;
/**
* {@inheritdoc}
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('markers', array($this, 'onMarkersFilter')),
);
}
/**
* Replace markers in string
*
* @param $string String with markers in format %marker_without_spaces%
* @param $context Context of the string
* @return String
*/
public function onMarkersFilter($string='', $context=null)
{
if(!preg_match_all('/%(\S+?)%/', $string, $markers) || $context === null)
{
return $string;
}
$this->context = $context;
$search = array();
$replace = array();
$markers[1] = array_unique($markers[1]);
$markers[0] = array_unique($markers[0]);
foreach($markers[1] as $m => $marker )
{
$methodFilter = 'onMarker'.ucfirst($marker);
if(!method_exists($this, $methodFilter) || !$replaceTo = $this->$methodFilter())
{
continue;
}
$search[] = $markers[0][$m];
$replace[] = $replaceTo;
}
return str_replace($search, $replace, $string);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'app_markers_filter';
}
/**
* Find requested context from provided
*
* @param $findContext Require Context (fully qualified class name)
* @return Entity | false
*/
abstract protected function findContext($findContext);
}