Skip to content

Commit

Permalink
update: add more unit tests, update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Nov 11, 2021
1 parent fc06482 commit 1df2b2a
Show file tree
Hide file tree
Showing 11 changed files with 230 additions and 82 deletions.
108 changes: 82 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@

## Features

- it's simple and fastly
- It's simple and fastly.
- It is simply processed and converted into native PHP syntax
- simple echo syntax. eg: `{{= $var }}` `{{ $var }}` `{{ echo $var }}`
- chained access array value syntax. eg: `{{ $arr.0 }}` `{{ $map.name }}` `{{ $map.user.name }}`
- support php builtin string function as filters. eg: `{{ $var | ucfirst }}`
- support php builtin function as filters. eg: `{{ $var | ucfirst }}`
- support all control syntax. such as `if,elseif,else;foreach;for;switch`
- support add custom filters.
- default builtin filters: `upper` `lower` `nl`
- support add custom directive.

## Install
Expand All @@ -30,34 +32,62 @@ composer require phppkg/easytpl
```php
use PhpPkg\EasyTpl\EasyTemplate;

$tplCode = <<<'CODE'
My name is {{ $name | strtoupper }},
My develop tags:
{{ foreach($tags => $tag) }}
- {{ $tag }}

{{ endforeach }}
CODE;

$t = new EasyTemplate();
$t->renderString($tplCode);

$str = $t->renderString($tplCode, [
'name' => 'inhere',
'tags' => ['php', 'go', 'java'],
]);

echo $str;
```

## Custom directives
**Output**:

You can use the directives implement some special logic.
```text
My name is INHERE,
My develop tags:
- php
- go
- java
```

### More usage

**chained access array**

Use `.` access array value.

```php
$tpl = EasyTemplate::new();
$tpl->addDirective(
'include',
function (string $body, string $name) {
/** will call {@see EasyTemplate::include()} */
return '$this->' . $name . $body;
}
);
$arr = [
'val0',
'subKey' => 'val1',
];
```

In template can use:
Use in template:

```php
First value is: {{ $arr.0 }}
'subKey' value is: {{ $arr.subKey }}
```

{{ include('part/header.tpl', ['title' => 'My world']) }}
## Use Filters

```
Default builtin filters:

### Filters
- `upper` - equals `strtoupper`
- `lower` - equals `strtolower`
- `nl` append newline `\n`

### Using the filters

Expand All @@ -81,7 +111,7 @@ You can use the filters in any of your templates.
```php
{{ $name | ucfirst | substr:0,1 }}
{{ $user['name'] | ucfirst | substr:0,1 }}
{{ $currentUser->name | ucfirst | substr:0,1 }}
{{ $userObj->name | ucfirst | substr:0,1 }}
{{ getName() | ucfirst | substr:0,1 }}
```

Expand All @@ -95,14 +125,6 @@ You can use the filters in any of your templates.
{{ '12.75' | add_suffix:$suffix }} // 12.75¥
```

**Built-in functionality**:

```php
{{ 'This is a title' | slug }} // this-is-a-title
{{ 'This is a title' | title }} // This Is A Title
{{ 'foo_bar' | studly }} // FooBar
```

### Custom filters

```php
Expand All @@ -118,6 +140,40 @@ $tpl->addFilters([
return substr($str, -3);
},
]);
```

Use in template:

```php
{{
$name = 'inhere';
}}

{{ $name | upper }} // Output: INHERE
{{ $name | last3chars }} // Output: ere
{{ $name | last3chars | upper }} // Output: ERE
```

## Custom directives

You can use the directives implement some special logic.

```php
$tpl = EasyTemplate::new();
$tpl->addDirective(
'include',
function (string $body, string $name) {
/** will call {@see EasyTemplate::include()} */
return '$this->' . $name . $body;
}
);
```

In template can use:

```php

{{ include('part/header.tpl', ['title' => 'My world']) }}

```

Expand Down
32 changes: 22 additions & 10 deletions src/Compiler/AbstractCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PhpPkg\EasyTpl\Compiler;

use PhpPkg\EasyTpl\Contract\CompilerInterface;
use Toolkit\FsUtil\File;
use Toolkit\Stdlib\Str;
use function array_shift;
use function explode;
Expand All @@ -15,7 +16,6 @@
use function sprintf;
use function str_contains;
use function strlen;
use function vdump;

/**
* class AbstractCompiler
Expand Down Expand Up @@ -82,6 +82,18 @@ public function setOpenCloseTag(string $open, string $close): self
return $this;
}

/**
* @param string $tplFile
*
* @return string
*/
public function compileFile(string $tplFile): string
{
$tplCode = File::readAll($tplFile);

return $this->compile($tplCode);
}

/**
* @param string $echoBody
*
Expand All @@ -96,15 +108,6 @@ protected function parseInlineFilters(string $echoBody): string
$filters = Str::explode($echoBody, $this->filterSep);
$newExpr = array_shift($filters);

$coreFn = $this->echoFilterFunc;
if (
$coreFn
&& $coreFn !== self::RAW_OUTPUT
&& !in_array(self::RAW_OUTPUT, $filters, true)
) {
$newExpr = sprintf('%s(%s)', $coreFn, $newExpr);
}

foreach ($filters as $filter) {
if ($filter === self::RAW_OUTPUT) {
continue;
Expand Down Expand Up @@ -139,6 +142,15 @@ protected function parseInlineFilters(string $echoBody): string
}
}

$coreFn = $this->echoFilterFunc;
if (
$coreFn
&& $coreFn !== self::RAW_OUTPUT
&& !in_array(self::RAW_OUTPUT, $filters, true)
) {
$newExpr = sprintf('%s((string)%s)', $coreFn, $newExpr);
}

return $newExpr;
}

Expand Down
13 changes: 0 additions & 13 deletions src/Compiler/PregCompiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace PhpPkg\EasyTpl\Compiler;

use Toolkit\FsUtil\File;
use function addslashes;
use function array_keys;
use function explode;
Expand Down Expand Up @@ -50,18 +49,6 @@ public function setOpenCloseTag(string $open, string $close): self
return $this;
}

/**
* @param string $tplFile
*
* @return string
*/
public function compileFile(string $tplFile): string
{
$tplCode = File::readAll($tplFile);

return $this->compile($tplCode);
}

/**
* @param string $tplCode
*
Expand Down
18 changes: 13 additions & 5 deletions src/Compiler/Token.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ class Token
self::T_ENDIF,
];

/**
* will auto add char `:` on statement end.
*/
public const CAN_FIX_TOKENS = [
self::T_IF,
self::T_ELSEIF,
self::T_ELSE,
self::T_FOREACH,
self::T_CASE,
self::T_SWITCH
];

/**
* @return string
*/
Expand Down Expand Up @@ -125,10 +137,6 @@ public static function isAloneToken(string $type): bool
*/
public static function canAutoFixed(string $type): bool
{
return in_array(
$type,
[self::T_IF, self::T_ELSEIF, self::T_ELSE, self::T_FOREACH, self::T_CASE, self::T_SWITCH],
true
);
return in_array($type, self::CAN_FIX_TOKENS, true);
}
}
4 changes: 2 additions & 2 deletions src/Contract/TemplateInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function render(string $tplFile, array $tplVars): void;
*
* @return string
*/
public function renderFile(string $tplFile, array $tplVars): string;
public function renderFile(string $tplFile, array $tplVars = []): string;

/**
* Render template text to string
Expand All @@ -38,5 +38,5 @@ public function renderFile(string $tplFile, array $tplVars): string;
*
* @return string
*/
public function renderString(string $tplCode, array $tplVars): string;
public function renderString(string $tplCode, array $tplVars = []): string;
}
40 changes: 35 additions & 5 deletions src/EasyTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,44 @@ class EasyTemplate extends PhpTemplate implements EasyTemplateInterface
/**
* Class constructor.
*
* @param array $config
* @param array{compiler: class-string|CompilerInterface} $config
*/
public function __construct(array $config = [])
{
if (isset($config['compiler'])) {
$customCompiler = $config['compiler'];
// class-string
if (is_string($customCompiler)) {
$customCompiler = new $customCompiler;
}

$this->compiler = $customCompiler;
unset($config['compiler']);
} else {
$this->compiler = new PregCompiler();
}

parent::__construct($config);

$this->compiler = new PregCompiler();
$this->compiler->addDirective(
$this->init($this->compiler);
}

/**
* @param CompilerInterface $compiler
*/
protected function init(CompilerInterface $compiler): void
{
// add built-in filters
$this->addFilters([
'upper' => 'strtoupper',
'lower' => 'strtolower',
'nl' => function ($str): string {
return $str . "\n";
},
]);

// add directive: include
$compiler->addDirective(
'include',
function (string $body, string $name) {
/** will call {@see include()} */
Expand All @@ -67,7 +97,7 @@ function (string $body, string $name) {
*
* @return string
*/
public function renderFile(string $tplFile, array $tplVars): string
public function renderFile(string $tplFile, array $tplVars = []): string
{
$phpFile = $this->compileFile($tplFile);

Expand All @@ -80,7 +110,7 @@ public function renderFile(string $tplFile, array $tplVars): string
*
* @return string
*/
public function renderString(string $tplCode, array $tplVars): string
public function renderString(string $tplCode, array $tplVars = []): string
{
$tplCode = $this->compiler->compile($tplCode);

Expand Down
4 changes: 2 additions & 2 deletions src/PhpTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class PhpTemplate extends AbstractTemplate
*
* @return string
*/
public function renderString(string $tplCode, array $tplVars): string
public function renderString(string $tplCode, array $tplVars = []): string
{
$tempFile = $this->genTmpPhpFile($tplCode);

Expand All @@ -59,7 +59,7 @@ public function renderString(string $tplCode, array $tplVars): string
*
* @return string
*/
public function renderFile(string $tplFile, array $tplVars): string
public function renderFile(string $tplFile, array $tplVars = []): string
{
return $this->doRenderFile($tplFile, $tplVars);
}
Expand Down
Loading

0 comments on commit 1df2b2a

Please sign in to comment.