Grima  2018-08
Whispering into Alma's ear
grima-splats.php
Go to the documentation of this file.
1 <?php
7 namespace zemowsplat;
8 
12 class Splat {
13  private $paths;
14  private $bases;
15 /* the stack */
16  private $stack;
21  protected function push( array $scope ) {
22  $this->stack[] = array_merge( (array) $this->peek(), (array) $scope );
23  }
24 
29  protected function peek() {
30  $length = sizeof( $this->stack );
31  return $length ? $this->stack[ $length - 1 ] : array();
32  }
33 
38  protected function pop() {
39  return array_pop( $this->stack );
40  }
41 
45  public function __construct() {
46  $this->stack = [ [
47  'e' => 'htmlspecialchars',
48  't' => [ $this, 'splat' ],
49  ] ];
50  $this->paths = [];
51  $this->bases = [];
52  }
53 
87  public function splat( $name, $scope = array() ) {
88  $this->push( $scope );
89  $scope = $this->peek();
90  foreach( $this->nameToPaths( $name ) as $file ) {
91  $exe = new SplatExecutionContext( $file, $scope );
92  $exe->splat();
93  }
94  $this->pop();
95  }
96 
101  public function addPaths( array $paths ) {
102  foreach( $paths as $name => $path ) {
103  $this->paths[$name][] = $path;
104  }
105  }
106 
111  public function addBases( $bases ) {
112  foreach( (array) $bases as $base ) {
113  $this->bases[] = $base;
114  }
115  }
116 
125  protected function nameToPaths($name) {
126  $ret = array();
127  @$onlyOne = array_merge( (array) $this->paths[$name], [ "$name.php", ]);
128  foreach( $onlyOne as $file ) {
129  foreach( $this->bases as $base ) {
130  $path = $base . DIRECTORY_SEPARATOR . $file;
131  if( is_readable( $path ) ) {
132  $ret[] = $path;
133  break 2;
134  }
135  }
136  }
137  @$adds = array_merge( (array) $this->paths[$name.'[]'], [ "$name-add.php", ]);
138  foreach( $adds as $file ) {
139  foreach( $this->bases as $base ) {
140  $path = $base . DIRECTORY_SEPARATOR . $file;
141  if( is_readable( $path ) ) {
142  $ret[] = $path;
143  }
144  }
145  }
146  return $ret;
147  }
148 }
149 
157  protected $file;
158  protected $scope;
164  public function __construct( $file, array $scope ) {
165  $this->file = $file;
166  $this->scope = $scope;
167  }
168 
172  public function splat() {
173  extract($this->scope);
174  include $this->file;
175  }
176 }
push(array $scope)
push a scope onto the stack
addBases( $bases)
Add a base directory to resolve $relativePath to $absolutePath
splat()
extract the scope and include the file
pop()
pop a scope off the stack
__construct()
Setup default scopes and paths, but leave base dirs empty.
Helper class for Splat that runs the template PHP.
__construct( $file, array $scope)
Record the $file and $scope
Simple template engine.
nameToPaths($name)
Resolve a template $name to an array of absolute $paths.
addPaths(array $paths)
Add a resolution of $name to $relativePath
peek()
peek at current scope
splat( $name, $scope=array())
Main function: execute template $name with given $scope