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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
| <?php
namespace rawsrc\PhpEcho;
use ArrayAccess;
if ( ! defined('HELPER_BOUND_TO_CLASS_INSTANCE')) {
define('HELPER_BOUND_TO_CLASS_INSTANCE', 1);
}
if ( ! defined('HELPER_RETURN_ESCAPED_DATA')) {
define('HELPER_RETURN_ESCAPED_DATA', 2);
}
/**
* PhpEcho : PHP Template engine : One class to rule them all ;-)
*
* @link https://www.developpez.net/forums/blogs/32058-rawsrc/b9154/phpecho-version-2-0-0/
* @author rawsrc - https://www.developpez.net/forums/u32058/rawsrc/
* @copyright MIT License
*
* Copyright (c) 2020 rawsrc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* @method mixed raw($p) Return the raw value from a PhpEcho block
* @method mixed hsc($p) Escape the value in parameter (scalar, array, stringifyable)
* @method bool isScalar($p)
* @method string selected($p, $ref) Return " selected " if $p == $ref
* @method string checked($p, $ref) Return " checked " if $p == $ref
*/
class PhpEcho
implements ArrayAccess
{
/**
* @var string
*/
private $id = '';
/**
* @var array
*/
private $vars = [];
/**
* Full resolved filepath to the external view file
* @var string
*/
private $file = '';
/**
* @var string
*/
private $code = '';
/**
* @var array [helper's id => bound closure]
*/
private $bound_helpers = [];
/**
* @param mixed $file see setFile() below
* @param array $vars
* @param string $id if empty then auto-generated
*/
public function __construct($file = '', array $vars = [], string $id = '')
{
if ($file !== '') {
$this->setFile($file);
}
if ($id === '') {
$this->generateId();
} else {
$this->id = $id;
}
$this->vars = $vars;
self::addPathToHelperFile(__DIR__.DIRECTORY_SEPARATOR.'stdHelpers.php');
}
/**
* @param string $id
*/
public function setId(string $id)
{
$this->id = $id;
}
/**
* @return string
*/
public function id(): string
{
return $this->id;
}
/**
* Generate an unique execution id based on random_bytes()
* Always start with a letter
*/
public function generateId()
{
$this->id = chr(mt_rand(97, 122)).bin2hex(random_bytes(4));
}
/**
* Interface ArrayAccess
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return array_key_exists($offset, $this->vars);
}
/**
* Interface ArrayAccess
*
* Return escaped value for
* - scalars
* - array (escape keys and values)
* - stringifyable instance (class implementing __toString() method)
*
* If object: return the object
*
* @param mixed $offset
* @return mixed|null
*/
public function offsetGet($offset)
{
if (isset($this->vars[$offset])) {
$v = $this->vars[$offset];
if (is_array($v) || $this('$is_scalar', $v)) {
return $this('$hsc', $v);
} elseif (is_object($v)) {
return $v;
}
}
return null;
}
/**
* Interface ArrayAccess
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
$this->vars[$offset] = $value;
}
/**
* Interface ArrayAccess
* @param mixed $offset
*/
public function offsetUnset($offset)
{
unset($this->vars[$offset]);
}
/**
* Define the filepath to the external view file to include
*
* Rule R001 : Any space inside a name will be automatically converted to DIRECTORY_SEPARATOR
*
* For strings : $parts = 'www user view login.php';
* - become "www/user/view/login.php" if DIRECTORY_SEPARATOR = '/'
* - become "www\user\view\login.php" if DIRECTORY_SEPARATOR = '\'
*
* For arrays, same rule (R001) for all values inside : $parts = ['www/user', 'view login.php'];
* - become "www/user/view/login.php" if DIRECTORY_SEPARATOR = '/'
* - become "www/user\view\login.php" if DIRECTORY_SEPARATOR = '\'
*
* File inclusion remove the inline code
*
* @param mixed $parts string|array
*/
public function setFile($parts)
{
$file = [];
$parts = is_string($parts) ? explode(' ', $parts) : $parts;
foreach ($parts as $p) {
$file[] = str_replace(' ', DIRECTORY_SEPARATOR, $p);
}
$this->file = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, implode(DIRECTORY_SEPARATOR, $file));
$this->code = '';
}
/**
* Instead on including an external file, use inline code for the view
*
* CAREFUL : when you use inline code with dynamic values from the array $vars, you must
* be absolutely sure that the values are already defined before, otherwise you will only have empty strings
*
* Inline code remove the included file
*
* @param string $code
*/
public function setCode(string $code)
{
$this->code = $code;
$this->file = '';
}
/**
* This function call a helper defined elsewhere or dynamically
* Auto-escape if necessary
*
* @param string $helper
* @param array $args
* @return mixed
*/
public function __invoke(string $helper, ...$args)
{
if ($helper !== '') {
if (self::isHelper($helper)) {
if (empty($this->bound_helpers)) {
$this->bound_helpers = self::bindHelpersTo($this);
}
$escaped = self::isHelperOfType($helper, HELPER_RETURN_ESCAPED_DATA);
$helpers = $this->bound_helpers + self::$helpers;
$helper = $helpers[$helper];
$result = $helper(...$args);
// being in a HTML context: in any case, the returned data should be escaped
// if you don't want so, use the specific helper '$raw'
if ($escaped) {
return $result;
} else {
return $this('$hsc', $result);
}
}
}
return null;
}
/**
* @param $name
* @param $arguments
*/
public function __call($name, $arguments)
{
if (self::isHelper($name)) {
return $this->__invoke($name, ...$arguments);
} elseif (self::isHelper('$'.$name)) {
return $this->__invoke('$'.$name, ...$arguments);
} else {
return null;
}
}
/**
* Magic method that returns a string instead of current instance of the class in a string context
*/
public function __toString()
{
if (($this->file !== '') && is_file($this->file)) {
ob_start();
include $this->file;
return ob_get_clean();
} else {
return $this->code;
}
}
//region HELPER ZONE
/**
* @var array [name => closure]
*/
private static $helpers = [];
/**
* @var array [path to the helpers file to include]
*/
private static $helpers_file_path = [];
/**
* @var array [helper's name => [type]]
*/
private static $helpers_types = [];
/**
* @var array [helpers filepath to inject]
*/
private static $helpers_file_to_inject = [];
/**
* @param string $name
* @param \Closure $closure
* @param int ...$types HELPER_RETURN_ESCAPED_DATA HELPER_BOUND_TO_CLASS_INSTANCE
*/
public static function addHelper(string $name, \Closure $closure, int ...$types)
{
self::$helpers[$name] = $closure;
foreach ($types as $t) {
self::$helpers_types[$name][] = $t; // HELPER_BOUND_TO_CLASS_INSTANCE HELPER_RETURN_ESCAPED_DATA
}
}
/**
* @param array $helpers [name => Closure | name => [Closure, ...type]]
*/
public static function addHelpers(array $helpers)
{
foreach ($helpers as $name => $h) {
if ($h instanceof \Closure) {
self::$helpers[$name] = $h;
} elseif (is_array($h)) {
self::addHelper($name, array_shift($h), ...$h);
}
}
}
/**
* @return array [name => closure]
*/
public static function helpers(): array
{
return self::$helpers;
}
/**
* Path to the file that contains helpers closure definition
* The helpers are common to all instances and will be included only once
*
* @param string ...$path
*/
public static function addPathToHelperFile(string ...$path)
{
foreach ($path as $p) {
if ( ! isset(self::$helpers_file_path[$p])) {
self::$helpers_file_path[$p] = true;
self::$helpers_file_to_inject[] = $p;
}
}
}
/**
* Read the paths and inject only once all the helpers
*/
public static function injectHelpers()
{
foreach (self::$helpers_file_to_inject as $path) {
if (is_file($path)) {
self::addHelpers(include $path);
}
}
self::$helpers_file_to_inject = [];
}
/**
* @param string $helper_name
* @return array [int]
*/
public static function getHelperTypes(string $helper_name): array
{
return self::$helpers_types[$helper_name] ?? [];
}
/**
* @param string $helper_name
* @return bool
*/
public static function isHelper(string $helper_name): bool
{
if (isset(self::$helpers[$helper_name])) {
return true;
} else {
self::injectHelpers();
return isset(self::$helpers[$helper_name]);
}
}
/**
* Check if the helper has the defined type
*
* @param string $helper_name
* @param int $type
* @return bool
*/
public static function isHelperOfType(string $helper_name, int $type): bool
{
return isset(self::$helpers_types[$helper_name])
? in_array($type, self::$helpers_types[$helper_name])
: false;
}
/**
* @param array $type array of types [type]
* @param bool $strict when match, check if the helper has only the asked types
* @return array [helper's name => closure]
*/
public static function getHelpersByType(array $type, bool $strict = false): array
{
$data = [];
foreach (self::$helpers_types as $name => $v) {
$intersect = array_intersect($type, $v);
if (( ! empty($intersect)) && (count($type) === count($intersect))) {
if ($strict) {
if (count($type) === count($v)) {
$data[$name] = self::$helpers[$name];
}
} else {
$data[$name] = self::$helpers[$name];
}
}
}
return $data;
}
/**
* Change the helper's binding context to the given one in parameter
* Only for helpers bound to a class instance
*
* @param object $p
* @return array [helper's id => bound closure]
*/
public static function bindHelpersTo(object $p): array
{
$helpers = [];
foreach (self::getHelpersByType([HELPER_BOUND_TO_CLASS_INSTANCE], false) as $name => $hlp) {
$helpers[$name] = $hlp->bindTo($p, $p);
}
return $helpers;
}
//endregion
}
// make the class directly available on the global namespace
class_alias('rawsrc\PhpEcho\PhpEcho', 'PhpEcho', false); |