35 Commits
Author SHA1 Message Date
mcndave 043fb90f8d - WIP on Picea's Asset. 2023-10-17 20:12:39 -04:00
mcndave d5de5e665b - WIP on picea-asset AND error handling 2023-10-12 19:07:16 +00:00
mcndave 3ccbf6bfab - WIP on picea-asset 2023-10-12 11:43:01 -04:00
mcndave 42d84796ee - Optional parameter of Opcache is now fixed 2023-08-31 09:15:05 -04:00
mcndave 386e0aa448 - Fixed error thrown on optional routes which arguments were not all fullfield 2023-06-09 15:31:53 -04:00
mcndave be65d45b41 Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-05-31 14:40:23 -04:00
mcndave 7d2bb8d407 - Quickfix on context name 2023-05-31 14:40:14 -04:00
mcndave 215bc26981 - UrlExtension now supports multiple application URL 2023-05-31 18:29:36 +00:00
Dave Mc Nicoll 3dce6a41cb - Added a batch() function to ease array iterations in templates 2023-05-01 14:36:47 -04:00
mcndave f9c955a82a - Fixed port redirection for URL behind proxy 2023-04-28 19:57:52 +00:00
Dave Mc Nicoll 2fe97c60ed - Fixed a bad merge 2023-04-28 19:56:05 +00:00
Dave Mc Nicoll 710ecad98d - Adjusted route name on exception 2023-04-28 19:52:19 +00:00
mcndave 3bcd5c9780 Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-04-20 18:16:29 +00:00
mcndave 7a2fa872fa - Added a no_html() method 2023-04-20 18:16:20 +00:00
mcndave 5182ba19bc - Fixed optional arguments in buildUrl() 2023-04-19 13:23:29 -04:00
mcndave 57367968ca Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-04-13 15:50:23 -04:00
mcndave b1e1324bfa - Fixed some PHP 8.x bugs (missing vars within compiler's context) and removed Picea's error handler - needs some work before putting online 2023-04-13 15:49:45 -04:00
mcndave 44b0283938 - Merged with new code-base 2023-03-30 14:46:52 -04:00
mcndave 1611ebe047 Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-03-30 18:29:35 +00:00
mcndave 6ee3e1bbae - Forced parameters in URL to be filled in UrlExtension buildUrl() and disabled the custom exception for now... 2023-03-30 18:29:17 +00:00
mcndave 169400cd61 Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-03-29 15:13:54 +00:00
mcndave b4964402fd - Renamed MoneyExtension to NumberExtension 2023-03-29 15:13:41 +00:00
mcndave a65aa72733 - Fixed bug Creation of dynamic property Picea\Compiler\BaseContext:: 2023-03-29 14:02:11 +00:00
mcndave b3a8e3aca2 - Token name and options are now passed through parse() method 2023-02-02 19:38:40 +00:00
mcndave e9b2f0ece3 - Fixed a bug added in previous commit 2023-02-02 18:12:31 +00:00
mcndave acd9f8c72e - First task of v2 done, tokens can now have unlimited options attached to it 2023-02-02 16:46:46 +00:00
mcndave afeb8789b5 - Added a new doc section about both new tokens 'section.prepend/append' 2023-02-01 18:20:42 +00:00
mcndave ded3d5e907 Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-02-01 18:09:01 +00:00
mcndave 9ea4856f49 - Added tokens 'section.append' and 'section.prepend' which equates longer form '{% section mysection, [ "action" => "prepend" ] %}' 2023-02-01 18:08:47 +00:00
mcndave 84020a871c Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-02-01 18:06:32 +00:00
mcndave 2dc16de7c3 - Simplified SLUG() method of the UrlExtension, since it was way too slow 2023-02-01 18:06:23 +00:00
mcndave af212b07ca Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-01-26 13:36:49 +00:00
mcndave 58766decaf - Fixed a bug within sections if it doesn't exist first 2023-01-26 13:36:38 +00:00
mcndave 08211282c2 - Added an event manager. Also, fixed some more bugs within Block and Section tokens 2023-01-26 13:32:52 +00:00
mcndave 58f73d914b - Some more documentation made / fixed 2022-12-22 14:35:26 +00:00
57 changed files with 672 additions and 223 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@
"authors": [ "authors": [
{ {
"name": "Dave Mc Nicoll", "name": "Dave Mc Nicoll",
"email": "mcndave@gmail.com" "email": "info@mcnd.ca"
} }
], ],
"autoload": { "autoload": {
+2 -2
View File
@@ -30,7 +30,7 @@ Using `print` or `echo`, which are, by default, made safer by using PHP's native
**[PHP]** Would yield internally: **[PHP]** Would yield internally:
```php ```html
<?php echo htmlspecialchars((string) "Hello World !", 3, 'UTF-8', true) ?> <?php echo htmlspecialchars((string) "Hello World !", 3, 'UTF-8', true) ?>
<?php echo htmlspecialchars((string) "This is another way to output &lt;safe&gt; content", 3, 'UTF-8', true) ?> <?php echo htmlspecialchars((string) "This is another way to output &lt;safe&gt; content", 3, 'UTF-8', true) ?>
@@ -63,7 +63,7 @@ Those tokens represents the equivalent of the printf() function from PHP.
**[PHP]** Would render internally as : **[PHP]** Would render internally as :
```php ```html
<?php <?php
$num = 5; $num = 5;
$location = 'tree'; $location = 'tree';
@@ -120,3 +120,51 @@ We could use the previous file `path/home` and generate, let's say, the same pag
``` ```
Notice that the `<header>` tag is now empty, since we've redeclared it in our navless view. Notice that the `<header>` tag is now empty, since we've redeclared it in our navless view.
## Overview of `section` (string $name, array $options)
In your `$name` variable, accepted characters are alpha-numeric and those specific caracters : `.-_:`, so
names suches as :
`body.content`
`my-cool-section:heading`
`MyOtherSection`
`_another_accepted_name`
Allowed options are :
string `action` : allowed are `prepend`, `default`, `append`
int `order` : if you must
### Actions can also be passed using specials tokens :
`section.prepend` and `section.append` can also be used without passing an `action` option.
*path/home-nav.phtml*
```html
{% extends "path/home" %}
{% section "header" %}
<a href="#mylink">First link here !</a>
{% endsection %}
```
*path/home-admin-nav.phtml*
```html
{% extends "path/home-nav" %}
{% section.prepend "header" %}
<h4>My new NAV header</h4>
{% endsection %}
{% section.append "header" %}
<a href="#mylink">Second link here !</a>
{% endsection %}
```
**[HTML]** Would render as such :
```html
<h4>My new NAV header</h4>
<a href="#mylink">First link here !</a>
<a href="#mylink">Second link here !</a>
```
View File
Whitespace-only changes.
+4
View File
@@ -0,0 +1,4 @@
# Extension - Creating an extension
+4
View File
@@ -0,0 +1,4 @@
# Extension - `json`, `json.pretty`, `json.html`
This extension
+7 -7
View File
@@ -7,10 +7,10 @@ It also insert `Tell` inside the LanguageHandler which handles the `{% _ 'relati
```php ```php
use function DI\autowire, DI\create, DI\get; use function DI\autowire, DI\create, DI\get;
use Zend\Diactoros\Response\HtmlResponse; use Laminas\Diactoros\Response\HtmlResponse;
use Picea\{ Picea, Caching\Cache, Caching\Opcache, Compiler, Compiler\Context, Compiler\BaseContext, FileFetcher, Language\DefaultRegistrations, Method\Request }; use Picea\{ Picea, Caching\Cache, Caching\Opcache, Compiler, Compiler\Context, Compiler\BaseContext, FileFetcher, Language\DefaultRegistrations, Method\Request };
use Picea\Extension\{ LanguageHandler, LanguageExtension, TitleExtension, MoneyExtension, UrlExtension }; use Picea\Extension\{ LanguageHandlerInterface, LanguageExtension, TitleExtension, NumberExtension, UrlExtension };
use Picea\Ui\{ Method, Ui }; use Picea\Ui\{ Method, Ui };
return [ return [
@@ -26,7 +26,7 @@ return [
return new Compiler(new class(array_merge([ return new Compiler(new class(array_merge([
$c->get(LanguageExtension::class), $c->get(LanguageExtension::class),
$c->get(TitleExtension::class), $c->get(TitleExtension::class),
$c->get(MoneyExtension::class), $c->get(NumberExtension::class),
$c->get(UrlExtension::class), $c->get(UrlExtension::class),
$c->get(Method\Form::class), $c->get(Method\Form::class),
$c->get(Method\Pagination::class), $c->get(Method\Pagination::class),
@@ -49,10 +49,10 @@ return [
Method\Pagination::class => autowire(Method\Pagination::class), Method\Pagination::class => autowire(Method\Pagination::class),
LanguageExtension::class => create(LanguageExtension::class)->constructor(get(LanguageHandler::class)), LanguageExtension::class => create(LanguageExtension::class)->constructor(get(LanguageHandlerInterface::class)),
LanguageHandler::class => function($c) { LanguageHandlerInterface::class => function($c) {
return new class( $c->get(Tell\I18n::class) ) implements LanguageHandler { return new class( $c->get(Tell\I18n::class) ) implements LanguageHandlerInterface {
public Tell\I18n $tell; public Tell\I18n $tell;
public function __construct(Tell\I18n $tell) { public function __construct(Tell\I18n $tell) {
@@ -68,7 +68,7 @@ return [
TitleExtension::class => autowire(TitleExtension::class), TitleExtension::class => autowire(TitleExtension::class),
MoneyExtension::class => autowire(MoneyExtension::class), NumberExtension::class => autowire(NumberExtension::class),
UrlExtension::class => create(UrlExtension::class)->constructor(get(Context::class), getenv("URL_BASE"), get('git.commit')), UrlExtension::class => create(UrlExtension::class)->constructor(get(Context::class), getenv("URL_BASE"), get('git.commit')),
+52 -4
View File
@@ -8,10 +8,13 @@ namespace %NAMESPACE%;
if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) { if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
class %CLASSNAME% %EXTENDS% { class %CLASSNAME% %EXTENDS% {
public array $blockList = []; public array $blockList = [];
public array $sectionList = []; public array $sectionList = [];
public array $sectionStack = [];
public array $variableList = []; public array $variableList = [];
public ?object $thisProxy = null; public ?object $thisProxy = null;
@@ -24,6 +27,8 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
public bool $renderingInsideSection = false; public bool $renderingInsideSection = false;
public int $depth = 0;
public function __construct(\Picea\Picea $picea, array $variablesList = [], ?object $thisProxy = null) { public function __construct(\Picea\Picea $picea, array $variablesList = [], ?object $thisProxy = null) {
$this->picea = $picea; $this->picea = $picea;
$this->variableList = $variablesList; $this->variableList = $variablesList;
@@ -37,14 +42,31 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
public function output(array $variablesList = []) : void public function output(array $variablesList = []) : void
{ {
$__event = new \Picea\Builder\ClassTemplateEvent();
$this->rendering = true; $this->rendering = true;
( function($___class__template, $___global_variables, $___variables, $picea) { $this->depth++;
$__event->eventExecute(\Picea\Event\Builder\ClassTemplateOutputing::class, $variablesList);
try {
( function($___class__template, $___global_variables, $___variables, $__event, $picea) {
extract($___global_variables); extract($___global_variables);
extract($___variables, \EXTR_OVERWRITE); extract($___variables, \EXTR_OVERWRITE);
?>%CONTENT%<?php ?>%CONTENT%<?php
} )->call($this->thisProxy ?? new class(){}, $this, $this->variableList, $variablesList, $this->picea); } )->call($this->thisProxy ?? new class() {}, $this, $this->variableList, $variablesList, $__event, $this->picea);
%PARENT_OUTPUT% } catch (\Throwable $error) {
throw $this->errorHandler($error);
}
$__event->eventExecute(\Picea\Event\Builder\ClassTemplateOutputDone::class, $variablesList);
try { %PARENT_OUTPUT% } catch (\Throwable $error) {
throw $this->errorHandler($error);
}
$this->depth--;
$this->rendering = false; $this->rendering = false;
} }
@@ -54,7 +76,7 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
$result = []; $result = [];
foreach([ 'prepend', 'default', 'append' ] as $item) { foreach([ 'prepend', 'default', 'append' ] as $item) {
if ( ! is_array($this->sectionList[$name][$item]) ) continue; if ( !isset($this->sectionList[$name][$item]) || ! is_array($this->sectionList[$name][$item]) ) continue;
usort($this->sectionList[$name][$item], fn($a, $b) => $a['order'] <=> $b['order']); usort($this->sectionList[$name][$item], fn($a, $b) => $a['order'] <=> $b['order']);
@@ -122,6 +144,32 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
$this->output($variablesList); $this->output($variablesList);
return ob_get_clean(); return ob_get_clean();
} }
public static function isTemplateError(\Throwable $error) : bool
{
$class = substr(static::class, strripos(static::class, '\\') + 1) . ".php";
return substr($error->getFile(), -strlen($class)) === $class;
}
protected function errorHandler(\Throwable $error) : \Throwable
{
$class = substr(static::class, strrpos(static::class, '\\') + 1) . ".php";
#dump( __NAMESPACE__, basename($error->getFile()), $class );
$basename = basename($error->getFile());
#dump(is_subclass_of(sprintf("\\%s\\%s", __NAMESPACE__, substr($basename,0 , strrpos($basename, '.'))), static::class, true));
if (str_ends_with($error->getFile(), $class)) {
$error = new \Picea\Exception\RenderHtmlException($this, $error->getMessage(), $error->getCode(), $error);
}
#elseif (is_subclass_of(sprintf("\\%s\\%s", __NAMESPACE__, substr($basename,0 , strrpos($basename, '.'))), static::class, true)) {
# $error = new \Picea\Exception\RenderHtmlException($this, $error->getMessage(), $error->getCode(), $error);
#}
return $error;
}
} }
} }
+8
View File
@@ -0,0 +1,8 @@
<?php declare(strict_types=1);
namespace Picea\Builder;
class ClassTemplateEvent
{
use \Picea\EventTrait;
}
+3 -3
View File
@@ -12,9 +12,9 @@ class Opcache implements Cache {
protected array $compiled = []; protected array $compiled = [];
protected ? Context $context; protected null|Context $context;
public function __construct(?string $cachePath = null, ? Context $context) public function __construct(?string $cachePath = null, null|Context $context = null)
{ {
$this->cachePath = $cachePath ?? sys_get_temp_dir(); $this->cachePath = $cachePath ?? sys_get_temp_dir();
$this->context = $context; $this->context = $context;
@@ -34,7 +34,7 @@ class Opcache implements Cache {
$compiledContext = $this->compiled[$viewPath]; $compiledContext = $this->compiled[$viewPath];
$fullName = isset($compiledContext['namespace']) ? "\\{$compiledContext['namespace']}\\{$compiledContext['classname']}" : $compiledContext['classname']; $fullName = isset($compiledContext['namespace']) ? "\\{$compiledContext['namespace']}\\{$compiledContext['classname']}" : ($compiledContext['classname'] ?? $viewPath);
return new $fullName(...$arguments); return new $fullName(...$arguments);
} }
+38 -13
View File
@@ -2,11 +2,17 @@
namespace Picea; namespace Picea;
use Picea\Event\Compiler\CompileTokenExtension;
use Picea\Event\Compiler\CompileTokenExtensionEvent;
use Picea\Event\Compiler\CompileTokenTagEvent;
use Picea\Exception\RegisterExtensionToken;
use Picea\Extension\FunctionExtension; use Picea\Extension\FunctionExtension;
use Picea\Language\LanguageRegistration; use Picea\Language\LanguageRegistration;
class Compiler class Compiler
{ {
use EventTrait;
protected string $sourceCode = ""; protected string $sourceCode = "";
protected array $syntaxObjectList = []; protected array $syntaxObjectList = [];
@@ -19,11 +25,10 @@ class Compiler
public array $extensionList = []; public array $extensionList = [];
public ? LanguageRegistration $languageRegistration; public function __construct(
public LanguageRegistration $languageRegistration
public function __construct(?LanguageRegistration $languageRegistration = null) )
{ {
$this->languageRegistration = $languageRegistration;
$this->languageRegistration->registerAll($this); $this->languageRegistration->registerAll($this);
} }
@@ -49,16 +54,21 @@ class Compiler
list($token, $arguments) = array_pad(array_filter(explode(' ', $matches[2], 2), 'strlen'), 2, null); list($token, $arguments) = array_pad(array_filter(explode(' ', $matches[2], 2), 'strlen'), 2, null);
$token = strtolower(trim($token)); $token = strtolower(trim($token));
$tokenName = $context->tokenName($token);
$tokenOptions = $context->tokenOptions($token);
# @TODO Refractor this parts to allows registration to the tag's name if ( $this->tagList[$tokenName] ?? false ) {
if ( $this->tagList[$token] ?? false ) { $this->eventExecute(CompileTokenTagEvent::class, $context, $arguments, $tokenName, $tokenOptions);
return $this->tagList[$token]->parse($context, $arguments, $token);
return $this->tagList[$tokenName]->parse($context, $arguments, $tokenName, $tokenOptions);
} }
elseif ( $this->extensionList[$token] ?? false ) { elseif ( $this->extensionList[$tokenName] ?? false ) {
return $this->extensionList[$token]->parse($context, $arguments, $token); $this->eventExecute(CompileTokenExtensionEvent::class, $context, $arguments, $tokenName, $tokenOptions);
return $this->extensionList[$tokenName]->parse($context, $arguments, $tokenName, $tokenOptions);
} }
else { else {
throw new \LogicException("Impossible to find token `$token` declared in `{$matches[2]}`. Perhapse you forgot to add a custom token to Picea's engine ?"); throw new \LogicException("Impossible to find token `$tokenName` declared in `{$matches[2]}`. Perhapse you forgot to add a custom token to Picea's engine ?");
} }
}, $this->sourceCode); }, $this->sourceCode);
@@ -87,6 +97,10 @@ class Compiler
public function registerControlStructure(ControlStructure\ControlStructure $controlStructureObject) : self public function registerControlStructure(ControlStructure\ControlStructure $controlStructureObject) : self
{ {
foreach($controlStructureObject->tokens ?? (array) ( $controlStructureObject->token ?? [] ) as $token) { foreach($controlStructureObject->tokens ?? (array) ( $controlStructureObject->token ?? [] ) as $token) {
if ( strpos($token, '.') !== false ) {
throw new RegisterExtensionToken(sprintf("Could not register token '%s' from control structure '%s' in this version. Options are now delt by extensions themselve instead.", $token, $controlStructureObject::class));
}
$this->tagList[strtolower($token)] = $controlStructureObject; $this->tagList[strtolower($token)] = $controlStructureObject;
} }
@@ -98,6 +112,10 @@ class Compiler
$tokens = $extension->tokens ?? (array) ( $extension->token ?? [] ); $tokens = $extension->tokens ?? (array) ( $extension->token ?? [] );
foreach($tokens as $token) { foreach($tokens as $token) {
if ( strpos($token, '.') !== false ) {
throw new RegisterExtensionToken(sprintf("Could not register token '%s' from extension '%s' in this version. Options are now delt by extensions themselve instead.", $token, $extension::class));
}
$this->extensionList[strtolower($token)] = $extension; $this->extensionList[strtolower($token)] = $extension;
} }
@@ -122,15 +140,22 @@ class Compiler
} }
public function __toString() : string
{
return "???";
}
public function getExtensionFromToken(string $name) : Extension\Extension public function getExtensionFromToken(string $name) : Extension\Extension
{ {
if ( false === $this->extensionList[$name] ?? false ) { $tokenName = explode('.', $name)[0];
if ( ! isset($this->extensionList[$tokenName]) ) {
throw new \InvalidArgumentException(<<<MSG throw new \InvalidArgumentException(<<<MSG
Requested extension from token `$name` could not be found from loaded Picea compiler's extension. Requested extension from token `$tokenName` could not be found from loaded Picea compiler's extension.
MSG); MSG);
} }
return $this->extensionList[$name]; return $this->extensionList[$tokenName];
} }
public function exportFunctions() : void public function exportFunctions() : void
+19 -1
View File
@@ -14,16 +14,22 @@ abstract class Context {
public string $compiledSource = ""; public string $compiledSource = "";
public ? string $sectionAction = null;
public string $viewPath = ""; public string $viewPath = "";
public string $filePath = ""; public string $filePath = "";
public string $classPath = "";
public array $switchStack = []; public array $switchStack = [];
public array $iterateStack = []; public array $iterationStack = [];
public array $useStack = []; public array $useStack = [];
public array $sections = [];
public int $functions = 0; public int $functions = 0;
public array $functionStack = []; public array $functionStack = [];
@@ -86,6 +92,18 @@ abstract class Context {
} }
public function tokenName(string $token) : string
{
return explode('.', $token)[0];
}
public function tokenOptions(string $token, bool $export = false) : array|string
{
$options = array_slice(explode('.', strtolower($token)), 1);
return $export ? var_export($options, true) : $options;
}
public function pushFunction($name, Callable $callable) : void public function pushFunction($name, Callable $callable) : void
{ {
$this->functionStack[$name] = $callable; $this->functionStack[$name] = $callable;
+2 -1
View File
@@ -4,7 +4,8 @@ namespace Picea\ControlStructure;
abstract class AbstractLoop implements ControlStructure { abstract class AbstractLoop implements ControlStructure {
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
switch($token) { switch($token) {
case "while": case "while":
case "foreach": case "foreach":
+6 -3
View File
@@ -6,7 +6,8 @@ class BlockToken implements ControlStructure {
public array $token = [ "arguments", "block", "endblock", "define", "slot", "endslot", "using" ]; public array $token = [ "arguments", "block", "endblock", "define", "slot", "endslot", "using" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
static $slotDefinitions = []; static $slotDefinitions = [];
switch($token) { switch($token) {
@@ -50,6 +51,8 @@ class BlockToken implements ControlStructure {
list($name, $definition) = array_pad(explode(',', $arguments, 2), 2, ""); list($name, $definition) = array_pad(explode(',', $arguments, 2), 2, "");
$loops = count($context->iterationStack ?? []) ? ",". implode(', ', array_filter(array_column($context->iterationStack, 'uid'), fn($e) => strpos($e, '[') === false)) : null;
if ($def->hasDefinitions() ) { if ($def->hasDefinitions() ) {
$slotName = eval("return $name;"); $slotName = eval("return $name;");
$def->currentSlot = $slotName; $def->currentSlot = $slotName;
@@ -62,7 +65,7 @@ class BlockToken implements ControlStructure {
} }
return <<<PHP return <<<PHP
<?php \$this->printSlot($name, function($definition array \$___using = []) use (\$picea) { extract(\$___using, \EXTR_SKIP); ?> <?php \$this->printSlot($name, function($definition array \$___using = []) use (\$picea $loops) { extract(\$___using, \EXTR_SKIP); ?>
PHP; PHP;
} }
else { else {
@@ -71,7 +74,7 @@ class BlockToken implements ControlStructure {
} }
return <<<PHP return <<<PHP
<?php (\$___block ?? \$this)->slotIsSet($name) || \$___block->setSlot($name, function($definition array \$___using = []) use (\$picea) { extract(\$___using, \EXTR_SKIP); ?> <?php (\$___block ?? \$this)->slotIsSet($name) || \$___block->setSlot($name, function($definition array \$___using = []) use (\$picea $loops) { extract(\$___using, \EXTR_SKIP); ?>
PHP; PHP;
} }
+2 -1
View File
@@ -6,7 +6,8 @@ class BreakToken implements ControlStructure {
public string $token = "break"; public string $token = "break";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
return "<?php break; ?>"; return "<?php break; ?>";
} }
+2 -1
View File
@@ -6,7 +6,8 @@ class CaseToken implements ControlStructure {
public string $token = "case"; public string $token = "case";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
$output = ""; $output = "";
if ( $context->switchStack ) { if ( $context->switchStack ) {
+1 -1
View File
@@ -6,7 +6,7 @@ class ContinueToken implements ControlStructure {
public string $token = "continue"; public string $token = "continue";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
return "<?php continue; ?>"; return "<?php continue; ?>";
} }
+1 -1
View File
@@ -6,7 +6,7 @@ class DefaultToken implements ControlStructure {
public string $token = "default"; public string $token = "default";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
$output = ""; $output = "";
if ( $context->switchStack ) { if ( $context->switchStack ) {
+1 -1
View File
@@ -6,7 +6,7 @@ class EchoToken implements ControlStructure {
public array $token = [ "echo", "echo.raw" ]; public array $token = [ "echo", "echo.raw" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) { switch($token) {
case "echo": case "echo":
return "<?php \\Picea\\ControlStructure\\EchoToken::echoSafe($arguments) ?>"; return "<?php \\Picea\\ControlStructure\\EchoToken::echoSafe($arguments) ?>";
+1 -1
View File
@@ -6,7 +6,7 @@ class ForToken implements ControlStructure {
public array $token = [ "for", "endfor" ]; public array $token = [ "for", "endfor" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) { switch($token) {
case "for": case "for":
$uid = "$".uniqid("for_"); $uid = "$".uniqid("for_");
+1 -1
View File
@@ -6,7 +6,7 @@ class FunctionToken implements ControlStructure {
public array $token = [ "function", "endfunction", "return" ]; public array $token = [ "function", "endfunction", "return" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) { switch($token) {
case "function": case "function":
$context->functions++; $context->functions++;
+1 -1
View File
@@ -6,7 +6,7 @@ class IfToken implements ControlStructure {
public array $token = [ "if", "else", "elseif", "endif" ]; public array $token = [ "if", "else", "elseif", "endif" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) { switch($token) {
case "if": case "if":
return "<?php if ($arguments): ?>"; return "<?php if ($arguments): ?>";
+1 -1
View File
@@ -6,7 +6,7 @@ class NamespaceToken implements ControlStructure {
public string $token = "namespace"; public string $token = "namespace";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
$context->namespace = $arguments; $context->namespace = $arguments;
return ""; return "";
} }
+1 -1
View File
@@ -6,7 +6,7 @@ class OrToken implements ControlStructure {
public string $token = "or"; public string $token = "or";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
if ( empty($context->iterationStack) ) { if ( empty($context->iterationStack) ) {
throw new \LogicException("Token `or` was used outside of iterator. Make sure your `for`, `foreach`, `while`, `do/until` declaration are properly made."); throw new \LogicException("Token `or` was used outside of iterator. Make sure your `for`, `foreach`, `while`, `do/until` declaration are properly made.");
} }
+33 -7
View File
@@ -2,11 +2,28 @@
namespace Picea\ControlStructure; namespace Picea\ControlStructure;
enum PrintActionEnum : string {
case prepend = "prepend";
case default = "default";
case append = "append";
# case both = "both";
}
class SectionToken implements ControlStructure { class SectionToken implements ControlStructure {
public array $token = [ "section", "endsection" ]; public array $token = [ "section", "endsection" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { protected PrintActionEnum $action = PrintActionEnum::default;
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
if (in_array('prepend', $options)) {
$this->action = PrintActionEnum::prepend;
}
elseif (in_array('append', $options)) {
$this->action = PrintActionEnum::append;
}
switch($token) { switch($token) {
case "section": case "section":
return $this->printSection($context, $arguments); return $this->printSection($context, $arguments);
@@ -28,7 +45,7 @@ class SectionToken implements ControlStructure {
$options = eval("return $options;"); $options = eval("return $options;");
} }
if ( ! ctype_alnum(str_replace([".", "\"", "'", "-", "_"], "", $name)) ) { if ( ! ctype_alnum(str_replace([".", "\"", "'", "-", "_", ":"], "", $name)) ) {
throw new \RuntimeException("Your section named `{$name}` contains invalid character. Allowed are only letters, numbers, dashes, underscores and dots"); throw new \RuntimeException("Your section named `{$name}` contains invalid character. Allowed are only letters, numbers, dashes, underscores and dots");
} }
@@ -37,7 +54,7 @@ class SectionToken implements ControlStructure {
'options' => $options, 'options' => $options,
]; ];
$action = $options['action'] ?? "default"; $action = $options['action'] ?? $this->action->value;
if (! in_array($action, ['prepend', 'append', 'default'])) { if (! in_array($action, ['prepend', 'append', 'default'])) {
throw new \RuntimeException("An unsupported action `$action` was given as an option of a {% section %} tag"); throw new \RuntimeException("An unsupported action `$action` was given as an option of a {% section %} tag");
@@ -46,14 +63,23 @@ class SectionToken implements ControlStructure {
$order = $options['order'] ?? "count(\$___class__template->sectionList[$name]['$action'])"; $order = $options['order'] ?? "count(\$___class__template->sectionList[$name]['$action'])";
return "<?php \$___class__template->sectionList[$name] ??= [ 'prepend' => [], 'append' => [], 'default' => [] ];" . return "<?php \$___class__template->sectionList[$name] ??= [ 'prepend' => [], 'append' => [], 'default' => [] ];" .
"\$___class__template->sectionList[$name]['$action'][] = [ 'order' => $order, 'callback' => function() use (\$picea, \$___class__template, \$___global_variables, \$___variables) {". "\$___class__template->sectionList[$name]['$action'][] = [ ".
"extract(\$___global_variables); extract(\$___variables, \EXTR_OVERWRITE); \$___class__template->sectionStack[] = '$name'; ?>"; "'order' => $order, " .
"'callback' => function() use (\$picea, \$___class__template, \$___global_variables, \$___variables, \$__event) {" .
"extract(\$___global_variables); extract(\$___variables, \EXTR_OVERWRITE);" .
"\$___class__template->sectionStack[] = $name;" .
"\$__event->eventExecute(\Picea\Event\Builder\ClassTemplateRenderSection::class, $name);?>";
} }
protected function printEndSection($context) : string protected function printEndSection($context) : string
{ {
$section = array_pop($context->sections); $section = array_pop($context->sections);
$build = $context->extendFrom ? "!empty(\$___class__template->sectionStack) && \$___class__template->renderSection({$section['name']});" : "\$___class__template->renderSection({$section['name']});"; $build = $context->extendFrom ? "!empty(\$___class__template->sectionStack) && \$___class__template->renderSection({$section['name']}, false);" : "\$___class__template->renderSection({$section['name']}, false);";
return "<?php array_pop(\$___class__template->sectionStack); }]; $build?>";
return "<?php \$__event->eventExecute(\Picea\Event\Builder\ClassTemplateRenderSectionDone::class, {$section['name']});" .
"array_pop(\$___class__template->sectionStack); }];" .
$build .
"?>";
} }
} }
+1 -1
View File
@@ -6,7 +6,7 @@ class SwitchToken implements ControlStructure {
public array $token = [ "switch", "case", "endswitch" ]; public array $token = [ "switch", "case", "endswitch" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) { switch($token) {
case "switch": case "switch":
$context->switchStack[] = true; $context->switchStack[] = true;
+1 -1
View File
@@ -6,7 +6,7 @@ class UseToken implements ControlStructure {
public string $token = "use"; public string $token = "use";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
$context->useStack[] = $arguments; $context->useStack[] = $arguments;
return ""; return "";
} }
+1 -1
View File
@@ -6,7 +6,7 @@ class ViewToken implements ControlStructure {
public string $token = "view"; public string $token = "view";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
# The way this is ordered, if you provide a second arguments, being an array of variables, get_defined_vars() will not be pushed inside the view # The way this is ordered, if you provide a second arguments, being an array of variables, get_defined_vars() will not be pushed inside the view
return "<?php echo \$___class__template->picea->inlineHtml(\$this, $arguments, get_defined_vars()); ?>"; return "<?php echo \$___class__template->picea->inlineHtml(\$this, $arguments, get_defined_vars()); ?>";
} }
+1 -1
View File
@@ -5,7 +5,7 @@ namespace Picea\ControlStructure;
class WhileToken extends AbstractLoop { class WhileToken extends AbstractLoop {
public array $token = [ "do", "while", "endwhile", ]; public array $token = [ "do", "while", "endwhile", ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) { switch($token) {
case "do": case "do":
$context->iterationStack[] = [ $context->iterationStack[] = [
@@ -0,0 +1,7 @@
<?php
namespace Picea\Event\Builder;
interface ClassTemplateOutputDone {
public function execute(string $name, array $variablesList) : mixed;
}
@@ -0,0 +1,7 @@
<?php
namespace Picea\Event\Builder;
interface ClassTemplateOutputing {
public function execute(string $name, array $variablesList) : mixed;
}
@@ -0,0 +1,7 @@
<?php
namespace Picea\Event\Builder;
interface ClassTemplateRenderSection {
public function execute(string $name) : mixed;
}
@@ -0,0 +1,7 @@
<?php
namespace Picea\Event\Builder;
interface ClassTemplateRenderSectionDone {
public function execute(string $section) : mixed;
}
@@ -0,0 +1,10 @@
<?php
namespace Picea\Event\Compiler;
use Picea\Compiler\Context;
interface CompileTokenExtensionEvent
{
public function execute(Context $context, ?string $arguments, string $token, array $options = []);
}
@@ -0,0 +1,10 @@
<?php
namespace Picea\Event\Compiler;
use Picea\Compiler\Context;
interface CompileTokenTagEvent
{
public function execute(Context &$context, ?string $arguments, string $token, array $options = []);
}
@@ -0,0 +1,8 @@
<?php
namespace Picea\Event\Extension;
interface UrlBuildAssetEvent
{
public function execute(string $uri, array $parameters = [], bool $appendVersion) : void;
}
@@ -0,0 +1,8 @@
<?php
namespace Picea\Event\Extension;
interface UrlBuildRouteEvent
{
public function execute(string $uri, array $parameters = [], bool $appendVersion) : void;
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Picea\Event\Extension;
interface UrlBuildUrlEvent
{
public function execute(string $uri, array $parameters = [], bool $appendVersion) : void;
}
@@ -0,0 +1,8 @@
<?php
namespace Picea\Event\Extension;
interface UrlRegisterRouteEvent
{
public function execute(string $name, array $route) : void;
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace Picea;
trait EventTrait
{
protected $eventTraitMethod = "execute";
public array $eventTraitList = [];
protected array $eventTraitReturnList = [];
public function eventRegister(object $event) : void
{
$this->eventTraitList[] = $event;
}
public function eventFromType(string $type) : array
{
return array_filter($this->eventTraitList, fn($ev) => $ev instanceof $type);
}
public function eventExecute(string $type, ...$arguments) : void
{
foreach($this->eventFromType($type) as $event) {
$this->eventTraitReturnList[$event::class][] = call_user_func_array([ $event, $this->eventTraitMethod ], $arguments);
}
}
}
@@ -0,0 +1,7 @@
<?php
namespace Picea\Exception;
use Picea\Picea;
class ParseExtensionException extends \Exception {}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace Picea\Exception;
use Picea\Picea;
class RegisterExtensionToken extends \Exception {}
+6 -19
View File
@@ -10,33 +10,20 @@ use Picea\Picea;
*/ */
class RenderHtmlException extends \Exception class RenderHtmlException extends \Exception
{ {
protected Picea $picea;
public function __construct(object $compiledObject, Picea $picea, string $message, int $code, \Throwable $previous) public function __construct(object $template, string $message, int $code, \Throwable $previous)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
$this->picea = $picea; $this->defineError($previous, $template);
$this->defineError($previous, $compiledObject);
} }
protected function defineError(\Throwable $previous, object $compiledObject) : void protected function defineError(\Throwable $previous, object $template) : void
{ {
$loadedTemplates = array_flip($this->picea->loadedTemplateFile); /*$loadedTemplates = array_flip($this->picea->loadedTemplateFile);*/
foreach($previous->getTrace() as $trace) { $this->file = $template::getParam('view');
if ( isset($trace['file'], $loadedTemplates[$trace['file']]) ) { $this->line = $template::getSourceLineFromException($previous->getLine());
$class = $loadedTemplates[ $trace['file'] ];
$content = include($trace['file']);
$this->file = $content['view'];
$this->line = $class::getSourceLineFromException($trace['line']);
return;
}
}
} }
protected function getTemplateFile(string $filePath) : ? array protected function getTemplateFile(string $filePath) : ? array
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Picea\Extension;
use Picea\Compiler\Context;
class BatchExtension implements Extension, FunctionExtension {
public string $token = "batch";
public function exportFunctions(): array
{
return [
"batch" => [ $this, 'batch' ]
];
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
return "<?php echo batch($arguments) ?>";
}
public function batch(iterable $array, int $size, mixed $default = null) : \Generator
{
$split = ceil( count($array) / $size );
for($i = 0; $i < $split; $i++) {
$slice = array_slice(is_array($array) ? $array : iterator_to_array($array, true), $i * $size, $size, true);
$pad = ( count($slice) !== $size ) && ( $default !== null );
yield $pad ? array_pad($slice, $size, $default) : $slice;
}
}
}
+1 -1
View File
@@ -3,5 +3,5 @@
namespace Picea\Extension; namespace Picea\Extension;
interface Extension { interface Extension {
public function parse(\Picea\Compiler\Context &$context, string $sourceCode, string $token); public function parse(\Picea\Compiler\Context &$context, string $sourceCode, string $token, array $options = []) : string;
} }
+7 -8
View File
@@ -6,21 +6,20 @@ use Picea\Compiler\Context;
class JsonExtension implements Extension, FunctionExtension { class JsonExtension implements Extension, FunctionExtension {
public array $token = [ "json", "json.pretty", "json.html" ]; public array $token = [ "json" ];
public int $flags = JSON_HEX_TAG | \JSON_HEX_QUOT | \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_UNICODE; public int $flags = JSON_HEX_TAG | \JSON_HEX_QUOT | \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_UNICODE;
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{ {
$flag = $this->flags; $flag = $this->flags;
switch ($token) { if ( in_array('pretty', $options) ) {
case "json.pretty":
$flag |= \JSON_PRETTY_PRINT; $flag |= \JSON_PRETTY_PRINT;
break; }
case "json.html": if ( in_array('html', $options) ) {
return "<?php echo htmlentities(json_encode($arguments, {$this->flags}), ENT_QUOTES, 'UTF-8') ?>"; return "<?php echo htmlentities(json_encode($arguments, $flag), ENT_QUOTES, 'UTF-8') ?>";
} }
$cls = static::class; $cls = static::class;
@@ -32,7 +31,7 @@ class JsonExtension implements Extension, FunctionExtension {
{ {
return [ return [
'json' => function($arguments, ? int $flags = null) { 'json' => function($arguments, ? int $flags = null) {
return json_encode($arguments, \JSON_FORCE_OBJECT); return json_encode($arguments, $flags ?? $this->flags);
}, },
]; ];
} }
+48 -13
View File
@@ -3,16 +3,17 @@
namespace Picea\Extension; namespace Picea\Extension;
use Picea\Compiler\Context; use Picea\Compiler\Context;
use Picea\Event\Builder\ClassTemplateRenderSectionDone;
class LanguageExtension implements Extension, FunctionExtension { class LanguageExtension implements Extension, FunctionExtension {
public array $tokens = [ "lang", "lang.raw", "_", "_.raw", "language.set" ]; public array $tokens = [ "lang", "_", "language" ];
public string $currentLanguage = ""; public string $currentLanguage = "";
protected LanguageHandler $languageHandler; protected LanguageHandlerInterface $languageHandler;
public function __construct(LanguageHandler $handler) { public function __construct(LanguageHandlerInterface $handler) {
$this->languageHandler = $handler; $this->languageHandler = $handler;
} }
@@ -24,25 +25,42 @@ class LanguageExtension implements Extension, FunctionExtension {
]; ];
} }
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) : string public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{ {
switch($token) { switch(explode('.', $token)[0]) {
case "language.set": case "language":
return "<?php \$picea->compiler->getExtensionFromToken('$token')->currentLanguage = $arguments; ?>"; $cls = $this::class;
return <<<PHP
<?php
(function(\\$cls \$ext) use (\$___class__template, \$__event) {
#\$extends = \$___class__template->getParam('extends');
if ( \$___class__template->depth === 1 || \$___class__template->sectionStack ) {
\$ext->currentLanguage = $arguments;
# @TODO Make sure this event is only registered when we output() a template, if we are in a section, we must attach it a view/section/block output event instead !
\$__event->eventRegister(\\$cls::outputDoneEvent(\$ext));
}
})(\$picea->compiler->getExtensionFromToken('$token'));
?>
PHP;
case "lang": case "lang":
if ( in_array('raw', $options) ) {
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->absoluteLang($arguments) ?>";
}
return "<?php echo htmlspecialchars(\$picea->compiler->getExtensionFromToken('$token')->absoluteLang($arguments), \ENT_QUOTES, ini_get('default_charset'), true) ?>"; return "<?php echo htmlspecialchars(\$picea->compiler->getExtensionFromToken('$token')->absoluteLang($arguments), \ENT_QUOTES, ini_get('default_charset'), true) ?>";
case "lang.raw":
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->absoluteLang($arguments) ?>";
case "_": case "_":
return "<?php echo htmlspecialchars(\$picea->compiler->getExtensionFromToken('$token')->relativeLang($arguments), \ENT_QUOTES, ini_get('default_charset'), true) ?>"; if ( in_array('raw', $options) ) {
case "_.raw":
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->relativeLang($arguments) ?>"; return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->relativeLang($arguments) ?>";
} }
return "<?php echo htmlspecialchars(\$picea->compiler->getExtensionFromToken('$token')->relativeLang($arguments), \ENT_QUOTES, ini_get('default_charset'), true) ?>";
}
return ""; return "";
} }
@@ -59,4 +77,21 @@ class LanguageExtension implements Extension, FunctionExtension {
{ {
return $this->languageHandler->languageFromKey($key, $variables); return $this->languageHandler->languageFromKey($key, $variables);
} }
public static function outputDoneEvent(LanguageExtension $languageExtension) : ClassTemplateRenderSectionDone
{
return new class($languageExtension) implements ClassTemplateRenderSectionDone {
protected string $current;
public function __construct(protected LanguageExtension $languageExtension) {
$this->current = $this->languageExtension->currentLanguage;
}
public function execute(string $name) : mixed
{
return $this->current ? $this->languageExtension->currentLanguage = $this->current : null;
}
};
}
} }
@@ -2,7 +2,7 @@
namespace Picea\Extension; namespace Picea\Extension;
interface LanguageHandler interface LanguageHandlerInterface
{ {
public function languageFromKey(string $key, array $variables = []); #: array|string; public function languageFromKey(string $key, array $variables = []); #: array|string;
} }
-41
View File
@@ -1,41 +0,0 @@
<?php
namespace Picea\Extension;
use Picea\Compiler\Context;
class MoneyExtension implements Extension {
public string $token = "money";
public string $title = "";
public string $locale;
public \NumberFormatter $formatter;
public function __construct(Context $context) {
$this->register($context);
$this->locale = explode('.', \Locale::getDefault())[0];
$this->formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY);
}
public function register(Context $context) : void
{
$context->pushFunction("money", [ $this, 'money' ]);
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) {
return "<?php echo money($arguments) ?>";
}
public function money(float $money, ? string $currency = null) /* : string|false */
{
$this->formatter->setTextAttribute(\NumberFormatter::CURRENCY_CODE, 'CAD');
$this->formatter->setPattern( str_replace('¤#','¤ #', $this->formatter->getPattern() ) );
return $this->formatter->formatCurrency($money, $currency ?? $this->formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE));
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace Picea\Extension;
use Picea\Compiler\Context;
class NumberExtension implements Extension, FunctionExtension {
public string $locale;
public \NumberFormatter $formatter;
public function __construct(
public string|array $token = [ "money", "format", "format_zero" ],
public string $title = "",
) {
$this->locale = explode('.', \Locale::getDefault())[0];
}
public function exportFunctions(): array
{
return [
"money" => [ $this, 'money' ],
"format" => [ $this, 'format' ],
"format_zero" => [ $this, 'formatZero' ],
];
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
switch($token) {
case "format":
return "<?php echo format($arguments) ?>";
case "format_zero":
return "<?php echo format_zero($arguments) ?>";
case "money":
return "<?php echo money($arguments) ?>";
}
return "";
}
public function format(int|float $num, int $decimals = 0, null|string $decimalSeparator = ".", null|string $thousandsSeparator = ",") : string
{
return number_format($num, $decimals, $decimalSeparator, $thousandsSeparator);
}
public function formatZero(int $num, int $length) : string
{
return sprintf("%0{$length}d", $num);
}
public function money(float $money, ? string $currency = null) /* : string|false */
{
$this->formatter ??= new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY);
$this->formatter->setTextAttribute(\NumberFormatter::CURRENCY_CODE, 'CAD');
$this->formatter->setPattern( str_replace('¤#','¤ #', $this->formatter->getPattern() ) );
return $this->formatter->formatCurrency($money, $currency ?? $this->formatter->getTextAttribute(\NumberFormatter::CURRENCY_CODE));
}
}
+2 -1
View File
@@ -6,7 +6,8 @@ class PhpExtension implements Extension {
public array $token = [ "php" ]; public array $token = [ "php" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
return "<?php $arguments ?>"; return "<?php $arguments ?>";
} }
} }
+14 -9
View File
@@ -6,7 +6,7 @@ use Picea\Compiler\Context;
class PrintExtension implements Extension { class PrintExtension implements Extension {
public array $token = [ "echo", "echo.raw", "print", "print.raw", "printf", "printf.raw" ]; public array $token = [ "echo", "print", "printf", "no_html" ];
public int $flag = \ENT_QUOTES; public int $flag = \ENT_QUOTES;
@@ -18,23 +18,28 @@ class PrintExtension implements Extension {
$this->encoding = ini_get("default_charset"); $this->encoding = ini_get("default_charset");
} }
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) : string public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{ {
switch($token) { switch($token) {
case 'echo': case 'echo':
case 'print': case 'print':
if (in_array('raw', $options)) {
return "<?php echo $arguments ?>";
}
return "<?php echo htmlspecialchars((string) $arguments, {$this->flag}, '{$this->encoding}', " . ($this->doubleEncode ? "true" : "false") . ") ?>"; return "<?php echo htmlspecialchars((string) $arguments, {$this->flag}, '{$this->encoding}', " . ($this->doubleEncode ? "true" : "false") . ") ?>";
case 'echo.raw':
case "print.raw":
return "<?php echo $arguments ?>";
case 'printf': case 'printf':
return "<?php echo htmlspecialchars(sprintf((string) $arguments), {$this->flag}, '{$this->encoding}', " . ($this->doubleEncode ? "true" : "false") . ") ?>"; if (in_array('raw', $options)) {
case 'printf.raw':
return "<?php printf((string) $arguments) ?>"; return "<?php printf((string) $arguments) ?>";
} }
return "<?php echo htmlspecialchars(sprintf((string) $arguments), {$this->flag}, '{$this->encoding}', " . ($this->doubleEncode ? "true" : "false") . ") ?>";
case 'no_html':
return "<?php echo nl2br(strip_tags((string) $arguments)) ?>";
}
} }
} }
+11 -11
View File
@@ -2,25 +2,25 @@
namespace Picea\Extension; namespace Picea\Extension;
use Picea\Compiler\Context; class TitleExtension implements Extension, FunctionExtension {
class TitleExtension implements Extension {
public string $token = "title"; public string $token = "title";
public string $title = ""; public string $title = "";
public function __construct(Context $context) { public function exportFunctions(): array
$this->register($context);
}
public function register(Context $context) : void
{ {
$context->pushFunction("title", [ $this, 'handleTitle' ]); return [
"title" => [$this, 'handleTitle'],
];
} }
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) { public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
return "<?php echo title($arguments) ?>"; {
return "<?php ".
"if ( null !== \$title = title($arguments) ) {".
"echo \$title;".
"} ?>";
} }
public function handleTitle(? string $set = null, ...$arguments) : ? string public function handleTitle(? string $set = null, ...$arguments) : ? string
+90 -33
View File
@@ -2,9 +2,16 @@
namespace Picea\Extension; namespace Picea\Extension;
use Notes\Route\Attribute\Object\Route;
use Picea\EventTrait;
use Picea\Compiler\Context; use Picea\Compiler\Context;
class UrlExtension implements Extension { use Picea\Event\Extension\{ UrlBuildAssetEvent, UrlBuildUrlEvent, UrlBuildRouteEvent, UrlRegisterRouteEvent };
class UrlExtension implements Extension, FunctionExtension {
use \Picea\EventTrait;
use EventTrait;
public const URLIZE_PATTERN_URL = <<<PATTERN public const URLIZE_PATTERN_URL = <<<PATTERN
~(?<!href=['"])https?://[\w/._\-&?]*(?!</a>)(?=[^\w/._\-&])~s ~(?<!href=['"])https?://[\w/._\-&?]*(?!</a>)(?=[^\w/._\-&])~s
@@ -16,21 +23,29 @@ PATTERN;
protected string $urlBase; protected string $urlBase;
protected array $appUrl;
protected string $assetToken; protected string $assetToken;
protected array $routes; protected array $routes;
protected array $routesTarget; protected array $routesTarget;
public array $tokens = [ "url" , "route", "route.cacheless", "asset", "url.current", "url.parameters", "slug" ]; protected bool $forceSSL = false;
public function __construct(Context $context, string $urlBase = "", string $assetToken = "") { public array $tokens = [ "url" , "route", "asset", "slug" ];
#[\Deprecated]
protected bool $enforceExistingArguments = true;
public function __construct(string $urlBase = "", string $assetToken = "", array $appUrl = [], bool $forceSSL = false) {
$this->urlBase = trim($urlBase, "/"); $this->urlBase = trim($urlBase, "/");
$this->assetToken = $assetToken; $this->assetToken = $assetToken;
$this->register($context); $this->appUrl = $appUrl;
$this->forceSSL = $forceSSL;
} }
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) : ?string public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{ {
switch($token) { switch($token) {
case "asset": case "asset":
@@ -40,29 +55,32 @@ PATTERN;
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->buildRouteUrl($arguments) ?>"; return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->buildRouteUrl($arguments) ?>";
case "url": case "url":
if ( in_array('parameters', $options) ) {
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->setUrlParameters($arguments) ?>";
}
elseif ( in_array('current', $options) ) {
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->currentUrl($arguments) ?>";
}
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->buildUrl($arguments) ?>"; return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->buildUrl($arguments) ?>";
case "url.current":
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->currentUrl($arguments) ?>";
case "url.parameters":
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->setUrlParameters($arguments) ?>";
case "slug": case "slug":
return \Transliterator::createFromRules(':: Any-Latin;:: NFD;:: [:Nonspacing Mark:] Remove;:: NFC;:: [:Punctuation:] Remove;:: Lower();[:Separator:] > \'-\'')->transliterate( $arguments ); return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->slug($arguments) ?>";
} }
return null; throw new \ParseExtensionException("Unknown token given $token in UrlExtension.");
} }
public function register(Context $context) : void public function exportFunctions(): array
{ {
$context->pushFunction("url", [ $this, 'buildUrl' ]); return [
$context->pushFunction("current_url", [ $this, 'currentUrl' ]); "url" => [ $this, 'buildUrl' ],
$context->pushFunction("asset", [ $this, 'buildAssetUrl' ]); "current_url" => [ $this, 'currentUrl' ],
$context->pushFunction("route", [ $this, 'buildRouteUrl' ]); "asset" => [ $this, 'buildAssetUrl' ],
$context->pushFunction("slug", [ $this, 'slug' ]); "route" => [ $this, 'buildRouteUrl' ],
$context->pushFunction("urlize", [ $this, 'urlize' ]); "slug" => [ $this, 'slug' ],
"urlize" => [ $this, 'urlize' ]
];
} }
public function getRouteList(bool $full = false) : array public function getRouteList(bool $full = false) : array
@@ -93,18 +111,22 @@ PATTERN;
public function buildUrl(string $uri = "", array $parameters = [], bool $appendVersion = false) : string public function buildUrl(string $uri = "", array $parameters = [], bool $appendVersion = false) : string
{ {
$this->eventExecute(UrlBuildUrlEvent::class, $uri, $parameters, $appendVersion);
return $this->setUrlParameters($this->url() . "/" . ltrim($uri, "/"), $appendVersion ? array_replace([ 'v' => $this->assetToken ], $parameters) : $parameters); return $this->setUrlParameters($this->url() . "/" . ltrim($uri, "/"), $appendVersion ? array_replace([ 'v' => $this->assetToken ], $parameters) : $parameters);
} }
public function buildAssetUrl(string $uri, array $parameters = [], bool $appendVersion = true) : string public function buildAssetUrl(string $uri, array $parameters = [], bool $appendVersion = true) : string
{ {
$this->eventExecute(UrlBuildAssetEvent::class, $uri, $parameters, $appendVersion);
return $this->buildUrl($uri, $parameters, $appendVersion); return $this->buildUrl($uri, $parameters, $appendVersion);
} }
public function buildRouteUrl(string $name, array $parameters = [], bool $appendVersion = false) : string public function buildRouteUrl(string $name, array $parameters = [], bool $appendVersion = false) : string
{ {
if ( false !== ( $route = $this->routes[$name] ?? false ) ) { if ( false !== ( $route = $this->routes[$name] ?? false ) ) {
return $this->buildUrl($this->prepareRoute($route['route'], $parameters), $parameters, $appendVersion); return $this->buildUrl($this->prepareRoute($route, $parameters), $parameters, $appendVersion);
} }
$routeList = json_encode($this->routes, \JSON_PRETTY_PRINT); $routeList = json_encode($this->routes, \JSON_PRETTY_PRINT);
@@ -120,9 +142,14 @@ PATTERN;
return $this->scheme() . $this->domain() . $this->base(); return $this->scheme() . $this->domain() . $this->base();
} }
# src: https://stackoverflow.com/a/14550919
public static function slug(string $text, string $separator = '-') : string public static function slug(string $text, string $separator = '-') : string
{ {
return trim(str_replace('-', $separator, \Transliterator::createFromRules(':: Any-Latin;:: NFD;:: [:Nonspacing Mark:] Remove;:: NFC;:: [:Punctuation:] Remove;:: Lower();[:Separator:] > \'-\'')->transliterate(str_replace('-', ' ', $text))), '-'); $clean = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text);
$clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
return preg_replace("/[\/_| -]+/", $separator, strtolower(trim($clean, '-')));
} }
public function registerRoute(string $name, string $route, string $class, string $method, array $routeMethods) : void public function registerRoute(string $name, string $route, string $class, string $method, array $routeMethods) : void
@@ -133,6 +160,8 @@ PATTERN;
'class' => $class, 'class' => $class,
'classMethod' => $method, 'classMethod' => $method,
]; ];
$this->eventExecute(UrlRegisterRouteEvent::class, $name, $this->routes[$name]);
} }
/** /**
@@ -159,7 +188,7 @@ PATTERN;
protected function scheme() : string protected function scheme() : string
{ {
return ( $this->isHttps() ? "https" : "http" ) . "://"; return ( $this->forceSSL || $this->isHttps() ? "https" : "http" ) . "://";
} }
protected function base() : string protected function base() : string
@@ -178,7 +207,25 @@ PATTERN;
protected function domain() : string protected function domain() : string
{ {
return strtolower($_SERVER['HTTP_HOST']); if ( ! empty($_SERVER['HTTP_X_FORWARDED_PROTO']) || ! empty($_SERVER['HTTP_X_FORWARDED_SSL']) ) {
$port = "";
}
else {
$port = $this->isDefaultPort() ? "" : ":" . $_SERVER['SERVER_PORT'];
}
return strtolower($this->appUrl($port) ?: $_SERVER['HTTP_HOST']);
}
protected function appUrl(string $port) : string
{
$domain = strtolower($_SERVER['HTTP_HOST']);
if (in_array($domain, $this->appUrl)) {
return $domain . $port;
}
return $this->appUrl[0] . $port;
} }
protected function isDefaultPort() : bool protected function isDefaultPort() : bool
@@ -203,32 +250,42 @@ PATTERN;
|| ( "off" !== ( strtolower($_SERVER['HTTPS'] ?? $_SERVER['HTTP_X_FORWARDED_SSL'] ?? $_SERVER['X-Forwarded-Ssl'] ?? "off")) ); || ( "off" !== ( strtolower($_SERVER['HTTPS'] ?? $_SERVER['HTTP_X_FORWARDED_SSL'] ?? $_SERVER['X-Forwarded-Ssl'] ?? "off")) );
} }
protected function prepareRoute(string $route, array &$arguments) protected function prepareRoute(array $routeParam, array &$arguments)
{ {
$route = $routeParam['route'];
if ( preg_match_all('~{(.*?)}~si', $route, $matches, PREG_SET_ORDER) ) { if ( preg_match_all('~{(.*?)}~si', $route, $matches, PREG_SET_ORDER) ) {
$search = []; $search = [];
foreach($matches as $item) { foreach($matches as $item) {
if (strpos($item[1], "=") !== false) { $default = null;
$variable = $item[1];
# Handles default
if (strpos($variable, "=") !== false) {
list($variable, $default) = explode('=', $item[1]); list($variable, $default) = explode('=', $item[1]);
} }
elseif (strpos($item[1], ":") !== false) {
# Handles type
if (strpos($variable, ":") !== false) {
list($variable, ) = explode(':', $item[1]); list($variable, ) = explode(':', $item[1]);
} }
else {
$variable = $item[1];
}
if ( array_key_exists($variable, $arguments) ) { if ( array_key_exists($variable, $arguments) ) {
$value = $arguments[ $variable ]; $value = $arguments[ $variable ];
unset($arguments[ $variable ]); unset($arguments[ $variable ]);
} }
else { else {
$value = $default ?? ""; if ($default ?? false) {
$value = $default;
}
elseif ( strpos($route, "[{$matches[0][0]}]") !== false && $this->enforceExistingArguments) {
throw new \RuntimeException(sprintf("Error while preparing route %s : could not match variable '%s' into given arguments ( %s ) from %s::%s", $route, $variable, json_encode($arguments), $routeParam['class'], $routeParam['classMethod']));
}
} }
$search[ $item[0] ] = $value; $search[$item[0]] = $value ?? "";
} }
$route = str_replace(array_keys($search), array_values($search), $route); $route = str_replace(array_keys($search), array_values($search), $route);
+6 -12
View File
@@ -6,18 +6,11 @@ use Picea\Compiler;
class DefaultRegistrations implements LanguageRegistration class DefaultRegistrations implements LanguageRegistration
{ {
protected array $extensions; public function __construct(
protected array $extensions,
protected array $syntaxes; protected array $syntaxes,
protected array $controlStructures,
protected array $controlStructures; ) { }
public function __construct(array $extensions = [], array $syntaxes = [], array $controlStructure = [])
{
$this->extensions = $extensions;
$this->syntaxes = $syntaxes;
$this->controlStructures = $controlStructure;
}
public function registerAll(Compiler $compiler) : void public function registerAll(Compiler $compiler) : void
{ {
@@ -67,6 +60,7 @@ class DefaultRegistrations implements LanguageRegistration
$compiler->registerExtension(new \Picea\Extension\PhpExtension()); $compiler->registerExtension(new \Picea\Extension\PhpExtension());
$compiler->registerExtension(new \Picea\Extension\PrintExtension()); $compiler->registerExtension(new \Picea\Extension\PrintExtension());
$compiler->registerExtension(new \Picea\Extension\JsonExtension()); $compiler->registerExtension(new \Picea\Extension\JsonExtension());
$compiler->registerExtension(new \Picea\Extension\BatchExtension());
foreach($this->extensions ?? [] as $extension) { foreach($this->extensions ?? [] as $extension) {
$compiler->registerExtension($extension); $compiler->registerExtension($extension);
+11 -9
View File
@@ -7,10 +7,11 @@ use Picea\Extension\Extension,
use Picea\Compiler\Context; use Picea\Compiler\Context;
use Picea\Extension\FunctionExtension;
use Psr\Http\Message\RequestInterface; use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
class Request implements Extension { class Request implements Extension, FunctionExtension {
use ExtensionTrait; use ExtensionTrait;
public array $tokens; public array $tokens;
@@ -21,18 +22,19 @@ class Request implements Extension {
public function __construct(ServerRequestInterface $request, Context $context) { public function __construct(ServerRequestInterface $request, Context $context) {
$this->request = $request; $this->request = $request;
$this->register($context);
} }
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) : string { } public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string { }
public function register(Context $context) : void public function exportFunctions(): array
{ {
$context->pushFunction("cookie", [ $this, 'cookie' ]); return [
$context->pushFunction("get", [ $this, 'get' ]); "cookie" => [ $this, 'cookie' ],
$context->pushFunction("post", [ $this, 'post' ]); "get" => [ $this, 'get' ],
$context->pushFunction("request", [ $this, 'request' ]); "post" => [ $this, 'post' ],
$context->pushFunction("server", [ $this, 'server' ]); "request" => [ $this, 'request' ],
"server" => [ $this, 'server' ],
];
} }
public function cookie(? string $variableName = null, $default = null) public function cookie(? string $variableName = null, $default = null)
+9 -9
View File
@@ -43,7 +43,7 @@ class Picea implements LanguageRegistration
){ ){
$this->cache = $cache ?? new Caching\Memory(""); $this->cache = $cache ?? new Caching\Memory("");
$this->context = $context ?? new Compiler\BaseContext(); $this->context = $context ?? new Compiler\BaseContext();
$this->languageRegistration = $languageRegistration ?? new Language\DefaultRegistrations(); $this->languageRegistration = $languageRegistration ?? new Language\DefaultRegistrations([], [], []);
$this->builderTemplatePath = $builderTemplatePath ?? dirname(__FILE__) . static::DEFAULT_BUILDER_TEMPLATE; $this->builderTemplatePath = $builderTemplatePath ?? dirname(__FILE__) . static::DEFAULT_BUILDER_TEMPLATE;
$this->compiler = $compiler ?? $this->instanciateCompiler(); $this->compiler = $compiler ?? $this->instanciateCompiler();
$this->fileFetcher = $fileFetcher ?? $this->instanciateFileFetcher(); $this->fileFetcher = $fileFetcher ?? $this->instanciateFileFetcher();
@@ -54,7 +54,7 @@ class Picea implements LanguageRegistration
$this->renderContext($this->context); $this->renderContext($this->context);
} }
public function gatherTemplateObject(string $viewPath, array $variables = [], ? object $proxy = null) : ? object public function gatherCompiledObject(string $viewPath, array $variables = [], ? object $proxy = null) : ? object
{ {
if ( null === $object = $this->fetchFromCache($viewPath, $this->globalVariables + $variables, $proxy) ) { if ( null === $object = $this->fetchFromCache($viewPath, $this->globalVariables + $variables, $proxy) ) {
throw new \RuntimeException("An error occured while trying to save a compiled template."); throw new \RuntimeException("An error occured while trying to save a compiled template.");
@@ -65,21 +65,21 @@ class Picea implements LanguageRegistration
public function renderHtml(string $viewPath, array $variables = [], ?object $proxy = null) : ? string public function renderHtml(string $viewPath, array $variables = [], ?object $proxy = null) : ? string
{ {
$object = $this->gatherTemplateObject($viewPath, $variables, $proxy); $object = $this->gatherCompiledObject($viewPath, $variables, $proxy);
try { try {
return call_user_func($object); return call_user_func($object);
} }
catch(\Throwable $ex) { catch(\Throwable $ex) {
if (! $ex instanceof Exception\RenderHtmlException ) { #if (! $ex instanceof Exception\RenderHtmlException ) {
throw new Exception\RenderHtmlException($object, $this, "An error occurred trying to render HTML view `$viewPath` : " . $ex->getMessage(), 911, $ex); # throw new Exception\RenderHtmlException($object, $this, "An error occurred trying to render HTML view `$viewPath` : " . $ex->getMessage(), 911, $ex);
} #}
else { #else {
throw $ex; throw $ex;
} #}
} }
exit(); return null;
} }
/** /**