63 Commits
Author SHA1 Message Date
mcndave 562950447e - Removed utf8_encode method which was removed in PHP 8.5 2026-07-14 15:16:51 +00:00
mcndave 54f209f8e2 - Upgrading to latest PHP version (8.5) 2026-07-08 12:12:57 +00:00
mcndave 28210836cd - WIP on DiExtension 2026-07-07 12:23:19 +00:00
mcndave 1f771b1932 - Added a new DiExtension and proceed to some code cleaning 2026-07-06 16:35:06 +00:00
mcndave 778f84116b - Modernized code a bit and added variables to blocks 2026-07-01 12:57:01 -04:00
Dev 722131d801 - Object type now show in invalid block arguments 2026-06-09 19:26:27 +00:00
mcndave 210c8ae0bd - Added support fort named parameters in block calls 2026-01-09 16:03:53 -05:00
Dave Mc Nicoll c975de0557 - variable of block can't be overwritten 2025-11-11 18:23:45 +00:00
Dave Mc Nicoll 0c0ba39072 - Fixed last rebase 2025-10-15 14:59:31 +00:00
Dave Mc Nicoll ef95576d74 - Added a loop index in AbstractLoop control struct. 2025-10-15 14:57:42 +00:00
Dave Mc Nicoll e737e82d7e - Fixed a deprecated attribute not supported on properties.
@
2025-01-25 00:28:54 +00:00
mcndave 830a643a56 - Fixed route generating (removed methods) 2024-11-21 19:15:04 -05:00
Dave Mc Nicoll b24bbbc150 - Fixed a bug where optional routes were badly parsed 2024-11-01 16:44:52 -04:00
Dave Mc Nicoll 3ffb69342b - Fixed a bug within FunctionToken control structure where multiple definition were runned if a view was loaded more than once 2024-11-01 16:11:31 -04:00
mcndave fa815a506e - Added a Try/Catch token to the language (and DefaultRegistration also registers it automatically 2024-10-29 13:40:17 +00:00
Dave Mc Nicoll 35a7bd4cf7 - Block can now reference a 'this' object from it's {% using [ 'this' => new stdClass() ] %} token
- Fixed a bug with {% use %} which was buggy whenever two uses were declared and one of them had a curly braces notation in it.
2024-10-21 18:09:33 +00:00
Dave Mc Nicoll 7970679894 - Fixed a bug checking for incomplete data given to build an URL within the UrlExt. 2024-10-18 13:08:29 +00:00
mcndave d22d26c9c8 - Fixed a bug that appeared deeper when rendering a block inside the slot of another block 2024-10-17 18:14:11 +00:00
Dave Mc Nicoll 934643214e - Fixed a part of Block's doc ; more work to be done on that part
- Fixed whitespaces from unprinted block parts
- Reworked a bit the UrlExtension route grabbing part
2024-10-16 20:30:27 +00:00
mcndave 5e54407f74 - WIP on urlextension 2023-12-07 15:46:25 +00:00
Dave Mc Nicoll b856743741 - Merged some code added a long time ago to the extension 2023-12-01 20:27:26 +00:00
mcndave 10fb17c7c3 - Removed Ui def 2023-11-15 23:26:27 -05:00
mcndave 8b6dd85fd5 - Added PPH-DI definition file 2023-11-15 22:12:25 -05:00
mcndave 8c7a4d730b - quickfix 2023-11-08 06:54:30 -05:00
mcndave ed0eb8225b Merge branch 'master' of https://git.mcnd.ca/mcndave/picea 2023-11-03 19:52:51 -04:00
mcndave 0e655fd387 - Added a default action for print 2023-11-03 19:52:15 -04:00
mcndave ce43abb954 - Added some flags for PrintExtension outputting 2023-11-01 09:57:43 -04:00
mcndave 5aa70dfd17 - Fixed missing formatter loading 2023-10-31 14:30:56 +00:00
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
67 changed files with 1045 additions and 318 deletions

No files matched your search

+11 -2
View File
@@ -6,7 +6,7 @@
"authors": [
{
"name": "Dave Mc Nicoll",
"email": "mcndave@gmail.com"
"email": "info@mcnd.ca"
}
],
"autoload": {
@@ -15,6 +15,15 @@
}
},
"require": {
"psr/http-message": "^1.0"
"psr/http-message": "^2.0"
},
"extra": {
"lean": {
"autoload": {
"definitions": [
"meta/definitions.php"
]
}
}
}
}
+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
```html
<?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) ?>
@@ -63,7 +63,7 @@ Those tokens represents the equivalent of the printf() function from PHP.
**[PHP]** Would render internally as :
```php
```html
<?php
$num = 5;
$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.
## 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>
```
@@ -96,9 +96,9 @@ You can do so by using `define` and `slot`.
```html
{% arguments string $name, string $anchor, int $index = 0 %}
{% define slot %}
{% define "attributes" %}
<a {% slot "attributes" %}href="{{ $anchor }}" tabindex="{{ $index }}"{% endslot %}>{{ $name }}"</a>
<a {% slot "attributes" %}{% endslot %} href="{{ $anchor }}" tabindex="{{ $index }}"{% endslot %}>{{ $name }}"</a>
```
**[HTML]** Would render the same as the `view` example :
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
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\Extension\{ LanguageHandler, LanguageExtension, TitleExtension, MoneyExtension, UrlExtension };
use Picea\Extension\{ LanguageHandlerInterface, LanguageExtension, TitleExtension, NumberExtension, UrlExtension };
use Picea\Ui\{ Method, Ui };
return [
@@ -26,7 +26,7 @@ return [
return new Compiler(new class(array_merge([
$c->get(LanguageExtension::class),
$c->get(TitleExtension::class),
$c->get(MoneyExtension::class),
$c->get(NumberExtension::class),
$c->get(UrlExtension::class),
$c->get(Method\Form::class),
$c->get(Method\Pagination::class),
@@ -49,10 +49,10 @@ return [
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) {
return new class( $c->get(Tell\I18n::class) ) implements LanguageHandler {
LanguageHandlerInterface::class => function($c) {
return new class( $c->get(Tell\I18n::class) ) implements LanguageHandlerInterface {
public Tell\I18n $tell;
public function __construct(Tell\I18n $tell) {
@@ -68,7 +68,7 @@ return [
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')),
+65
View File
@@ -0,0 +1,65 @@
<?php
use function DI\autowire, DI\create, DI\get;
use Picea\{
Caching\Cache,
Caching\Opcache,
Compiler,
Compiler\Context,
Compiler\BaseContext,
FileFetcher,
Method\Request
};
use Picea\Extension\{ LanguageHandlerInterface, LanguageExtension, TitleExtension, NumberExtension, UrlExtension, DiExtension };
return [
Picea\Picea::class => function($c) {
return new Picea\Picea($c->get(Context::class), $c->get(Cache::class), $c->get(Compiler::class), null, $c->get(FileFetcher::class), null, getenv("DEBUG"));
},
Context::class => function($c) {
return new BaseContext(
defaultNamespace: $c->get(Lean\Lean::class)->getPiceaContext(),
declare: getenv('PICEA_DECLARE') ?? 'declare(strict_types=1)'
);
},
Compiler::class => autowire(Compiler::class),
Request::class => autowire(Request::class),
LanguageExtension::class => create(LanguageExtension::class)->constructor(get(LanguageHandlerInterface::class)),
# LanguageHandlerInterface::class => autowire(\Lean\LanguageHandler::class),
# LanguageRegistration::class => create(\Lean\PiceaDefaultRegistration::class)->constructor(get('picea.extensions'), [], [], get(Ui::class), null),
'picea.extensions' => function(\Psr\Container\ContainerInterface $c) {
return array_merge([
$c->get(LanguageExtension::class),
$c->get(TitleExtension::class),
$c->get(NumberExtension::class),
$c->get(DiExtension::class),
$c->get(UrlExtension::class),
$c->get(Request::class),
], class_exists(\Taxus\Picea\Extension::class) ? [ $c->get(\Taxus\Picea\Extension::class) ] : [],
array_map(fn($class) => $c->get($class), $c->get(Lean\Lean::class)->getPiceaExtensions())
);
},
TitleExtension::class => autowire(TitleExtension::class),
NumberExtension::class => autowire(NumberExtension::class),
DiExtension::class => autowire(DiExtension::class),
UrlExtension::class => create(UrlExtension::class)->constructor(getenv("URL_BASE"), get('git.commit'), explode(',', getenv('APP_URL')), (bool) getenv('FORCE_SSL')),
Cache::class => create(Opcache::class)->constructor(getenv("CACHE_PATH"), get(Context::class)),
FileFetcher::class => function($c) {
return new FileFetcher($c->get(Lean\Lean::class)->getViewPaths());
},
];
+2 -1
View File
@@ -21,7 +21,8 @@ class Builder
$replace = [
'%NAMESPACE%' => $context->namespace,
'%USE%' => ( $uses = $context->renderUses() ) ? "use $uses;" : false,
'%USE%' => ( $uses = $context->renderUses() ) ? $uses : false,
'%DECLARE%' => $context->declare ? rtrim($context->declare, ';') . ';' : "",
'%CLASSNAME%' => $context->className,
'%PATHNAME%' => $path($context->viewPath),
'%FULLPATH%' => $path($context->filePath),
+53 -5
View File
@@ -1,4 +1,4 @@
<?php
<?php %DECLARE%
namespace %NAMESPACE%;
@@ -8,10 +8,13 @@ namespace %NAMESPACE%;
if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
class %CLASSNAME% %EXTENDS% {
public array $blockList = [];
public array $sectionList = [];
public array $sectionStack = [];
public array $variableList = [];
public ?object $thisProxy = null;
@@ -24,6 +27,8 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
public bool $renderingInsideSection = false;
public int $depth = 0;
public function __construct(\Picea\Picea $picea, array $variablesList = [], ?object $thisProxy = null) {
$this->picea = $picea;
$this->variableList = $variablesList;
@@ -37,14 +42,31 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
public function output(array $variablesList = []) : void
{
$__event = new \Picea\Builder\ClassTemplateEvent();
$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($___variables, \EXTR_OVERWRITE);
?>%CONTENT%<?php
} )->call($this->thisProxy ?? new class(){}, $this, $this->variableList, $variablesList, $this->picea);
%PARENT_OUTPUT%
} )->call($this->thisProxy ?? new class() {}, $this, $this->variableList, $variablesList, $__event, $this->picea);
} 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;
}
@@ -54,7 +76,7 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
$result = [];
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']);
@@ -122,6 +144,32 @@ if (! class_exists("%NAMESPACE%\%CLASSNAME%", false) ) {
$this->output($variablesList);
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 ? 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->context = $context;
@@ -34,7 +34,7 @@ class Opcache implements Cache {
$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);
}
+38 -13
View File
@@ -2,11 +2,17 @@
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\Language\LanguageRegistration;
class Compiler
{
use EventTrait;
protected string $sourceCode = "";
protected array $syntaxObjectList = [];
@@ -19,11 +25,10 @@ class Compiler
public array $extensionList = [];
public ? LanguageRegistration $languageRegistration;
public function __construct(?LanguageRegistration $languageRegistration = null)
public function __construct(
public LanguageRegistration $languageRegistration
)
{
$this->languageRegistration = $languageRegistration;
$this->languageRegistration->registerAll($this);
}
@@ -49,16 +54,21 @@ class Compiler
list($token, $arguments) = array_pad(array_filter(explode(' ', $matches[2], 2), 'strlen'), 2, null);
$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[$token] ?? false ) {
return $this->tagList[$token]->parse($context, $arguments, $token);
if ( $this->tagList[$tokenName] ?? false ) {
$this->eventExecute(CompileTokenTagEvent::class, $context, $arguments, $tokenName, $tokenOptions);
return $this->tagList[$tokenName]->parse($context, $arguments, $tokenName, $tokenOptions);
}
elseif ( $this->extensionList[$token] ?? false ) {
return $this->extensionList[$token]->parse($context, $arguments, $token);
elseif ( $this->extensionList[$tokenName] ?? false ) {
$this->eventExecute(CompileTokenExtensionEvent::class, $context, $arguments, $tokenName, $tokenOptions);
return $this->extensionList[$tokenName]->parse($context, $arguments, $tokenName, $tokenOptions);
}
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);
@@ -87,6 +97,10 @@ class Compiler
public function registerControlStructure(ControlStructure\ControlStructure $controlStructureObject) : self
{
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;
}
@@ -98,6 +112,10 @@ class Compiler
$tokens = $extension->tokens ?? (array) ( $extension->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;
}
@@ -122,15 +140,22 @@ class Compiler
}
public function __toString() : string
{
return "???";
}
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
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);
}
return $this->extensionList[$name];
return $this->extensionList[$tokenName];
}
public function exportFunctions() : void
+19 -1
View File
@@ -4,7 +4,25 @@ namespace Picea\Compiler;
class BaseContext extends Context {
public function __construct(?string $defaultNamespace = null) {
public function __construct(
?string $defaultNamespace = null,
public string $namespace = "",
public string $extendFrom = "",
public string $className = "",
public string $compiledSource = "",
public ? string $sectionAction = null,
public string $viewPath = "",
public string $filePath = "",
public string $classPath = "",
public string $declare = "declare(strict_types=1);",
public array $switchStack = [],
public array $iterationStack = [],
public array $useStack = [],
public array $sections = [],
public int $functions = 0,
public array $functionStack = [],
public array $hooks = []
) {
if ( $defaultNamespace !== null ) {
$this->namespace = $defaultNamespace;
}
+13 -25
View File
@@ -6,30 +6,6 @@ use Picea\Compiler;
abstract class Context {
public string $namespace = "";
public string $extendFrom = "";
public string $className = "";
public string $compiledSource = "";
public string $viewPath = "";
public string $filePath = "";
public array $switchStack = [];
public array $iterateStack = [];
public array $useStack = [];
public int $functions = 0;
public array $functionStack = [];
public array $hooks = [];
public Compiler $compiler;
public function hook(string $path, Callable $callback) : self
@@ -51,7 +27,7 @@ abstract class Context {
public function renderUses() : string
{
return implode(",", $this->useStack ?? []);
return implode(PHP_EOL, array_map(fn($use) => "use $use;", $this->useStack ?? []));
}
public function renderFunctions() : string
@@ -86,6 +62,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
{
$this->functionStack[$name] = $callable;
+7 -8
View File
@@ -4,10 +4,8 @@ namespace Picea\ControlStructure;
abstract class AbstractLoop implements ControlStructure {
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) {
switch($token) {
case "while":
case "foreach":
protected function openLoop(\Picea\Compiler\Context &$context, ?string $arguments, string $token,) : string
{
$name = "$".uniqid("{$token}_");
$stack = array_filter($context->iterationStack ?? [], function($item) {
@@ -26,10 +24,11 @@ abstract class AbstractLoop implements ControlStructure {
'token' => "end{$token}",
];
return "<?php $token ($arguments): $name = ( $name ?? 0 ) + 1; ?>";
return "<?php $token ($arguments): \$__loop_index = $name = ( $name ?? 0 ) + 1; ?>";
}
case "endwhile":
case "endforeach":
protected function closeLoop(\Picea\Compiler\Context &$context, ?string $arguments, string $token,) : string
{
$last = end($context->iterationStack);
if ( $last['or'] === false ) {
@@ -43,5 +42,5 @@ abstract class AbstractLoop implements ControlStructure {
return $output;
}
}
}
+125 -25
View File
@@ -2,25 +2,35 @@
namespace Picea\ControlStructure;
use http\Exception\InvalidArgumentException;
class BlockToken implements ControlStructure {
public array $token = [ "arguments", "block", "endblock", "define", "slot", "endslot", "using" ];
public array $token = [ "arguments", "block", "endblock", "/block", "define", "slot", "endslot", "/slot", "using", "public", "private", "protected", "set" ];
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 $depth = 0;
static $slotDepth = 0;
static $slotDefinitions = [];
static $slotName = [];
$class= static::class;
# dump($slotDepth, $token, $arguments, $slotDefinitions);
switch($token) {
case "block":
$slotDefinitions[] = $this->slotDefinitions();
$depth++;
return "<?php \$___block = \Picea\ControlStructure\BlockToken::instanciateBlock($arguments); ?>";
case "/block":
case "endblock":
$depth--;
return "<?php echo \$___block->render(\$___class__template); unset(\$___block); ?>";
case "arguments":
$class = static::class;
return <<<PHP
<?php
try {
@@ -29,8 +39,10 @@ class BlockToken implements ControlStructure {
unset(\$inlineVariables);
}
catch(\TypeError \$ex) {
\$showArgs = fn(\$e) => (\$type = gettype(\$e)) === 'object' ? \$e::class : \$type;
throw new \Exception(
sprintf('A block awaiting arguments `%s` instead received `%s` with values `%s`', '$arguments', implode(', ', array_map('gettype', \$inlineVariables ?? [])), json_encode(\$inlineVariables))
sprintf('A block awaiting arguments (%s) instead received (%s) with values (%s)', '$arguments', implode(', ', array_map(\$showArgs, \$inlineVariables ?? [])), json_encode(\$inlineVariables))
);
}
/*%EXCEPTION_LINE_BASE%*/?>
@@ -39,30 +51,33 @@ class BlockToken implements ControlStructure {
case "define":
list($name, $definition) = array_pad(explode(',', $arguments, 2), 2, "");
end($slotDefinitions)->setDefinition(eval("return $name;"), $definition);
( $slotDefinitions[$depth] ?? end($slotDefinitions) )->setDefinition(eval("return $name;"), $definition);
return <<<PHP
<?php \$this->defineSlot($name, function($definition) {}); ?>
PHP;
case "slot":
$def = end($slotDefinitions);
$def = ( $slotDefinitions[$depth] ?? end($slotDefinitions) );
list($name, $definition) = array_pad(explode(',', $arguments, 2), 2, "");
if ($def->hasDefinitions() ) {
$slotName = eval("return $name;");
$def->currentSlot = $slotName;
$def->setDefinitionVars($slotName, $definition);
$loops = count($context->iterationStack ?? []) ? ",". implode(', ', array_filter(array_column($context->iterationStack, 'uid'), fn($e) => strpos($e, '[') === false)) : null;
$slotDepth++;
$definition = $def->printDefinition($slotName);
if ($def->hasDefinitions() ) {
$slotName[] = eval("return $name;");
$def->currentSlot = end($slotName);
$def->setDefinitionVars(end($slotName), $definition);
$definition = $def->printDefinition(end($slotName));
if ($definition) {
$definition .= ",";
}
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, \$___class__template $loops) { extract(\$___using, \EXTR_SKIP); ?>
PHP;
}
else {
@@ -71,14 +86,17 @@ class BlockToken implements ControlStructure {
}
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 ?? \$this)->setSlot($name, function($definition array \$___using = []) use (\$picea, \$___class__template $loops) { extract(\$___using, \EXTR_SKIP); ?>
PHP;
}
case "/slot":
case "endslot":
$def =end($slotDefinitions);
$slotDepth--;
$def = ( $slotDefinitions[$depth] ?? end($slotDefinitions) );
if ($def->hasDefinitions() ) {
$def->currentSlot = array_pop($slotName);
$definition = $def->getCurrentSlotDefinitionVars();
if ($definition) {
@@ -93,11 +111,22 @@ class BlockToken implements ControlStructure {
return "<?php }); ?>";
}
case "public":
case "private":
case "protected":
$arguments = rtrim($arguments, ';');
return "<?php \$this->createProperty(\\$class::parseProperty('$token', fn($arguments) => func_get_arg(0))) ?>";
case "set":
return "<?php \$___block->setPropertyValue({$arguments}); ?>";
# DEPRECATED ; should be removed, to be superseded by 'set' instead
case "using":
return "<?php \$___block->setUsing($arguments); ?>";
}
}
throw new \LogicException("Unhandled token ? Should never have been here !");
}
public function inlineHtml(? object $proxy, string $viewPath, ... $variables) {
return $this->renderHtml($viewPath, [ 'inlineVariables' => $variables ], $proxy);
@@ -108,7 +137,6 @@ class BlockToken implements ControlStructure {
#return
}
public static function parseArguments(Callable $method, array $arguments) : array
{
try{
@@ -121,23 +149,51 @@ class BlockToken implements ControlStructure {
$parameters = [];
foreach((new \ReflectionFunction($method))->getParameters() as $key => $value) {
$name = $value->getName();
# Ordered arguments
if ( isset($arguments[$key]) ) {
$parameters[ $value->getName() ] = $arguments[$key];
$parameters[ $name ] = $arguments[$key];
}
# Named arguments
elseif (isset($arguments[$name])) {
$parameters[ $name ] = $arguments[$name];
}
# Using default value
elseif ( $value->isDefaultValueAvailable() ) {
$parameters[ $value->getName() ] = $value->getDefaultValue();
$parameters[ $name ] = $value->getDefaultValue();
}
elseif ( $value->isVariadic() ) {
$parameters[ $value->getName() ] = [];
$parameters[ $name ] = [];
}
else {
$parameters[ $value->getName() ] = null;
$parameters[ $name ] = null;
}
}
return $parameters;
}
public static function parseProperty(string $token, \Closure $method) : BlockToken\Property
{
foreach((new \ReflectionFunction($method))->getParameters() as $value) {
$property = new BlockToken\Property(
name: $value->getName(),
scope: BlockToken\PropertyScopeEnum::from($token),
setter: $method,
);
if ($value->isDefaultValueAvailable()) {
$property->value = $value->getDefaultValue();
}
# For now, we only allow one declaration per token, might be revised at another moment...
break;
}
return $property ?? throw new \LogicException("No parameters found in property declaration.");
}
public static function slotDefinitions() {
return new class() {
@@ -181,7 +237,7 @@ class BlockToken implements ControlStructure {
public function printDefinition(string $name) : string
{
if ( ! isset($this->definitions[$name]) ) {
throw new \Exception("Slot definition for `$name` was not found. Have you defined it in your block header ?");
throw new \Exception("Slot definition for `$name` was not found. Have you defined it in your block header using something like '{% define \"$name\", ...\$arguments %}' ?");
}
return $this->definitions[$name];
@@ -191,7 +247,6 @@ class BlockToken implements ControlStructure {
{
$this->rendering = true;
}
};
}
@@ -211,6 +266,10 @@ class BlockToken implements ControlStructure {
public array $definition = [];
protected array $properties = [];
private array $definedPropertyValues = [];
public function __construct(string $viewPath, ...$arguments) {
$this->viewPath = $viewPath;
$this->arguments = $arguments;
@@ -220,6 +279,10 @@ class BlockToken implements ControlStructure {
{
$this->rendering = true;
if ($this->using['this'] ?? false) {
throw new \InvalidArgumentException("Block '{$this->viewPath}' cannot overwrite 'this' variable.");
}
return $classTemplate->picea->inlineBlock($this, $this->viewPath, ...$this->arguments);
}
@@ -238,14 +301,51 @@ class BlockToken implements ControlStructure {
return ! empty($this->slots[$name]);
}
public function printSlot(string $name, Callable $default)
public function printSlot(string $name, Callable $default) : mixed
{
return $this->slotIsSet($name) ? $this->slots[$name] : $default;
}
public function setUsing(array $variables) {
public function setUsing(array $variables) : void
{
$this->using = $variables;
}
public function setPropertyValue(array $vars) : void
{
foreach($vars as $key => $value) {
$this->definedPropertyValues[$key] = $value;
}
}
public function createProperty(BlockToken\Property $property) : void
{
if (isset($this->properties[$property->name])) {
throw new \InvalidArgumentException("Given property '{$property->name}' is already defined somewhere else in this block.");
}
$this->properties[$property->name] = $property;
if (isset($this->definedPropertyValues[$property->name])) {
if ($property->scope !== BlockToken\PropertyScopeEnum::Public) {
throw new \InvalidArgumentException(
sprintf("Trying to set property %s but it's scope (%s) makes it impossible", $property->name, $property->scope->name)
);
}
$this->__set($property->name, $this->definedPropertyValues[$property->name]);
}
}
public function __set(string $name, mixed $value) : void
{
$this->properties[$name]->value = call_user_func($this->properties[$name]->setter, $value);
}
public function __get(string $name) : mixed
{
return $this->properties[$name]->value;
}
};
}
}
@@ -0,0 +1,14 @@
<?php
namespace Picea\ControlStructure\BlockToken;
class Property
{
public mixed $value;
public function __construct(
public readonly string $name,
public readonly PropertyScopeEnum $scope,
public readonly \Closure $setter,
) {}
}
@@ -0,0 +1,10 @@
<?php
namespace Picea\ControlStructure\BlockToken;
enum PropertyScopeEnum: string
{
case Private = "private";
case Protected = "protected";
case Public = "public";
}
+3 -2
View File
@@ -4,9 +4,10 @@ namespace Picea\ControlStructure;
class BreakToken implements ControlStructure {
public string $token = "break";
public array $token = [ "break", "/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
{
return "<?php break; ?>";
}
+2 -1
View File
@@ -6,7 +6,8 @@ class CaseToken implements ControlStructure {
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 = "";
if ( $context->switchStack ) {
+1 -1
View File
@@ -6,7 +6,7 @@ class ContinueToken implements ControlStructure {
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; ?>";
}
+1 -1
View File
@@ -6,7 +6,7 @@ class DefaultToken implements ControlStructure {
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 = "";
if ( $context->switchStack ) {
+1 -1
View File
@@ -6,7 +6,7 @@ class EchoToken implements ControlStructure {
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) {
case "echo":
return "<?php \\Picea\\ControlStructure\\EchoToken::echoSafe($arguments) ?>";
+3 -2
View File
@@ -4,9 +4,9 @@ namespace Picea\ControlStructure;
class ForToken implements ControlStructure {
public array $token = [ "for", "endfor" ];
public array $token = [ "for", "endfor", "/for" ];
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) {
case "for":
$uid = "$".uniqid("for_");
@@ -19,6 +19,7 @@ class ForToken implements ControlStructure {
return "<?php for ($arguments): {$uid} = 1; ?>";
case "/for":
case "endfor":
$last = end($context->iterationStack);
+13 -1
View File
@@ -5,5 +5,17 @@ namespace Picea\ControlStructure;
use DI\Definition\Source\AnnotationBasedAutowiring;
class ForeachToken extends AbstractLoop {
public array $token = [ "foreach", "endforeach" ];
public array $token = [ "foreach", "endforeach", "/foreach" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
switch($token) {
case "foreach":
return $this->openLoop($context, $arguments, $token);
case "endforeach":
case "/foreach":
return $this->closeLoop($context, $arguments, $token);
}
}
}
+5 -3
View File
@@ -6,7 +6,7 @@ class FunctionToken implements ControlStructure {
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) {
case "function":
$context->functions++;
@@ -33,7 +33,9 @@ class FunctionToken implements ControlStructure {
protected function printFunction($context, ?string $arguments) : string
{
return "<?php function $arguments { ?>";
$name = trim(explode('(', $arguments, 2)[0]);
return "<?php if (! function_exists(__NAMESPACE__ . '\\$name')) { function $arguments { ?>";
}
protected function printReturn($context, ?string $arguments) : string
@@ -43,6 +45,6 @@ class FunctionToken implements ControlStructure {
protected function printEndFunction($context) : string
{
return "<?php } ?>";
return "<?php } } ?>";
}
}
+3 -2
View File
@@ -4,9 +4,9 @@ namespace Picea\ControlStructure;
class IfToken implements ControlStructure {
public array $token = [ "if", "else", "elseif", "endif" ];
public array $token = [ "if", "else", "elseif", "endif", "/if" ];
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) {
case "if":
return "<?php if ($arguments): ?>";
@@ -17,6 +17,7 @@ class IfToken implements ControlStructure {
case "elseif":
return "<?php elseif ($arguments): ?>";
case "/if":
case "endif":
return "<?php endif ?>";
}
+1 -1
View File
@@ -6,7 +6,7 @@ class NamespaceToken implements ControlStructure {
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;
return "";
}
+1 -1
View File
@@ -6,7 +6,7 @@ class OrToken implements ControlStructure {
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) ) {
throw new \LogicException("Token `or` was used outside of iterator. Make sure your `for`, `foreach`, `while`, `do/until` declaration are properly made.");
}
+39 -10
View File
@@ -2,25 +2,45 @@
namespace Picea\ControlStructure;
enum PrintActionEnum : string {
case prepend = "prepend";
case default = "default";
case append = "append";
# case both = "both";
}
class SectionToken implements ControlStructure {
public array $token = [ "section", "endsection" ];
public array $token = [ "section", "endsection", "/section" ];
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;
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) {
switch($token) {
case "section":
return $this->printSection($context, $arguments);
case "endsection":
case "/endsection":
if ( empty($context->sections) ) {
throw new \RuntimeException("A section closing tag {% endsection %} was found without an opening {% section %} tag");
}
$this->action = PrintActionEnum::default;
return $this->printEndSection($context);
}
}
protected function printSection($context, ?string $arguments) : string
protected function printSection($context, ? string $arguments) : string
{
list($name, $options) = array_pad(explode(',', $arguments, 2), 2, null);
@@ -28,7 +48,7 @@ class SectionToken implements ControlStructure {
$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");
}
@@ -37,7 +57,7 @@ class SectionToken implements ControlStructure {
'options' => $options,
];
$action = $options['action'] ?? "default";
$action = $options['action'] ?? $this->action->value;
if (! in_array($action, ['prepend', 'append', 'default'])) {
throw new \RuntimeException("An unsupported action `$action` was given as an option of a {% section %} tag");
@@ -45,15 +65,24 @@ class SectionToken implements ControlStructure {
$order = $options['order'] ?? "count(\$___class__template->sectionList[$name]['$action'])";
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) {".
"extract(\$___global_variables); extract(\$___variables, \EXTR_OVERWRITE); \$___class__template->sectionStack[] = '$name'; ?>";
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, \$__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
{
$section = array_pop($context->sections);
$build = $context->extendFrom ? "!empty(\$___class__template->sectionStack) && \$___class__template->renderSection({$section['name']});" : "\$___class__template->renderSection({$section['name']});";
return "<?php array_pop(\$___class__template->sectionStack); }]; $build?>";
$build = $context->extendFrom ? "!empty(\$___class__template->sectionStack) && \$___class__template->renderSection({$section['name']}, false);" : "\$___class__template->renderSection({$section['name']}, false);";
return "<?php \$__event->eventExecute(\Picea\Event\Builder\ClassTemplateRenderSectionDone::class, {$section['name']});" .
"array_pop(\$___class__template->sectionStack); }];" .
$build .
"?>";
}
}
+4 -2
View File
@@ -4,9 +4,9 @@ namespace Picea\ControlStructure;
class SwitchToken implements ControlStructure {
public array $token = [ "switch", "case", "endswitch" ];
public array $token = [ "switch", "case", "endcase", "endswitch", "/switch" ];
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) {
case "switch":
$context->switchStack[] = true;
@@ -25,9 +25,11 @@ class SwitchToken implements ControlStructure {
return ( $output ?? "" ) . "case $arguments: ?>";
case "endcase":
case "/case":
return "<?php break; ?>";
case "endswitch":
case "/switch":
return "<?php endswitch; ?>";
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Picea\ControlStructure;
class TryCatchToken implements ControlStructure {
public array $token = [ "try", "catch", "finally", "endtry", "/try" ];
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string {
switch($token) {
case "try":
return "<?php try { ?>";
case "catch":
return "<?php } catch($arguments) { ?>";
case "finally":
return "<?php } finally { ?>";
case "endtry":
case "/try":
return "<?php } ?>";
}
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ class UseToken implements ControlStructure {
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;
return "";
}
+1 -1
View File
@@ -6,7 +6,7 @@ class ViewToken implements ControlStructure {
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
return "<?php echo \$___class__template->picea->inlineHtml(\$this, $arguments, get_defined_vars()); ?>";
}
+8 -5
View File
@@ -3,9 +3,9 @@
namespace Picea\ControlStructure;
class WhileToken extends AbstractLoop {
public array $token = [ "do", "while", "endwhile", ];
public array $token = [ "do", "while", "endwhile", "/while" ];
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) {
case "do":
$context->iterationStack[] = [
@@ -23,10 +23,13 @@ class WhileToken extends AbstractLoop {
return "<?php } while($arguments); ?>";
}
}
return $this->openLoop($context, $arguments, $token);
case "endwhile":
case "/while":
return $this->closeLoop($context, $arguments, $token);
}
return parent::parse($context, $arguments, $token);
}
}
@@ -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 = []);
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Picea\Event\Extension;
interface BuildAssetUrl
{
public function execute(string $uri, array $parameters = [], bool $appendVersion = true) : mixed;
}
@@ -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
{
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);
$this->picea = $picea;
$this->defineError($previous, $compiledObject);
$this->defineError($previous, $template);
}
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) {
if ( isset($trace['file'], $loadedTemplates[$trace['file']]) ) {
$class = $loadedTemplates[ $trace['file'] ];
$content = include($trace['file']);
$this->file = $content['view'];
$this->line = $class::getSourceLineFromException($trace['line']);
return;
}
}
$this->file = $template::getParam('view');
$this->line = $template::getSourceLineFromException($previous->getLine());
}
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;
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace Picea\Extension;
use Picea\Compiler\Context;
use Psr\Container\ContainerInterface;
class DiExtension implements Extension, FunctionExtension {
public array $token = [ "di:has", "di:get" ];
public function __construct(public readonly ContainerInterface $container) {}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
if ( $token === 'di:get' ) {
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->container->get($arguments) ?>";
}
if ( $token === 'di:has' ) {
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->container->has($arguments) ?>";
}
throw new \InvalidArgumentException("You must use di:get/di:has tokens or di_get()/di_has() methods.");
}
public function exportFunctions(): array
{
return [
'di_get' => function(string $classname) {
return $this->container->get($classname);
},
'di_has' => function(string $classname) {
return $this->container->has($classname);
},
];
}
}
+1 -1
View File
@@ -3,5 +3,5 @@
namespace Picea\Extension;
interface Extension {
public function parse(\Picea\Compiler\Context &$context, string $sourceCode, string $token);
public function parse(\Picea\Compiler\Context &$context, string $arguments, string $token, array $options = []) : string;
}
+7 -8
View File
@@ -6,21 +6,20 @@ use Picea\Compiler\Context;
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 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;
switch ($token) {
case "json.pretty":
if ( in_array('pretty', $options) ) {
$flag |= \JSON_PRETTY_PRINT;
break;
}
case "json.html":
return "<?php echo htmlentities(json_encode($arguments, {$this->flags}), ENT_QUOTES, 'UTF-8') ?>";
if ( in_array('html', $options) ) {
return "<?php echo htmlentities(json_encode($arguments, $flag), ENT_QUOTES, 'UTF-8') ?>";
}
$cls = static::class;
@@ -32,7 +31,7 @@ class JsonExtension implements Extension, FunctionExtension {
{
return [
'json' => function($arguments, ? int $flags = null) {
return json_encode($arguments, \JSON_FORCE_OBJECT);
return json_encode($arguments, $flags ?? $this->flags);
},
];
}
+49 -16
View File
@@ -3,18 +3,17 @@
namespace Picea\Extension;
use Picea\Compiler\Context;
use Picea\Event\Builder\ClassTemplateRenderSectionDone;
class LanguageExtension implements Extension, FunctionExtension {
public array $tokens = [ "lang", "lang.raw", "_", "_.raw", "language.set" ];
public array $tokens = [ "lang", "_", "language" ];
public string $currentLanguage = "";
protected LanguageHandler $languageHandler;
public function __construct(LanguageHandler $handler) {
$this->languageHandler = $handler;
}
public function __construct(
protected LanguageHandlerInterface $languageHandler
) {}
public function exportFunctions(): array
{
@@ -24,25 +23,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) {
case "language.set":
return "<?php \$picea->compiler->getExtensionFromToken('$token')->currentLanguage = $arguments; ?>";
switch(explode('.', $token)[0]) {
case "language":
$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":
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) ?>";
case "lang.raw":
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->absoluteLang($arguments) ?>";
case "_":
return "<?php echo htmlspecialchars(\$picea->compiler->getExtensionFromToken('$token')->relativeLang($arguments), \ENT_QUOTES, ini_get('default_charset'), true) ?>";
case "_.raw":
if ( in_array('raw', $options) ) {
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 "";
}
@@ -59,4 +75,21 @@ class LanguageExtension implements Extension, FunctionExtension {
{
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;
interface LanguageHandler
interface LanguageHandlerInterface
{
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));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?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];
$this->formatter = new \NumberFormatter($this->locale, \NumberFormatter::CURRENCY);
}
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->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 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 ?>";
}
}
+14 -9
View File
@@ -6,9 +6,9 @@ use Picea\Compiler\Context;
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 | \ENT_DISALLOWED | \ENT_SUBSTITUTE;
public string $encoding;
@@ -18,22 +18,27 @@ class PrintExtension implements Extension {
$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) {
case 'echo':
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") . ") ?>";
case 'echo.raw':
case "print.raw":
return "<?php echo $arguments ?>";
case 'printf':
if (in_array('raw', $options)) {
return "<?php printf((string) $arguments) ?>";
}
return "<?php echo htmlspecialchars(sprintf((string) $arguments), {$this->flag}, '{$this->encoding}', " . ($this->doubleEncode ? "true" : "false") . ") ?>";
case 'printf.raw':
return "<?php printf((string) $arguments) ?>";
case 'no_html':
return "<?php echo nl2br(strip_tags((string) $arguments)) ?>";
}
}
+13 -12
View File
@@ -2,28 +2,28 @@
namespace Picea\Extension;
use Picea\Compiler\Context;
class TitleExtension implements Extension {
class TitleExtension implements Extension, FunctionExtension {
public string $token = "title";
public string $title = "";
public function __construct(Context $context) {
$this->register($context);
}
public function register(Context $context) : void
public function exportFunctions(): array
{
$context->pushFunction("title", [ $this, 'handleTitle' ]);
return [
"title" => [$this, 'handleTitle'],
];
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) {
return "<?php echo title($arguments) ?>";
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string
{
return "<?php ".
"if ( null !== \$title = title($arguments) ) {".
"echo \$title;".
"} ?>";
}
public function handleTitle(? string $set = null, ...$arguments) : ? string
public function handleTitle(null|\Stringable|string $set = null, ...$arguments) : ? string
{
if ( $set === null ) {
return $this->title;
@@ -31,6 +31,7 @@ class TitleExtension implements Extension {
else {
# Fixed a bug where template inheritance was rewriting title
if ( empty($this->title) ) {
$set = (string) $set;
$this->title = $arguments ? sprintf($set, ...$arguments) : $set;
}
}
+103 -43
View File
@@ -2,9 +2,11 @@
namespace Picea\Extension;
use Picea\Compiler\Context;
use Picea\EventTrait;
use Picea\Event\Extension\{ UrlBuildAssetEvent, UrlBuildUrlEvent, UrlBuildRouteEvent, UrlRegisterRouteEvent };
class UrlExtension implements Extension {
class UrlExtension implements Extension, FunctionExtension {
use EventTrait;
public const URLIZE_PATTERN_URL = <<<PATTERN
~(?<!href=['"])https?://[\w/._\-&?]*(?!</a>)(?=[^\w/._\-&])~s
@@ -14,23 +16,25 @@ class UrlExtension implements Extension {
/(?:[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])/
PATTERN;
protected string $urlBase;
protected string $assetToken;
protected array $routes;
protected array $routesTarget;
public array $tokens = [ "url" , "route", "route.cacheless", "asset", "url.current", "url.parameters", "slug" ];
public array $tokens = [ "url" , "route", "asset", "slug" ];
public function __construct(Context $context, string $urlBase = "", string $assetToken = "") {
##[\Deprecated]
public bool $enforceExistingArguments = true;
public function __construct(
protected string $urlBase = "",
protected string $assetToken = "",
protected array $appUrl = [],
protected bool $forceSSL = false
) {
$this->urlBase = trim($urlBase, "/");
$this->assetToken = $assetToken;
$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
{
switch($token) {
case "asset":
@@ -40,29 +44,32 @@ PATTERN;
return "<?php echo \$picea->compiler->getExtensionFromToken('$token')->buildRouteUrl($arguments) ?>";
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) ?>";
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":
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 \Exception("Unknown token given $token in UrlExtension.");
}
public function register(Context $context) : void
public function exportFunctions(): array
{
$context->pushFunction("url", [ $this, 'buildUrl' ]);
$context->pushFunction("current_url", [ $this, 'currentUrl' ]);
$context->pushFunction("asset", [ $this, 'buildAssetUrl' ]);
$context->pushFunction("route", [ $this, 'buildRouteUrl' ]);
$context->pushFunction("slug", [ $this, 'slug' ]);
$context->pushFunction("urlize", [ $this, 'urlize' ]);
return [
"url" => [ $this, 'buildUrl' ],
"current_url" => [ $this, 'currentUrl' ],
"asset" => [ $this, 'buildAssetUrl' ],
"route" => [ $this, 'buildRouteUrl' ],
"slug" => [ $this, 'slug' ],
"urlize" => [ $this, 'urlize' ]
];
}
public function getRouteList(bool $full = false) : array
@@ -93,18 +100,22 @@ PATTERN;
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);
}
public function buildAssetUrl(string $uri, array $parameters = [], bool $appendVersion = true) : string
{
$this->eventExecute(UrlBuildAssetEvent::class, $uri, $parameters, $appendVersion);
return $this->buildUrl($uri, $parameters, $appendVersion);
}
public function buildRouteUrl(string $name, array $parameters = [], bool $appendVersion = false) : string
{
if ( false !== ( $route = $this->routes[$name] ?? false ) ) {
return $this->buildUrl($this->prepareRoute($route['route'], $parameters), $parameters, $appendVersion);
if ( false !== $route = $this->findRoute($name) ) {
return $this->buildUrl($this->prepareRoute($route, $parameters), $parameters, $appendVersion);
}
$routeList = json_encode($this->routes, \JSON_PRETTY_PRINT);
@@ -120,19 +131,40 @@ PATTERN;
return $this->scheme() . $this->domain() . $this->base();
}
public static function slug(string $text, string $separator = '-') : string
# src: https://stackoverflow.com/a/14550919
public static function slug(\Stringable|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', (string) $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
{
$this->routes[$name] = [
$this->routes[] = $array = [
'name' => $name,
'route' => $route,
'routeMethods' => $routeMethods,
'routeMethods' => array_map('strtoupper', $routeMethods),
'class' => $class,
'classMethod' => $method,
];
$this->eventExecute(UrlRegisterRouteEvent::class, $name, $array);
}
protected function findRoute(string $name, string $method = "*") : false|array
{
foreach($this->routes as $route) {
if ( $route['name'] === $name ) {
if ($method === '*' || in_array(strtoupper($method), $route['routeMethods']) ) {
return $route;
}
}
}
return false;
}
/**
@@ -159,7 +191,7 @@ PATTERN;
protected function scheme() : string
{
return ( $this->isHttps() ? "https" : "http" ) . "://";
return ( $this->forceSSL || $this->isHttps() ? "https" : "http" ) . "://";
}
protected function base() : string
@@ -178,7 +210,25 @@ PATTERN;
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
@@ -203,32 +253,42 @@ PATTERN;
|| ( "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) ) {
$search = [];
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]);
}
elseif (strpos($item[1], ":") !== false) {
# Handles type
if (strpos($variable, ":") !== false) {
list($variable, ) = explode(':', $item[1]);
}
else {
$variable = $item[1];
}
if ( array_key_exists($variable, $arguments) ) {
$value = $arguments[ $variable ];
unset($arguments[ $variable ]);
}
else {
$value = $default ?? "";
if ($default ?? false) {
$value = $default;
}
elseif ( $this->enforceExistingArguments && ! preg_match(sprintf("/\[\/?%s]/i", $item[0]), $route) ) {
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);
+7 -12
View File
@@ -6,18 +6,11 @@ use Picea\Compiler;
class DefaultRegistrations implements LanguageRegistration
{
protected array $extensions;
protected array $syntaxes;
protected array $controlStructures;
public function __construct(array $extensions = [], array $syntaxes = [], array $controlStructure = [])
{
$this->extensions = $extensions;
$this->syntaxes = $syntaxes;
$this->controlStructures = $controlStructure;
}
public function __construct(
protected array $extensions,
protected array $syntaxes,
protected array $controlStructures,
) { }
public function registerAll(Compiler $compiler) : void
{
@@ -39,6 +32,7 @@ class DefaultRegistrations implements LanguageRegistration
public function registerControlStructure(Compiler $compiler) : void
{
$compiler->registerControlStructure(new \Picea\ControlStructure\TryCatchToken());
$compiler->registerControlStructure(new \Picea\ControlStructure\NamespaceToken());
$compiler->registerControlStructure(new \Picea\ControlStructure\UseToken());
$compiler->registerControlStructure(new \Picea\ControlStructure\IfToken());
@@ -67,6 +61,7 @@ class DefaultRegistrations implements LanguageRegistration
$compiler->registerExtension(new \Picea\Extension\PhpExtension());
$compiler->registerExtension(new \Picea\Extension\PrintExtension());
$compiler->registerExtension(new \Picea\Extension\JsonExtension());
$compiler->registerExtension(new \Picea\Extension\BatchExtension());
foreach($this->extensions ?? [] as $extension) {
$compiler->registerExtension($extension);
+16 -17
View File
@@ -5,34 +5,33 @@ namespace Picea\Method;
use Picea\Extension\Extension,
Picea\Extension\ExtensionTrait;
use Picea\Compiler\Context;
use Picea\Extension\FunctionExtension;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ServerRequestInterface;
class Request implements Extension {
class
Request implements Extension, FunctionExtension {
use ExtensionTrait;
public array $tokens;
public string $token;
public ServerRequestInterface $request;
public function __construct(
public ServerRequestInterface $request
) { }
public function __construct(ServerRequestInterface $request, Context $context) {
$this->request = $request;
$this->register($context);
}
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string { }
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token) : string { }
public function register(Context $context) : void
public function exportFunctions(): array
{
$context->pushFunction("cookie", [ $this, 'cookie' ]);
$context->pushFunction("get", [ $this, 'get' ]);
$context->pushFunction("post", [ $this, 'post' ]);
$context->pushFunction("request", [ $this, 'request' ]);
$context->pushFunction("server", [ $this, 'server' ]);
return [
"cookie" => [ $this, 'cookie' ],
"get" => [ $this, 'get' ],
"post" => [ $this, 'post' ],
"request" => [ $this, 'request' ],
"server" => [ $this, 'server' ],
];
}
public function cookie(? string $variableName = null, $default = null)
@@ -82,7 +81,7 @@ class Request implements Extension {
$post = $this->request->getParsedBody();
if ( ! $post ) {
$content = utf8_encode((string) $this->request->getBody());
$content = mb_convert_encoding((string)$this->request->getBody(), 'UTF-8', 'ISO-8859-1');
if ( $content && ( $json = json_decode($content, true) ) ) {
$post = $json;
+10 -9
View File
@@ -43,7 +43,7 @@ class Picea implements LanguageRegistration
){
$this->cache = $cache ?? new Caching\Memory("");
$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->compiler = $compiler ?? $this->instanciateCompiler();
$this->fileFetcher = $fileFetcher ?? $this->instanciateFileFetcher();
@@ -54,7 +54,7 @@ class Picea implements LanguageRegistration
$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) ) {
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
{
$object = $this->gatherTemplateObject($viewPath, $variables, $proxy);
$object = $this->gatherCompiledObject($viewPath, $variables, $proxy);
try {
return call_user_func($object);
}
catch(\Throwable $ex) {
if (! $ex instanceof Exception\RenderHtmlException ) {
throw new Exception\RenderHtmlException($object, $this, "An error occurred trying to render HTML view `$viewPath` : " . $ex->getMessage(), 911, $ex);
}
else {
#if (! $ex instanceof Exception\RenderHtmlException ) {
# throw new Exception\RenderHtmlException($object, $this, "An error occurred trying to render HTML view `$viewPath` : " . $ex->getMessage(), 911, $ex);
#}
#else {
throw $ex;
}
#}
}
exit();
return null;
}
/**
@@ -180,6 +180,7 @@ class Picea implements LanguageRegistration
{
if ( $this->debug || ! $this->cache->compiled( $context->cacheFilename() ) ) {
$context = $this->compileContext($context);
$this->cache->save($context);
}