Rename Cytro to Fenom

This commit is contained in:
bzick 2013-06-28 11:53:53 +04:00
parent f36cecaaea
commit b9ac24bb5b
44 changed files with 479 additions and 641 deletions

View File

@ -1,9 +1,9 @@
Cytro - awesome template engine for PHP Fenom - awesome template engine for PHP
========================== ==========================
> Composer package: `{"bzick/cytro": "dev-master"}`. See on [Packagist.org](https://packagist.org/packages/bzick/cytro) > Composer package: `{"bzick/fenom": "dev-master"}`. See on [Packagist.org](https://packagist.org/packages/bzick/fenom)
[![Build Status](https://travis-ci.org/bzick/cytro.png?branch=master)](https://travis-ci.org/bzick/cytro) [![Build Status](https://travis-ci.org/bzick/fenom.png?branch=master)](https://travis-ci.org/bzick/fenom)
## [About](./docs/about.md) :: [Documentation](./docs/main.md) :: [Benchmark](./docs/benchmark.md) :: [Articles](./docs/articles.md) ## [About](./docs/about.md) :: [Documentation](./docs/main.md) :: [Benchmark](./docs/benchmark.md) :: [Articles](./docs/articles.md)
* Simplest known [syntax](./docs/syntax.md) * Simplest known [syntax](./docs/syntax.md)
@ -20,11 +20,11 @@ Simple template
```smarty ```smarty
<html> <html>
<head> <head>
<title>Cytro</title> <title>Fenom</title>
</head> </head>
<body> <body>
{if $templaters.cytro?} {if $templaters.fenom?}
{var $tpl = $templaters.cytro} {var $tpl = $templaters.fenom}
<div>Name: {$tpl.name}</div> <div>Name: {$tpl.name}</div>
<div>Description: {$tpl.name|truncate:80}</div> <div>Description: {$tpl.name|truncate:80}</div>
<ul> <ul>
@ -41,25 +41,25 @@ Display template
```php ```php
<?php <?php
$cytro = Cytro::factory('./templates', './compiled', Cytro::CHECK_MTIME); $fenom = Fenom::factory('./templates', './compiled', Fenom::AUTO_RELOAD);
$cytro->display("pages/about.tpl", $data); $fenom->display("pages/about.tpl", $data);
``` ```
Get content Get content
```php ```php
<?php <?php
$cytro = Cytro::factory('./templates', './compiled', Cytro::CHECK_MTIME); $fenom = Fenom::factory('./templates', './compiled', Fenom::AUTO_RELOAD);
$content = $cytro->fetch("pages/about.tpl", $data); $content = $fenom->fetch("pages/about.tpl", $data);
``` ```
Runtime compilation Runtime compilation
```php ```php
<?php <?php
$cytro = new Cytro(); $fenom = new Fenom();
$tempate = $cytro->compileCode('Hello {$user.name}! {if $user.email?} Your email: {$user.email} {/if}'); $template = $fenom->compileCode('Hello {$user.name}! {if $user.email?} Your email: {$user.email} {/if}');
$tempate->display($data); $template->display($data);
// or // or
$content = $tempate->fetch($data); $content = $template->fetch($data);
``` ```

View File

@ -2,7 +2,7 @@
require_once __DIR__.'/scripts/bootstrap.php'; require_once __DIR__.'/scripts/bootstrap.php';
exec("rm -rf ".__DIR__."/compile/*"); exec("rm -rf ".__DIR__."/compile/*");
echo "Smarty3 vs Twig vs Cytro\n\n"; echo "Smarty3 vs Twig vs Fenom\n\n";
echo "Generate templates... "; echo "Generate templates... ";
passthru("php ".__DIR__."/templates/inheritance/smarty.gen.php"); passthru("php ".__DIR__."/templates/inheritance/smarty.gen.php");
@ -13,34 +13,34 @@ echo "Testing a lot output...\n";
Benchmark::runs("smarty3", 'echo/smarty.tpl', __DIR__.'/templates/echo/data.json'); Benchmark::runs("smarty3", 'echo/smarty.tpl', __DIR__.'/templates/echo/data.json');
Benchmark::runs("twig", 'echo/twig.tpl', __DIR__.'/templates/echo/data.json'); Benchmark::runs("twig", 'echo/twig.tpl', __DIR__.'/templates/echo/data.json');
Benchmark::runs("cytro", 'echo/smarty.tpl', __DIR__.'/templates/echo/data.json'); Benchmark::runs("fenom", 'echo/smarty.tpl', __DIR__.'/templates/echo/data.json');
//if(extension_loaded("phalcon")) { if(extension_loaded("phalcon")) {
// Benchmark::runs("volt", 'echo/twig.tpl', __DIR__.'/templates/echo/data.json'); Benchmark::runs("volt", 'echo/twig.tpl', __DIR__.'/templates/echo/data.json');
//} }
echo "\nTesting 'foreach' of big array...\n"; echo "\nTesting 'foreach' of big array...\n";
Benchmark::runs("smarty3", 'foreach/smarty.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("smarty3", 'foreach/smarty.tpl', __DIR__.'/templates/foreach/data.json');
Benchmark::runs("twig", 'foreach/twig.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("twig", 'foreach/twig.tpl', __DIR__.'/templates/foreach/data.json');
Benchmark::runs("cytro", 'foreach/smarty.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("fenom", 'foreach/smarty.tpl', __DIR__.'/templates/foreach/data.json');
//if(extension_loaded("phalcon")) { if(extension_loaded("phalcon")) {
// Benchmark::runs("volt", 'foreach/twig.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("volt", 'foreach/twig.tpl', __DIR__.'/templates/foreach/data.json');
//} }
echo "\nTesting deep 'inheritance'...\n"; echo "\nTesting deep 'inheritance'...\n";
Benchmark::runs("smarty3", 'inheritance/smarty/b100.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("smarty3", 'inheritance/smarty/b100.tpl', __DIR__.'/templates/foreach/data.json');
Benchmark::runs("twig", 'inheritance/twig/b100.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("twig", 'inheritance/twig/b100.tpl', __DIR__.'/templates/foreach/data.json');
Benchmark::runs("cytro", 'inheritance/smarty/b100.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("fenom", 'inheritance/smarty/b100.tpl', __DIR__.'/templates/foreach/data.json');
//if(extension_loaded("phalcon")) { if(extension_loaded("phalcon")) {
// Benchmark::runs("volt", 'inheritance/twig/b100.tpl', __DIR__.'/templates/foreach/data.json'); Benchmark::runs("volt", 'inheritance/twig/b100.tpl', __DIR__.'/templates/foreach/data.json');
//} }
echo "\nDone. Cleanup.\n"; echo "\nDone. Cleanup.\n";
//passthru("rm -rf ".__DIR__."/compile/*"); //passthru("rm -rf ".__DIR__."/compile/*");
passthru("rm -f ".__DIR__."/templates/inheritance/smarty/*"); passthru("rm -f ".__DIR__."/templates/inheritance/smarty/*");
passthru("rm -f ".__DIR__."/templates/inheritance/twig/*"); passthru("rm -f ".__DIR__."/templates/inheritance/twig/*");
echo "\nSmarty3 vs Cytro (more details)\n\n"; echo "\nSmarty3 vs Fenom (more details)\n\n";
echo "Coming soon\n"; echo "Coming soon\n";

View File

@ -43,15 +43,15 @@ class Benchmark {
printf(self::$t, __FUNCTION__, $message, round(microtime(true)-$start, 4), round(memory_get_peak_usage()/1024/1024, 2)); printf(self::$t, __FUNCTION__, $message, round(microtime(true)-$start, 4), round(memory_get_peak_usage()/1024/1024, 2));
} }
public static function cytro($tpl, $data, $double, $message) { public static function fenom($tpl, $data, $double, $message) {
$cytro = Cytro::factory(__DIR__.'/../templates', __DIR__."/../compile"); $fenom = Fenom::factory(__DIR__.'/../templates', __DIR__."/../compile");
if($double) { if($double) {
$cytro->fetch($tpl, $data); $fenom->fetch($tpl, $data);
} }
$_SERVER["t"] = $start = microtime(true); $_SERVER["t"] = $start = microtime(true);
$cytro->fetch($tpl, $data); $fenom->fetch($tpl, $data);
printf(self::$t, __FUNCTION__, $message, round(microtime(true)-$start, 4), round(memory_get_peak_usage()/1024/1024, 2)); printf(self::$t, __FUNCTION__, $message, round(microtime(true)-$start, 4), round(memory_get_peak_usage()/1024/1024, 2));
} }

View File

@ -1,65 +0,0 @@
<?php
//$data = json_decode(file_get_contents(__DIR__.'/echo/data.json'), true);
require_once __DIR__.'/../scripts/bootstrap.php';
exec("rm -rf ".__DIR__."/../compile/*");
echo "A lot outputs...\n";
Benchmark::run("smarty3", 'echo/smarty.tpl', __DIR__.'/echo/data.json', false, '!compiled and !loaded');
Benchmark::run("smarty3", 'echo/smarty.tpl', __DIR__.'/echo/data.json', false, 'compiled and !loaded');
Benchmark::run("smarty3", 'echo/smarty.tpl', __DIR__.'/echo/data.json', true, 'compiled and loaded');
Benchmark::run("twig", 'echo/twig.tpl', __DIR__.'/echo/data.json', false, '!compiled and !loaded');
Benchmark::run("twig", 'echo/twig.tpl', __DIR__.'/echo/data.json', false, 'compiled and !loaded');
Benchmark::run("twig", 'echo/twig.tpl', __DIR__.'/echo/data.json', true, 'compiled and loaded');
Benchmark::run("cytro", 'echo/smarty.tpl', __DIR__.'/echo/data.json', false, '!compiled and !loaded');
Benchmark::run("cytro", 'echo/smarty.tpl', __DIR__.'/echo/data.json', false, 'compiled and !loaded');
Benchmark::run("cytro", 'echo/smarty.tpl', __DIR__.'/echo/data.json', true, 'compiled and loaded');
exit;
require(__DIR__.'/../../vendor/autoload.php');
$smarty = new Smarty();
$smarty->compile_check = false;
$smarty->setTemplateDir(__DIR__);
$smarty->setCompileDir(__DIR__."/../compile/");
$start = microtime(true);
$smarty->assign($data);
$smarty->fetch('echo/smarty.tpl');
var_dump("Smarty3: ".(microtime(true)-$start));
$start = microtime(true);
$smarty->assign($data);
$smarty->fetch('echo/smarty.tpl');
var_dump("Smarty3 cached: ".(microtime(true)-$start));
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(__DIR__);
$twig = new Twig_Environment($loader, array(
'cache' => __DIR__."/../compile/",
'autoescape' => false,
'auto_reload' => false,
));
$start = microtime(true);
$template = $twig->loadTemplate('echo/twig.tpl');
$template->render($data);
var_dump("Twig: ".(microtime(true)-$start));
$start = microtime(true);
$template = $twig->loadTemplate('echo/twig.tpl');
$template->render($data);
var_dump("Twig cached: ".(microtime(true)-$start));
$cytro = Cytro::factory(__DIR__, __DIR__."/../compile/", Cytro::AUTO_RELOAD);
$start = microtime(true);
$template = $cytro->fetch('echo/smarty.tpl', $data);
var_dump("Cytro: ".(microtime(true)-$start));
$start = microtime(true);
$template = $cytro->fetch('echo/smarty.tpl', $data);
var_dump("Cytro cached: ".(microtime(true)-$start));

View File

@ -1,50 +0,0 @@
<?php
$data = json_decode(file_get_contents(__DIR__.'/foreach/data.json'), true);
exec("rm -rf ".__DIR__."/../compile/*");
require(__DIR__.'/../../vendor/autoload.php');
$smarty = new Smarty();
$smarty->compile_check = true;
$smarty->setTemplateDir(__DIR__);
$smarty->setCompileDir(__DIR__."/../compile/");
$start = microtime(true);
$smarty->assign($data);
$smarty->fetch('foreach/smarty.tpl');
var_dump("Smarty3: ".(microtime(true)-$start));
$start = microtime(true);
$smarty->assign($data);
$smarty->fetch('foreach/smarty.tpl');
var_dump("Smarty3 cached: ".(microtime(true)-$start));
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(__DIR__);
$twig = new Twig_Environment($loader, array(
'cache' => __DIR__."/../compile/",
'autoescape' => false,
'auto_reload' => false,
));
$start = microtime(true);
$template = $twig->loadTemplate('foreach/twig.tpl');
$template->render($data);
var_dump("Twig: ".(microtime(true)-$start));
$start = microtime(true);
$template = $twig->loadTemplate('foreach/twig.tpl');
$template->render($data);
var_dump("Twig cached: ".(microtime(true)-$start));
$cytro = Cytro::factory(__DIR__, __DIR__."/../compile/", Cytro::AUTO_RELOAD);
$start = microtime(true);
$template = $cytro->fetch('foreach/smarty.tpl', $data);
var_dump("Cytro: ".(microtime(true)-$start));
$start = microtime(true);
$template = $cytro->fetch('foreach/smarty.tpl', $data);
var_dump("Cytro cached: ".(microtime(true)-$start));

View File

@ -1,61 +0,0 @@
<?php
$data = array(
"inh" => 'inheritance',
"var1" => 'val1'
);
function trace() {
$e = new Exception();
echo $e->getTraceAsString();
ob_flush();
exit(0);
}
exec("rm -rf ".__DIR__."/../compile/*");
require(__DIR__.'/../../vendor/autoload.php');
$smarty = new Smarty();
$smarty->compile_check = true;
$smarty->setTemplateDir(__DIR__);
$smarty->setCompileDir(__DIR__."/../compile/");
$start = microtime(true);
$smarty->assign($data);
$smarty->fetch('inheritance/smarty/b100.tpl');
var_dump("Smarty3: ".(microtime(true)-$start));
$start = microtime(true);
$smarty->assign($data);
$smarty->fetch('inheritance/smarty/b100.tpl');
var_dump("Smarty3 cached: ".(microtime(true)-$start));
Twig_Autoloader::register();
$loader = new Twig_Loader_Filesystem(__DIR__);
$twig = new Twig_Environment($loader, array(
'cache' => __DIR__."/../compile/",
'autoescape' => false,
'auto_reload' => false,
));
$start = microtime(true);
$template = $twig->loadTemplate('inheritance/twig/b100.tpl');
$template->render($data);
var_dump("Twig: ".(microtime(true)-$start));
$start = microtime(true);
$template = $twig->loadTemplate('inheritance/twig/b100.tpl');
$template->render($data);
var_dump("Twig cached: ".(microtime(true)-$start));
$cytro = Cytro::factory(__DIR__, __DIR__."/../compile/", Cytro::AUTO_RELOAD);
$start = microtime(true);
$template = $cytro->fetch('inheritance/smarty/b100.tpl', $data);
var_dump("Cytro: ".(microtime(true)-$start));
$start = microtime(true);
$template = $cytro->fetch('inheritance/smarty/b100.tpl', $data);
var_dump("Cytro cached: ".(microtime(true)-$start));

View File

@ -1,9 +1,9 @@
{ {
"name": "bzick/cytro", "name": "bzick/fenom",
"type": "library", "type": "library",
"description": "Cytro - fast template engine for PHP", "description": "Fenom - fast template engine for PHP",
"homepage": "http://bzick.github.io/cytro/", "homepage": "http://bzick.github.io/fenom/",
"keywords": ["cytro", "template", "templating"], "keywords": ["fenom", "template", "templating"],
"license": "BSD-3", "license": "BSD-3",
"authors": [ "authors": [
{ {
@ -22,7 +22,7 @@
"twig/twig": "1.*" "twig/twig": "1.*"
}, },
"autoload": { "autoload": {
"psr-0": { "Cytro\\": "src/" }, "psr-0": { "Fenom\\": "src/" },
"classmap": [ "src/Cytro.php" ] "classmap": [ "src/Fenom.php" ]
} }
} }

View File

@ -1,9 +1,9 @@
About Cytro [RU] About Fenom [RU]
================ ================
Cytro - самый быстрый, гибкий и тонкий шаблонизатор для PHP, унаследовавший синтаксис от Smarty3 и улучшив его. Fenom - самый быстрый, гибкий и тонкий шаблонизатор для PHP, унаследовавший синтаксис от Smarty3 и улучшив его.
Пожалуй это единственный шаблонизатор, который не использет ни регулярные выражения, как Twig, ни лексер от BISON, как Smarty3. Пожалуй это единственный шаблонизатор, который не использет ни регулярные выражения, как Twig, ни лексер от BISON, как Smarty3.
Вы не найдёте ни одного регулярного выражения в ядре Cytro, но тем не менее ядро простое, компактное и очень быстрое. Вы не найдёте ни одного регулярного выражения в ядре Fenom, но тем не менее ядро простое, компактное и очень быстрое.
* Скорость. Разбор шаблонов постоен на основе нативного [токенайзера](http://docs.php.net/tokenizer). Шаблон преобразуется в исполняемый PHP код, * Скорость. Разбор шаблонов постоен на основе нативного [токенайзера](http://docs.php.net/tokenizer). Шаблон преобразуется в исполняемый PHP код,
который может быть закеширован на файловой системе. который может быть закеширован на файловой системе.

View File

@ -3,7 +3,7 @@ Benchmark
To start benchmark run script `benchmark/run.php`. To start benchmark run script `benchmark/run.php`.
### Smarty3 vs Twig vs Cytro ### Smarty3 vs Twig vs Fenom
PHP 5.4.11 PHP 5.4.11
@ -17,9 +17,9 @@ PHP 5.4.11
twig: compiled and !loaded 0.0337 sec, 16.1 MiB twig: compiled and !loaded 0.0337 sec, 16.1 MiB
twig: compiled and loaded 0.0027 sec, 16.1 MiB twig: compiled and loaded 0.0027 sec, 16.1 MiB
cytro: !compiled and !loaded 1.0142 sec, 8.8 MiB fenom: !compiled and !loaded 1.0142 sec, 8.8 MiB
cytro: compiled and !loaded 0.0167 sec, 6.1 MiB fenom: compiled and !loaded 0.0167 sec, 6.1 MiB
cytro: compiled and loaded 0.0024 sec, 6.1 MiB fenom: compiled and loaded 0.0024 sec, 6.1 MiB
Iterating of array ({foreach}) Iterating of array ({foreach})
@ -31,9 +31,9 @@ PHP 5.4.11
twig: compiled and !loaded 0.0605 sec, 2.9 MiB twig: compiled and !loaded 0.0605 sec, 2.9 MiB
twig: compiled and loaded 0.0550 sec, 2.9 MiB twig: compiled and loaded 0.0550 sec, 2.9 MiB
cytro: !compiled and !loaded 0.0093 sec, 3.0 MiB fenom: !compiled and !loaded 0.0093 sec, 3.0 MiB
cytro: compiled and !loaded 0.0033 sec, 2.4 MiB fenom: compiled and !loaded 0.0033 sec, 2.4 MiB
cytro: compiled and loaded 0.0027 sec, 2.4 MiB fenom: compiled and loaded 0.0027 sec, 2.4 MiB
Inheriting of templates ({extends}) Inheriting of templates ({extends})
@ -45,9 +45,9 @@ PHP 5.4.11
twig: compiled and !loaded 0.0255 sec, 6.3 MiB twig: compiled and !loaded 0.0255 sec, 6.3 MiB
twig: compiled and loaded 0.0038 sec, 6.3 MiB twig: compiled and loaded 0.0038 sec, 6.3 MiB
cytro: !compiled and !loaded 0.1222 sec, 3.9 MiB fenom: !compiled and !loaded 0.1222 sec, 3.9 MiB
cytro: compiled and !loaded 0.0004 sec, 2.4 MiB fenom: compiled and !loaded 0.0004 sec, 2.4 MiB
cytro: compiled and loaded 0.0000 sec, 2.4 MiB fenom: compiled and loaded 0.0000 sec, 2.4 MiB
* **!compiled and !loaded** - template engine object created but parsers not initialized and templates not compiled * **!compiled and !loaded** - template engine object created but parsers not initialized and templates not compiled
* **compiled and !loaded** - template engine object created, template compiled but not loaded * **compiled and !loaded** - template engine object created, template compiled but not loaded
@ -59,4 +59,4 @@ PHP 5.4.11
| --------------- | ------:| --------:| ------:| | --------------- | ------:| --------:| ------:|
| Smarty3 (3.1.13)| 320 | 190 | 55095 | | Smarty3 (3.1.13)| 320 | 190 | 55095 |
| Twig (1.13.0) | 162 | 131 | 13908 | | Twig (1.13.0) | 162 | 131 | 13908 |
| Cytro (1.0.1) | 9 | 16 | 3899 | | Fenom (1.0.1) | 9 | 16 | 3899 |

View File

@ -31,19 +31,3 @@ Variant #2. Сloudy.
Variant #3. Rain. Variant #3. Rain.
Variant #4. Tornado. Variant #4. Tornado.
Error Info (x2) :
Exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '839621621,839622021)' at line 1
Query: SELECT `image_id`, `filename` FROM `s3_image_version` WHERE `format_id`=1 AND `image_id` IN (,839621621,839622021)
#0 /www/oml.ru/s3/lib/class.db.php(480): Db::parseError('SELECT `image_i...')
#1 /www/oml.ru/s3/forms/class.shop2.product.form.php(225): Db::query('SELECT `image_i...')
#2 /www/oml.ru/s3/lib/class.form.php(2390): Shop2ProductForm->fillControls()
#3 /www/oml.ru/s3/lib/class.form.php(1444): Form->execute()
#4 /www/oml.ru/public/my/s3/data/shop2_product/edit.cphp(44): Form->display(Object(Smarty), 'form.ajax.tpl')
#5 {main}
Place: /www/oml.ru/s3/lib/class.db.php:607
Time: 2013-06-05 03:54:51
Url: http://agyumama.ru/my/s3/data/shop2_product/edit.cphp?shop_id=196421&ver_id=636664&access=u%3B270377&popup=1&product_id=89445221&rnd=9296&xhr=1

View File

@ -3,7 +3,7 @@
``` ```
$cytro->addModifier(string $modifier, callable $callback); $fenom->addModifier(string $modifier, callable $callback);
``` ```
* `$modifier` - название модификатора, которое будет использоваться в шаблоне * `$modifier` - название модификатора, которое будет использоваться в шаблоне
@ -16,7 +16,7 @@ For example:
``` ```
```php ```php
$cytro->addModifier('my_modifier', function ($variable, $param1, $param2) { $fenom->addModifier('my_modifier', function ($variable, $param1, $param2) {
// ... // ...
}); });
``` ```

View File

@ -1,3 +1,9 @@
Parsing templates Parsing templates [RU]
================= ======================
### Tokenizer
Объект Tokenizer содержит список готовых к обработке токенов и необходимые для фильтрации токенов методы. Помимо основнях констант расширения Tokenizer у объекта есть макросы, объединения, определенных токенов.
### Parsers

View File

@ -1,3 +1,8 @@
Add template provider Add template provider [RU]
===================== =====================
Источники шаблонов позволяют хранить шаблоны не только на файловой системе, а там где вам удобдно будет. Что бы указать откуда нужно взять шаблон используется схема в имени шаблона `db:page/about.tpl`, шаблон будет взят из источника `db`. Источник шаблонов добавляется через метод `addProvider`, при добавлении необходимо указать схему по которой можно запросить шаблон из этого источника:
```php
$fenom->addProvider("db", $db_provider);
```

View File

@ -11,15 +11,15 @@ Tags [RU]
Примитивное добавление функции можно осуществить следующим образом: Примитивное добавление функции можно осуществить следующим образом:
```php ```php
$cytro->addFunction(string $function_name, callable $callback[, callable $parser]); $fenom->addFunction(string $function_name, callable $callback[, callable $parser]);
``` ```
В данном случае запускается стандартный парсер, который автоматически разберет аргументы тега, которые должны быть в формате HTML аттрибутов и отдаст их в функцию ассоциативным массивом. В данном случае запускается стандартный парсер, который автоматически разберет аргументы тега, которые должны быть в формате HTML аттрибутов и отдаст их в функцию ассоциативным массивом.
В данном случае вы можете переопределить парсер на произвольный в формате `function (Cytro\Tokenizer $tokenizer, Cytro\Template $template)` В данном случае вы можете переопределить парсер на произвольный в формате `function (Fenom\Tokenizer $tokenizer, Fenom\Template $template)`
Существует более совершенный способ добавления функции: Существует более совершенный способ добавления функции:
```php ```php
$cytro->addFunctionSmarty(string $function_name, callable $callback); $fenom->addFunctionSmarty(string $function_name, callable $callback);
``` ```
В данном случае парсер просканирует список аргументов коллбека и попробует сопоставить с аргументами из тега. Таким образом вы успешно можете добавлять Ваши штатные функции. В данном случае парсер просканирует список аргументов коллбека и попробует сопоставить с аргументами из тега. Таким образом вы успешно можете добавлять Ваши штатные функции.
@ -29,7 +29,7 @@ $cytro->addFunctionSmarty(string $function_name, callable $callback);
Добавление блоковой функции аналогичен добавлению строковой за исключением того что есть возможность указать парсер для закрывающего тега. Добавление блоковой функции аналогичен добавлению строковой за исключением того что есть возможность указать парсер для закрывающего тега.
```php ```php
$cytro->addBlockFunction(string $function_name, callable $callback[, callable $parser_open[, callable $parser_close]]); $fenom->addBlockFunction(string $function_name, callable $callback[, callable $parser_open[, callable $parser_close]]);
``` ```
Сам коллбек принимает первым аргументом контент между открывающим и закрывающим тегом, а вторым аргументом - ассоциативный массив из аргуметов тега. Сам коллбек принимает первым аргументом контент между открывающим и закрывающим тегом, а вторым аргументом - ассоциативный массив из аргуметов тега.
@ -39,14 +39,14 @@ $cytro->addBlockFunction(string $function_name, callable $callback[, callable $p
Добавление строчного компилятора осуществляеться очень просто: Добавление строчного компилятора осуществляеться очень просто:
```php ```php
$cytro->addCompiler(string $compiler, callable $parser); $fenom->addCompiler(string $compiler, callable $parser);
``` ```
Парсер должен принимать `Cytro\Tokenizer $tokenizer`, `Cytro\Template $template` и возвращать PHP код. Парсер должен принимать `Fenom\Tokenizer $tokenizer`, `Fenom\Template $template` и возвращать PHP код.
Компилятор так же можно импортировать из класса автоматически Компилятор так же можно импортировать из класса автоматически
```php ```php
$cytro->addCompilerSmart(string $compiler, $storage); $fenom->addCompilerSmart(string $compiler, $storage);
``` ```
`$storage` может быть как классом так и объектом. В данном случае шаблонизатор будет искать метод `tag{$compiler}`, который будет взят в качестве парсера тега. `$storage` может быть как классом так и объектом. В данном случае шаблонизатор будет искать метод `tag{$compiler}`, который будет взят в качестве парсера тега.
@ -56,13 +56,13 @@ $cytro->addCompilerSmart(string $compiler, $storage);
Добавление блочного компилятора осуществяется двум способами. Первый Добавление блочного компилятора осуществяется двум способами. Первый
```php ```php
$cytro->addBlockCompiler(string $compiler, array $parsers, array $tags); $fenom->addBlockCompiler(string $compiler, array $parsers, array $tags);
``` ```
где `$parser` ассоциативный массив `["open" => parser, "close" => parser]`, сождержащий парсер на открывающий и на закрывающий тег, а `$tags` содержит список внутренних тегов в формате `["tag_name"] => parser`, которые могут быть использованы только с этим компилятором. где `$parser` ассоциативный массив `["open" => parser, "close" => parser]`, сождержащий парсер на открывающий и на закрывающий тег, а `$tags` содержит список внутренних тегов в формате `["tag_name"] => parser`, которые могут быть использованы только с этим компилятором.
Второй способ добавления парсера через импортирование из класса или объекта методов: Второй способ добавления парсера через импортирование из класса или объекта методов:
```php ```php
$cytro->addBlockCompilerSmart(string $compiler, $storage, array $tags, array $floats); $fenom->addBlockCompilerSmart(string $compiler, $storage, array $tags, array $floats);
``` ```

View File

@ -5,11 +5,11 @@ For installation use [composer](http://getcompoer.org). Add in your `composer.js
```json ```json
{ {
"require": { "require": {
"bzick/cytro": "dev-master" "bzick/fenom": "dev-master"
} }
} }
``` ```
or use shell or use shell
`composer require bzick/cytro` `composer require bzick/fenom`
If you do not use composer - use `psr-0` format for loading Cytro's classes. If you do not use composer - use `psr-0` format for loading Fenom's classes.

View File

@ -1,10 +1,10 @@
Documentation Documentation
============= =============
### Cytro ### Fenom
* [About](./about.md)
* [Install](./install.md) * [Install](./install.md)
* [Usage](./usage.md)
* [Syntax](./syntax.md) * [Syntax](./syntax.md)
* [Settings](./settings.md) * [Settings](./settings.md)
* [Callbacks and filters](./callbacks.md) * [Callbacks and filters](./callbacks.md)
@ -47,7 +47,6 @@ Documentation
* [filter](./tags/filter.md) * [filter](./tags/filter.md)
* [ignore](./tags/ignore.md) * [ignore](./tags/ignore.md)
* [macro](./tags/macro.md) and `import` * [macro](./tags/macro.md) and `import`
* [autotrim](./tags/autotrim.md)
* or [add](./ext/tags.md) your own * or [add](./ext/tags.md) your own
*** ***

View File

@ -6,31 +6,31 @@ Settings [RU]
Что бы установить папку для хранения кеша собранных шаблонов Что бы установить папку для хранения кеша собранных шаблонов
```php ```php
$cytro->setCompileDir($dir); $fenom->setCompileDir($dir);
``` ```
### Template settings ### Template settings
```php ```php
// set options using factory // set options using factory
$cytro = Cytro::factory($tpl_dir, $compile_dir, $options); $fenom = Fenom::factory($tpl_dir, $compile_dir, $options);
// or inline using method setOptions // or inline using method setOptions
$cytro->setOptions($options); $fenom->setOptions($options);
``` ```
Параметры могут быть массивом `'option_name' => true` (если ключ не указан автоматически задаётся false) или битовой маской. Параметры могут быть массивом `'option_name' => true` (если ключ не указан автоматически задаётся false) или битовой маской.
* **disable_methods**, `Cytro::DENY_METHODS`, запретить вызов методов у объектов * **disable_methods**, `Fenom::DENY_METHODS`, запретить вызов методов у объектов
* **disable_native_funcs**, `Cytro::DENY_INLINE_FUNCS`, запретить использование PHP функций, кроме разрешенных * **disable_native_funcs**, `Fenom::DENY_INLINE_FUNCS`, запретить использование PHP функций, кроме разрешенных
* **auto_reload**, `Cytro::AUTO_RELOAD`, пересобирать шаблон если его оригинал был изменён (замедляет работу шаблонизатора). * **auto_reload**, `Fenom::AUTO_RELOAD`, пересобирать шаблон если его оригинал был изменён (замедляет работу шаблонизатора).
* **force_compile**, `Cytro::FORCE_COMPILE`, пересобирать шаблон при каждом вызове (сильно замедляет работу шаблонизатора). * **force_compile**, `Fenom::FORCE_COMPILE`, пересобирать шаблон при каждом вызове (сильно замедляет работу шаблонизатора).
* **force_include**, `Cytro::FORCE_INCLUDE`, оптимизировать вставку шаблона в шаблон. Это увеличит производительность и размер собранного шаблона. * **force_include**, `Fenom::FORCE_INCLUDE`, оптимизировать вставку шаблона в шаблон. Это увеличит производительность и размер собранного шаблона.
```php ```php
$cytro->setOptions(array( $fenom->setOptions(array(
"compile_check" => true, "compile_check" => true,
"force_include" => true "force_include" => true
)); ));
// same // same
$cytro->setOptions(Cytro::AUTO_RELOAD | Cytro::FORCE_INCLUDE); $fenom->setOptions(Fenom::AUTO_RELOAD | Fenom::FORCE_INCLUDE);
``` ```

View File

@ -1,7 +1,7 @@
Syntax [RU] Syntax [RU]
=========== ===========
Cytro have [Smarty](http://www.smarty.net/) like syntax. Fenom have [Smarty](http://www.smarty.net/) like syntax.
## Variable ## Variable
@ -198,11 +198,11 @@ but if use single quote any template expressions will be on display as it is
### Ignoring temaplate code ### Ignoring temaplate code
В шаблонизаторе Cytro используются фигурные скобки для отделения HTML от кода Cytro. В шаблонизаторе Fenom используются фигурные скобки для отделения HTML от кода Fenom.
Если требуется вывести текст, содержащий фигурные скобки, помните о следующих возможностях: Если требуется вывести текст, содержащий фигурные скобки, помните о следующих возможностях:
1. Использование блочного тега `{ignore}{/ignore}`. Текст внутри этого тега текст не компилируется шаблонизатором и выводится как есть. 1. Использование блочного тега `{ignore}{/ignore}`. Текст внутри этого тега текст не компилируется шаблонизатором и выводится как есть.
2. Если после открывающей фигурной скобки есть пробельный символ (пробел или `\t`) или перенос строки (`\r` или `\n`), то она не воспринимается как разделитель кода Cytro и код после неё выводится как есть. 2. Если после открывающей фигурной скобки есть пробельный символ (пробел или `\t`) или перенос строки (`\r` или `\n`), то она не воспринимается как разделитель кода Fenom и код после неё выводится как есть.
Пример: Пример:

View File

@ -79,7 +79,7 @@ Tag {foreach} [RU]
{/foreach} {/foreach}
``` ```
В блоке `{foreachelse}...{/foreach}` использование `{break}`, `{continue}` выбросит исключение `Cytro\CompileException` при компиляции В блоке `{foreachelse}...{/foreach}` использование `{break}`, `{continue}` выбросит исключение `Fenom\CompileException` при компиляции
### Notice ### Notice

20
docs/usage.md Normal file
View File

@ -0,0 +1,20 @@
Basic usage
===========
### Creating template engine
```php
$fenom = Fenom::factory('/path/to/templates', '/path/to/template/cache', $options);
//or
$fenom = new Fenom(new FSProvider('/path/to/templates'));
$fenom->setCompileDir('/path/to/template/cache');
$fenom->setOptions($options);
```
### Output template result
```php
$fenom->display("template/name.tpl", $vars);
```

View File

@ -1,20 +1,20 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
use Cytro\Tokenizer; use Fenom\Tokenizer;
use Cytro\Template; use Fenom\Template;
use Cytro\Scope; use Fenom\Scope;
/** /**
* Compilers collection * Compilers collection
* @package Cytro * @package Fenom
*/ */
class Compiler { class Compiler {
/** /**
@ -30,7 +30,7 @@ class Compiler {
$cname = $tpl->parsePlainArg($tokens, $name); $cname = $tpl->parsePlainArg($tokens, $name);
$p = $tpl->parseParams($tokens); $p = $tpl->parseParams($tokens);
if($p) { // if we have additionally variables if($p) { // if we have additionally variables
if($name && ($tpl->getStorage()->getOptions() & \Cytro::FORCE_INCLUDE)) { // if FORCE_INCLUDE enabled and template name known if($name && ($tpl->getStorage()->getOptions() & \Fenom::FORCE_INCLUDE)) { // if FORCE_INCLUDE enabled and template name known
$inc = $tpl->getStorage()->compile($name, false); $inc = $tpl->getStorage()->compile($name, false);
$tpl->addDepend($inc); $tpl->addDepend($inc);
return '$_tpl = (array)$tpl; $tpl->exchangeArray('.self::toArray($p).'+$_tpl); ?>'.$inc->_body.'<?php $tpl->exchangeArray($_tpl); unset($_tpl);'; return '$_tpl = (array)$tpl; $tpl->exchangeArray('.self::toArray($p).'+$_tpl); ?>'.$inc->_body.'<?php $tpl->exchangeArray($_tpl); unset($_tpl);';
@ -38,7 +38,7 @@ class Compiler {
return '$tpl->getStorage()->getTemplate('.$cname.')->display('.self::toArray($p).'+(array)$tpl);'; return '$tpl->getStorage()->getTemplate('.$cname.')->display('.self::toArray($p).'+(array)$tpl);';
} }
} else { } else {
if($name && ($tpl->getStorage()->getOptions() & \Cytro::FORCE_INCLUDE)) { // if FORCE_INCLUDE enabled and template name known if($name && ($tpl->getStorage()->getOptions() & \Fenom::FORCE_INCLUDE)) { // if FORCE_INCLUDE enabled and template name known
$inc = $tpl->getStorage()->compile($name, false); $inc = $tpl->getStorage()->compile($name, false);
$tpl->addDepend($inc); $tpl->addDepend($inc);
return '$_tpl = (array)$tpl; ?>'.$inc->_body.'<?php $tpl->exchangeArray($_tpl); unset($_tpl);'; return '$_tpl = (array)$tpl; ?>'.$inc->_body.'<?php $tpl->exchangeArray($_tpl); unset($_tpl);';
@ -399,7 +399,7 @@ class Compiler {
$tpl->_compatible = true; $tpl->_compatible = true;
} }
$tpl->_extends = $tpl_name; $tpl->_extends = $tpl_name;
return '$parent = $tpl->getStorage()->getTemplate('.$tpl_name.', \Cytro\Template::EXTENDED);'; return '$parent = $tpl->getStorage()->getTemplate('.$tpl_name.', \Fenom\Template::EXTENDED);';
} }
} }
@ -416,7 +416,7 @@ class Compiler {
while(isset($t->_extends)) { while(isset($t->_extends)) {
$t = $t->_extends; $t = $t->_extends;
if(is_object($t)) { if(is_object($t)) {
/* @var \Cytro\Template $t */ /* @var \Fenom\Template $t */
$t->_extended = true; $t->_extended = true;
$tpl->addDepend($t); $tpl->addDepend($t);
$t->_compatible = &$tpl->_compatible; $t->_compatible = &$tpl->_compatible;
@ -470,7 +470,7 @@ class Compiler {
return '?>'.$donor->getBody().'<?php '; return '?>'.$donor->getBody().'<?php ';
} else { } else {
$tpl->_compatible = true; $tpl->_compatible = true;
return '$donor = $tpl->getStorage()->getTemplate('.$cname.', \Cytro\Template::EXTENDED);'.PHP_EOL. return '$donor = $tpl->getStorage()->getTemplate('.$cname.', \Fenom\Template::EXTENDED);'.PHP_EOL.
'$donor->fetch((array)$tpl);'.PHP_EOL. '$donor->fetch((array)$tpl);'.PHP_EOL.
'$tpl->b += (array)$donor->b'; '$tpl->b += (array)$donor->b';
// throw new ImproperUseException('template name must be given explicitly'); // throw new ImproperUseException('template name must be given explicitly');

View File

@ -1,13 +1,13 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
/** /**
* Collection of modifiers * Collection of modifiers

View File

@ -1,20 +1,20 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
use Cytro\ProviderInterface; use Fenom\ProviderInterface;
/** /**
* Templates provider * Templates provider
* @author Ivan Shalganov * @author Ivan Shalganov
*/ */
class FSProvider implements ProviderInterface { class Provider implements ProviderInterface {
private $_path; private $_path;
/** /**

View File

@ -1,13 +1,13 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
interface ProviderInterface { interface ProviderInterface {
/** /**

View File

@ -1,14 +1,14 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
use Cytro; use Fenom;
/** /**
* Primitive template * Primitive template
@ -41,9 +41,9 @@ class Render extends \ArrayObject {
*/ */
protected $_base_name = 'runtime'; protected $_base_name = 'runtime';
/** /**
* @var Cytro * @var Fenom
*/ */
protected $_cytro; protected $_fenom;
/** /**
* Timestamp of compilation * Timestamp of compilation
* @var float * @var float
@ -56,7 +56,7 @@ class Render extends \ArrayObject {
protected $_depends = array(); protected $_depends = array();
/** /**
* @var int tempalte options (see Cytro options) * @var int tempalte options (see Fenom options)
*/ */
protected $_options = 0; protected $_options = 0;
@ -67,15 +67,15 @@ class Render extends \ArrayObject {
protected $_provider; protected $_provider;
/** /**
* @param Cytro $cytro * @param Fenom $fenom
* @param callable $code template body * @param callable $code template body
* @param array $props * @param array $props
*/ */
public function __construct(Cytro $cytro, \Closure $code, $props = array()) { public function __construct(Fenom $fenom, \Closure $code, $props = array()) {
$this->_cytro = $cytro; $this->_fenom = $fenom;
$props += self::$_props; $props += self::$_props;
$this->_name = $props["name"]; $this->_name = $props["name"];
$this->_provider = $this->_cytro->getProvider($props["scm"]); $this->_provider = $this->_fenom->getProvider($props["scm"]);
$this->_scm = $props["scm"]; $this->_scm = $props["scm"];
$this->_time = $props["time"]; $this->_time = $props["time"];
$this->_depends = $props["depends"]; $this->_depends = $props["depends"];
@ -84,10 +84,10 @@ class Render extends \ArrayObject {
/** /**
* Get template storage * Get template storage
* @return Cytro * @return Fenom
*/ */
public function getStorage() { public function getStorage() {
return $this->_cytro; return $this->_fenom;
} }
public function getDepends() { public function getDepends() {
@ -135,12 +135,12 @@ class Render extends \ArrayObject {
* @return bool * @return bool
*/ */
public function isValid() { public function isValid() {
$provider = $this->_cytro->getProvider(strstr($this->_name, ":"), true); $provider = $this->_fenom->getProvider(strstr($this->_name, ":"), true);
if($provider->getLastModified($this->_name) >= $this->_time) { if($provider->getLastModified($this->_name) >= $this->_time) {
return false; return false;
} }
foreach($this->_depends as $tpl => $time) { foreach($this->_depends as $tpl => $time) {
if($this->_cytro->getTemplate($tpl)->getTime() !== $time) { if($this->_fenom->getTemplate($tpl)->getTime() !== $time) {
return false; return false;
} }
} }

View File

@ -1,13 +1,13 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
/** /**
* Scope for blocks tags * Scope for blocks tags

View File

@ -1,19 +1,19 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
use Cytro; use Fenom;
/** /**
* Template compiler * Template compiler
* *
* @package Cytro * @package Fenom
* @author Ivan Shalganov <owner@bzick.net> * @author Ivan Shalganov <owner@bzick.net>
*/ */
class Template extends Render { class Template extends Render {
@ -88,21 +88,21 @@ class Template extends Render {
/** /**
* Just factory * Just factory
* *
* @param \Cytro $cytro * @param \Fenom $fenom
* @param $options * @param $options
* @return Template * @return Template
*/ */
public static function factory(Cytro $cytro, $options) { public static function factory(Fenom $fenom, $options) {
return new static($cytro, $options); return new static($fenom, $options);
} }
/** /**
* @param Cytro $cytro Template storage * @param Fenom $fenom Template storage
* @param int $options * @param int $options
* @return \Cytro\Template * @return \Fenom\Template
*/ */
public function __construct(Cytro $cytro, $options) { public function __construct(Fenom $fenom, $options) {
$this->_cytro = $cytro; $this->_fenom = $fenom;
$this->_options = $options; $this->_options = $options;
} }
@ -120,7 +120,7 @@ class Template extends Render {
} else { } else {
$this->_base_name = $name; $this->_base_name = $name;
} }
$this->_provider = $this->_cytro->getProvider($provider); $this->_provider = $this->_fenom->getProvider($provider);
$this->_src = $this->_provider->getSource($this->_base_name, $this->_time); $this->_src = $this->_provider->getSource($this->_base_name, $this->_time);
if($compile) { if($compile) {
$this->compile(); $this->compile();
@ -133,7 +133,7 @@ class Template extends Render {
* @param string $name template name * @param string $name template name
* @param string $src template source * @param string $src template source
* @param bool $compile * @param bool $compile
* @return \Cytro\Template * @return \Fenom\Template
*/ */
public function source($name, $src, $compile = true) { public function source($name, $src, $compile = true) {
$this->_name = $name; $this->_name = $name;
@ -177,7 +177,7 @@ class Template extends Render {
if($end === false) { // if unexpected end of template if($end === false) { // if unexpected end of template
throw new CompileException("Unclosed tag in line {$this->_line}", 0, 1, $this->_name, $this->_line); throw new CompileException("Unclosed tag in line {$this->_line}", 0, 1, $this->_name, $this->_line);
} }
$tag = substr($this->_src, $start, $end - $start + 1); // variable $tag contains cytro tag '{...}' $tag = substr($this->_src, $start, $end - $start + 1); // variable $tag contains fenom tag '{...}'
$_tag = substr($tag, 1, -1); // strip delimiters '{' and '}' $_tag = substr($tag, 1, -1); // strip delimiters '{' and '}'
@ -321,8 +321,8 @@ class Template extends Render {
*/ */
public function getTemplateCode() { public function getTemplateCode() {
return "<?php \n". return "<?php \n".
"/** Cytro template '".$this->_name."' compiled at ".date('Y-m-d H:i:s')." */\n". "/** Fenom template '".$this->_name."' compiled at ".date('Y-m-d H:i:s')." */\n".
"return new Cytro\\Render(\$cytro, ".$this->_getClosureSource().", ".var_export(array( "return new Fenom\\Render(\$fenom, ".$this->_getClosureSource().", ".var_export(array(
"options" => $this->_options, "options" => $this->_options,
"provider" => $this->_scm, "provider" => $this->_scm,
"name" => $this->_name, "name" => $this->_name,
@ -466,20 +466,20 @@ class Template extends Render {
return $this->parseMacro($tokens, $name); return $this->parseMacro($tokens, $name);
} }
if($act = $this->_cytro->getFunction($action)) { // call some function if($act = $this->_fenom->getFunction($action)) { // call some function
switch($act["type"]) { switch($act["type"]) {
case Cytro::BLOCK_COMPILER: case Fenom::BLOCK_COMPILER:
$scope = new Scope($action, $this, $this->_line, $act, count($this->_stack), $this->_body); $scope = new Scope($action, $this, $this->_line, $act, count($this->_stack), $this->_body);
$code = $scope->open($tokens); $code = $scope->open($tokens);
if(!$scope->is_closed) { if(!$scope->is_closed) {
array_push($this->_stack, $scope); array_push($this->_stack, $scope);
} }
return $code; return $code;
case Cytro::INLINE_COMPILER: case Fenom::INLINE_COMPILER:
return call_user_func($act["parser"], $tokens, $this); return call_user_func($act["parser"], $tokens, $this);
case Cytro::INLINE_FUNCTION: case Fenom::INLINE_FUNCTION:
return call_user_func($act["parser"], $act["function"], $tokens, $this); return call_user_func($act["parser"], $act["function"], $tokens, $this);
case Cytro::BLOCK_FUNCTION: case Fenom::BLOCK_FUNCTION:
$scope = new Scope($action, $this, $this->_line, $act, count($this->_stack), $this->_body); $scope = new Scope($action, $this, $this->_line, $act, count($this->_stack), $this->_body);
$scope->setFuncName($act["function"]); $scope->setFuncName($act["function"]);
array_push($this->_stack, $scope); array_push($this->_stack, $scope);
@ -494,7 +494,7 @@ class Template extends Render {
return $this->_stack[$i]->tag($action, $tokens); return $this->_stack[$i]->tag($action, $tokens);
} }
} }
if($tags = $this->_cytro->getTagOwners($action)) { // unknown template tag if($tags = $this->_fenom->getTagOwners($action)) { // unknown template tag
throw new TokenizeException("Unexpected tag '$action' (this tag can be used with '".implode("', '", $tags)."')"); throw new TokenizeException("Unexpected tag '$action' (this tag can be used with '".implode("', '", $tags)."')");
} else { } else {
throw new TokenizeException("Unexpected tag $action"); throw new TokenizeException("Unexpected tag $action");
@ -548,7 +548,7 @@ class Template extends Render {
if($tokens->isSpecialVal()) { if($tokens->isSpecialVal()) {
$_exp .= $tokens->getAndNext(); $_exp .= $tokens->getAndNext();
} elseif($tokens->isNext("(")) { } elseif($tokens->isNext("(")) {
$func = $this->_cytro->getModifier($tokens->current()); $func = $this->_fenom->getModifier($tokens->current());
$tokens->next(); $tokens->next();
$_exp .= $func.$this->parseArgs($tokens); $_exp .= $func.$this->parseArgs($tokens);
} else { } else {
@ -687,7 +687,7 @@ class Template extends Render {
} elseif($t === T_OBJECT_OPERATOR) { } elseif($t === T_OBJECT_OPERATOR) {
$prop = $tokens->getNext(T_STRING); $prop = $tokens->getNext(T_STRING);
if($tokens->isNext("(")) { if($tokens->isNext("(")) {
if($this->_options & Cytro::DENY_METHODS) { if($this->_options & Fenom::DENY_METHODS) {
throw new \LogicException("Forbidden to call methods"); throw new \LogicException("Forbidden to call methods");
} }
$pure_var = false; $pure_var = false;
@ -844,7 +844,7 @@ class Template extends Render {
*/ */
public function parseModifier(Tokenizer $tokens, $value) { public function parseModifier(Tokenizer $tokens, $value) {
while($tokens->is("|")) { while($tokens->is("|")) {
$mods = $this->_cytro->getModifier( $modifier_name = $tokens->getNext(Tokenizer::MACRO_STRING) ); $mods = $this->_fenom->getModifier( $modifier_name = $tokens->getNext(Tokenizer::MACRO_STRING) );
$tokens->next(); $tokens->next();
$args = array(); $args = array();

View File

@ -1,13 +1,13 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Cytro; namespace Fenom;
/** /**
* for <PHP 5.4 compatible * for <PHP 5.4 compatible
@ -32,7 +32,7 @@ defined('T_YIELD') || define('T_YIELD', 370);
* @property array $curr the current token * @property array $curr the current token
* @property array $next the next token * @property array $next the next token
* *
* @package Cytro * @package Fenom
*/ */
class Tokenizer { class Tokenizer {
const TOKEN = 0; const TOKEN = 0;

View File

@ -1,19 +1,19 @@
<?php <?php
/* /*
* This file is part of Cytro. * This file is part of Fenom.
* *
* (c) 2013 Ivan Shalganov * (c) 2013 Ivan Shalganov
* *
* For the full copyright and license information, please view the license.md * For the full copyright and license information, please view the license.md
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
use Cytro\Template, use Fenom\Template,
Cytro\ProviderInterface; Fenom\ProviderInterface;
/** /**
* Cytro Template Engine * Fenom Template Engine
*/ */
class Cytro { class Fenom {
const VERSION = '1.0'; const VERSION = '1.0';
/* Compiler types */ /* Compiler types */
@ -32,11 +32,11 @@ class Cytro {
const DISABLE_CACHE = 0x1F0; const DISABLE_CACHE = 0x1F0;
/* Default parsers */ /* Default parsers */
const DEFAULT_CLOSE_COMPILER = 'Cytro\Compiler::stdClose'; const DEFAULT_CLOSE_COMPILER = 'Fenom\Compiler::stdClose';
const DEFAULT_FUNC_PARSER = 'Cytro\Compiler::stdFuncParser'; const DEFAULT_FUNC_PARSER = 'Fenom\Compiler::stdFuncParser';
const DEFAULT_FUNC_OPEN = 'Cytro\Compiler::stdFuncOpen'; const DEFAULT_FUNC_OPEN = 'Fenom\Compiler::stdFuncOpen';
const DEFAULT_FUNC_CLOSE = 'Cytro\Compiler::stdFuncClose'; const DEFAULT_FUNC_CLOSE = 'Fenom\Compiler::stdFuncClose';
const SMART_FUNC_PARSER = 'Cytro\Compiler::smartFuncParser'; const SMART_FUNC_PARSER = 'Fenom\Compiler::smartFuncParser';
/** /**
* @var int[] of possible options, as associative array * @var int[] of possible options, as associative array
@ -52,7 +52,7 @@ class Cytro {
); );
/** /**
* @var Cytro\Render[] Templates storage * @var Fenom\Render[] Templates storage
*/ */
protected $_storage = array(); protected $_storage = array();
/** /**
@ -74,7 +74,7 @@ class Cytro {
*/ */
private $_provider; private $_provider;
/** /**
* @var Cytro\ProviderInterface[] * @var Fenom\ProviderInterface[]
*/ */
protected $_providers = array(); protected $_providers = array();
@ -86,15 +86,15 @@ class Cytro {
"up" => 'strtoupper', "up" => 'strtoupper',
"lower" => 'strtolower', "lower" => 'strtolower',
"low" => 'strtolower', "low" => 'strtolower',
"date_format" => 'Cytro\Modifier::dateFormat', "date_format" => 'Fenom\Modifier::dateFormat',
"date" => 'Cytro\Modifier::date', "date" => 'Fenom\Modifier::date',
"truncate" => 'Cytro\Modifier::truncate', "truncate" => 'Fenom\Modifier::truncate',
"escape" => 'Cytro\Modifier::escape', "escape" => 'Fenom\Modifier::escape',
"e" => 'Cytro\Modifier::escape', // alias of escape "e" => 'Fenom\Modifier::escape', // alias of escape
"unescape" => 'Cytro\Modifier::unescape', "unescape" => 'Fenom\Modifier::unescape',
"strip" => 'Cytro\Modifier::strip', "strip" => 'Fenom\Modifier::strip',
"length" => 'Cytro\Modifier::length', "length" => 'Fenom\Modifier::length',
"default" => 'Cytro\Modifier::defaultValue' "default" => 'Fenom\Modifier::defaultValue'
); );
/** /**
@ -112,137 +112,137 @@ class Cytro {
protected $_actions = array( protected $_actions = array(
'foreach' => array( // {foreach ...} {break} {continue} {foreachelse} {/foreach} 'foreach' => array( // {foreach ...} {break} {continue} {foreachelse} {/foreach}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::foreachOpen', 'open' => 'Fenom\Compiler::foreachOpen',
'close' => 'Cytro\Compiler::foreachClose', 'close' => 'Fenom\Compiler::foreachClose',
'tags' => array( 'tags' => array(
'foreachelse' => 'Cytro\Compiler::foreachElse', 'foreachelse' => 'Fenom\Compiler::foreachElse',
'break' => 'Cytro\Compiler::tagBreak', 'break' => 'Fenom\Compiler::tagBreak',
'continue' => 'Cytro\Compiler::tagContinue', 'continue' => 'Fenom\Compiler::tagContinue',
), ),
'float_tags' => array('break' => 1, 'continue' => 1) 'float_tags' => array('break' => 1, 'continue' => 1)
), ),
'if' => array( // {if ...} {elseif ...} {else} {/if} 'if' => array( // {if ...} {elseif ...} {else} {/if}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::ifOpen', 'open' => 'Fenom\Compiler::ifOpen',
'close' => 'Cytro\Compiler::stdClose', 'close' => 'Fenom\Compiler::stdClose',
'tags' => array( 'tags' => array(
'elseif' => 'Cytro\Compiler::tagElseIf', 'elseif' => 'Fenom\Compiler::tagElseIf',
'else' => 'Cytro\Compiler::tagElse', 'else' => 'Fenom\Compiler::tagElse',
) )
), ),
'switch' => array( // {switch ...} {case ...} {break} {default} {/switch} 'switch' => array( // {switch ...} {case ...} {break} {default} {/switch}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::switchOpen', 'open' => 'Fenom\Compiler::switchOpen',
'close' => 'Cytro\Compiler::stdClose', 'close' => 'Fenom\Compiler::stdClose',
'tags' => array( 'tags' => array(
'case' => 'Cytro\Compiler::tagCase', 'case' => 'Fenom\Compiler::tagCase',
'default' => 'Cytro\Compiler::tagDefault', 'default' => 'Fenom\Compiler::tagDefault',
'break' => 'Cytro\Compiler::tagBreak', 'break' => 'Fenom\Compiler::tagBreak',
), ),
'float_tags' => array('break' => 1) 'float_tags' => array('break' => 1)
), ),
'for' => array( // {for ...} {break} {continue} {/for} 'for' => array( // {for ...} {break} {continue} {/for}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::forOpen', 'open' => 'Fenom\Compiler::forOpen',
'close' => 'Cytro\Compiler::forClose', 'close' => 'Fenom\Compiler::forClose',
'tags' => array( 'tags' => array(
'forelse' => 'Cytro\Compiler::forElse', 'forelse' => 'Fenom\Compiler::forElse',
'break' => 'Cytro\Compiler::tagBreak', 'break' => 'Fenom\Compiler::tagBreak',
'continue' => 'Cytro\Compiler::tagContinue', 'continue' => 'Fenom\Compiler::tagContinue',
), ),
'float_tags' => array('break' => 1, 'continue' => 1) 'float_tags' => array('break' => 1, 'continue' => 1)
), ),
'while' => array( // {while ...} {break} {continue} {/while} 'while' => array( // {while ...} {break} {continue} {/while}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::whileOpen', 'open' => 'Fenom\Compiler::whileOpen',
'close' => 'Cytro\Compiler::stdClose', 'close' => 'Fenom\Compiler::stdClose',
'tags' => array( 'tags' => array(
'break' => 'Cytro\Compiler::tagBreak', 'break' => 'Fenom\Compiler::tagBreak',
'continue' => 'Cytro\Compiler::tagContinue', 'continue' => 'Fenom\Compiler::tagContinue',
), ),
'float_tags' => array('break' => 1, 'continue' => 1) 'float_tags' => array('break' => 1, 'continue' => 1)
), ),
'include' => array( // {include ...} 'include' => array( // {include ...}
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
'parser' => 'Cytro\Compiler::tagInclude' 'parser' => 'Fenom\Compiler::tagInclude'
), ),
'var' => array( // {var ...} 'var' => array( // {var ...}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::varOpen', 'open' => 'Fenom\Compiler::varOpen',
'close' => 'Cytro\Compiler::varClose' 'close' => 'Fenom\Compiler::varClose'
), ),
'block' => array( // {block ...} {parent} {/block} 'block' => array( // {block ...} {parent} {/block}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::tagBlockOpen', 'open' => 'Fenom\Compiler::tagBlockOpen',
'close' => 'Cytro\Compiler::tagBlockClose', 'close' => 'Fenom\Compiler::tagBlockClose',
'tags' => array( 'tags' => array(
'parent' => 'Cytro\Compiler::tagParent' 'parent' => 'Fenom\Compiler::tagParent'
), ),
'float_tags' => array('parent' => 1) 'float_tags' => array('parent' => 1)
), ),
'extends' => array( // {extends ...} 'extends' => array( // {extends ...}
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
'parser' => 'Cytro\Compiler::tagExtends' 'parser' => 'Fenom\Compiler::tagExtends'
), ),
'use' => array( // {use} 'use' => array( // {use}
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
'parser' => 'Cytro\Compiler::tagUse' 'parser' => 'Fenom\Compiler::tagUse'
), ),
'capture' => array( // {capture ...} {/capture} 'capture' => array( // {capture ...} {/capture}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::captureOpen', 'open' => 'Fenom\Compiler::captureOpen',
'close' => 'Cytro\Compiler::captureClose' 'close' => 'Fenom\Compiler::captureClose'
), ),
'filter' => array( // {filter} ... {/filter} 'filter' => array( // {filter} ... {/filter}
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::filterOpen', 'open' => 'Fenom\Compiler::filterOpen',
'close' => 'Cytro\Compiler::filterClose' 'close' => 'Fenom\Compiler::filterClose'
), ),
'macro' => array( 'macro' => array(
'type' => self::BLOCK_COMPILER, 'type' => self::BLOCK_COMPILER,
'open' => 'Cytro\Compiler::macroOpen', 'open' => 'Fenom\Compiler::macroOpen',
'close' => 'Cytro\Compiler::macroClose' 'close' => 'Fenom\Compiler::macroClose'
), ),
'import' => array( 'import' => array(
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
'parser' => 'Cytro\Compiler::tagImport' 'parser' => 'Fenom\Compiler::tagImport'
), ),
'cycle' => array( 'cycle' => array(
'type' => self::INLINE_COMPILER, 'type' => self::INLINE_COMPILER,
'parser' => 'Cytro\Compiler::tagCycle' 'parser' => 'Fenom\Compiler::tagCycle'
) )
); );
/** /**
* Just factory * Just factory
* *
* @param string|Cytro\ProviderInterface $source path to templates or custom provider * @param string|Fenom\ProviderInterface $source path to templates or custom provider
* @param string $compile_dir path to compiled files * @param string $compile_dir path to compiled files
* @param int $options * @param int $options
* @throws InvalidArgumentException * @throws InvalidArgumentException
* @return Cytro * @return Fenom
*/ */
public static function factory($source, $compile_dir = '/tmp', $options = 0) { public static function factory($source, $compile_dir = '/tmp', $options = 0) {
if(is_string($source)) { if(is_string($source)) {
$provider = new Cytro\FSProvider($source); $provider = new Fenom\Provider($source);
} elseif($source instanceof ProviderInterface) { } elseif($source instanceof ProviderInterface) {
$provider = $source; $provider = $source;
} else { } else {
throw new InvalidArgumentException("Source must be a valid path or provider object"); throw new InvalidArgumentException("Source must be a valid path or provider object");
} }
$cytro = new static($provider); $fenom = new static($provider);
/* @var Cytro $cytro */ /* @var Fenom $fytro */
$cytro->setCompileDir($compile_dir); $fenom->setCompileDir($compile_dir);
if($options) { if($options) {
$cytro->setOptions($options); $fenom->setOptions($options);
} }
return $cytro; return $fenom;
} }
/** /**
* @param Cytro\ProviderInterface $provider * @param Fenom\ProviderInterface $provider
*/ */
public function __construct(Cytro\ProviderInterface $provider) { public function __construct(Fenom\ProviderInterface $provider) {
$this->_provider = $provider; $this->_provider = $provider;
} }
@ -250,7 +250,7 @@ class Cytro {
* Set compile directory * Set compile directory
* *
* @param string $dir directory to store compiled templates in * @param string $dir directory to store compiled templates in
* @return Cytro * @return Fenom
*/ */
public function setCompileDir($dir) { public function setCompileDir($dir) {
$this->_compile_dir = $dir; $this->_compile_dir = $dir;
@ -285,7 +285,7 @@ class Cytro {
* *
* @param string $modifier the modifier name * @param string $modifier the modifier name
* @param string $callback the modifier callback * @param string $callback the modifier callback
* @return Cytro * @return Fenom
*/ */
public function addModifier($modifier, $callback) { public function addModifier($modifier, $callback) {
$this->_modifiers[$modifier] = $callback; $this->_modifiers[$modifier] = $callback;
@ -297,7 +297,7 @@ class Cytro {
* *
* @param string $compiler * @param string $compiler
* @param callable $parser * @param callable $parser
* @return Cytro * @return Fenom
*/ */
public function addCompiler($compiler, $parser) { public function addCompiler($compiler, $parser) {
$this->_actions[$compiler] = array( $this->_actions[$compiler] = array(
@ -329,7 +329,7 @@ class Cytro {
* @param callable $open_parser * @param callable $open_parser
* @param callable|string $close_parser * @param callable|string $close_parser
* @param array $tags * @param array $tags
* @return Cytro * @return Fenom
*/ */
public function addBlockCompiler($compiler, $open_parser, $close_parser = self::DEFAULT_CLOSE_COMPILER, array $tags = array()) { public function addBlockCompiler($compiler, $open_parser, $close_parser = self::DEFAULT_CLOSE_COMPILER, array $tags = array()) {
$this->_actions[$compiler] = array( $this->_actions[$compiler] = array(
@ -347,7 +347,7 @@ class Cytro {
* @param array $tags * @param array $tags
* @param array $floats * @param array $floats
* @throws LogicException * @throws LogicException
* @return Cytro * @return Fenom
*/ */
public function addBlockCompilerSmart($compiler, $storage, array $tags, array $floats = array()) { public function addBlockCompilerSmart($compiler, $storage, array $tags, array $floats = array()) {
$c = array( $c = array(
@ -383,7 +383,7 @@ class Cytro {
* @param string $function * @param string $function
* @param callable $callback * @param callable $callback
* @param callable|string $parser * @param callable|string $parser
* @return Cytro * @return Fenom
*/ */
public function addFunction($function, $callback, $parser = self::DEFAULT_FUNC_PARSER) { public function addFunction($function, $callback, $parser = self::DEFAULT_FUNC_PARSER) {
$this->_actions[$function] = array( $this->_actions[$function] = array(
@ -397,7 +397,7 @@ class Cytro {
/** /**
* @param string $function * @param string $function
* @param callable $callback * @param callable $callback
* @return Cytro * @return Fenom
*/ */
public function addFunctionSmart($function, $callback) { public function addFunctionSmart($function, $callback) {
$this->_actions[$function] = array( $this->_actions[$function] = array(
@ -413,7 +413,7 @@ class Cytro {
* @param callable $callback * @param callable $callback
* @param callable|string $parser_open * @param callable|string $parser_open
* @param callable|string $parser_close * @param callable|string $parser_close
* @return Cytro * @return Fenom
*/ */
public function addBlockFunction($function, $callback, $parser_open = self::DEFAULT_FUNC_OPEN, $parser_close = self::DEFAULT_FUNC_CLOSE) { public function addBlockFunction($function, $callback, $parser_open = self::DEFAULT_FUNC_OPEN, $parser_close = self::DEFAULT_FUNC_CLOSE) {
$this->_actions[$function] = array( $this->_actions[$function] = array(
@ -427,7 +427,7 @@ class Cytro {
/** /**
* @param array $funcs * @param array $funcs
* @return Cytro * @return Fenom
*/ */
public function addAllowedFunctions(array $funcs) { public function addAllowedFunctions(array $funcs) {
$this->_allowed_funcs = $this->_allowed_funcs + array_flip($funcs); $this->_allowed_funcs = $this->_allowed_funcs + array_flip($funcs);
@ -495,9 +495,9 @@ class Cytro {
* Add source template provider by scheme * Add source template provider by scheme
* *
* @param string $scm scheme name * @param string $scm scheme name
* @param Cytro\ProviderInterface $provider provider object * @param Fenom\ProviderInterface $provider provider object
*/ */
public function addProvider($scm, \Cytro\ProviderInterface $provider) { public function addProvider($scm, \Fenom\ProviderInterface $provider) {
$this->_providers[$scm] = $provider; $this->_providers[$scm] = $provider;
} }
@ -528,7 +528,7 @@ class Cytro {
/** /**
* @param bool|string $scm * @param bool|string $scm
* @return Cytro\ProviderInterface * @return Fenom\ProviderInterface
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public function getProvider($scm = false) { public function getProvider($scm = false) {
@ -546,10 +546,10 @@ class Cytro {
/** /**
* Return empty template * Return empty template
* *
* @return Cytro\Template * @return Fenom\Template
*/ */
public function getRawTemplate() { public function getRawTemplate() {
return new \Cytro\Template($this, $this->_options); return new \Fenom\Template($this, $this->_options);
} }
/** /**
@ -557,7 +557,7 @@ class Cytro {
* *
* @param string $template name of template * @param string $template name of template
* @param array $vars array of data for template * @param array $vars array of data for template
* @return Cytro\Render * @return Fenom\Render
*/ */
public function display($template, array $vars = array()) { public function display($template, array $vars = array()) {
return $this->getTemplate($template)->display($vars); return $this->getTemplate($template)->display($vars);
@ -580,8 +580,8 @@ class Cytro {
* @param array $vars * @param array $vars
* @param $callback * @param $callback
* @param float $chunk * @param float $chunk
* @return \Cytro\Render * @return \Fenom\Render
* @example $cytro->pipe("products.yml.tpl", $iterators, [new SplFileObject("/tmp/products.yml"), "fwrite"], 512*1024) * @example $fenom->pipe("products.yml.tpl", $iterators, [new SplFileObject("/tmp/products.yml"), "fwrite"], 512*1024)
*/ */
public function pipe($template, array $vars, $callback, $chunk = 1e6) { public function pipe($template, array $vars, $callback, $chunk = 1e6) {
ob_start($callback, $chunk, true); ob_start($callback, $chunk, true);
@ -595,12 +595,12 @@ class Cytro {
* *
* @param string $template template name with schema * @param string $template template name with schema
* @param int $options additional options and flags * @param int $options additional options and flags
* @return Cytro\Template * @return Fenom\Template
*/ */
public function getTemplate($template, $options = 0) { public function getTemplate($template, $options = 0) {
$key = dechex($this->_options | $options)."@".$template; $key = dechex($this->_options | $options)."@".$template;
if(isset($this->_storage[ $key ])) { if(isset($this->_storage[ $key ])) {
/** @var Cytro\Template $tpl */ /** @var Fenom\Template $tpl */
$tpl = $this->_storage[ $key ]; $tpl = $this->_storage[ $key ];
if(($this->_options & self::AUTO_RELOAD) && !$tpl->isValid()) { if(($this->_options & self::AUTO_RELOAD) && !$tpl->isValid()) {
return $this->_storage[ $key ] = $this->compile($template, true, $options); return $this->_storage[ $key ] = $this->compile($template, true, $options);
@ -617,9 +617,9 @@ class Cytro {
/** /**
* Add custom template into storage * Add custom template into storage
* *
* @param Cytro\Render $template * @param Fenom\Render $template
*/ */
public function addTemplate(Cytro\Render $template) { public function addTemplate(Fenom\Render $template) {
$this->_storage[dechex($template->getOptions()).'@'. $template->getName() ] = $template; $this->_storage[dechex($template->getOptions()).'@'. $template->getName() ] = $template;
} }
@ -628,14 +628,14 @@ class Cytro {
* *
* @param string $tpl * @param string $tpl
* @param int $opts * @param int $opts
* @return Cytro\Render * @return Fenom\Render
*/ */
protected function _load($tpl, $opts) { protected function _load($tpl, $opts) {
$file_name = $this->_getCacheName($tpl, $opts); $file_name = $this->_getCacheName($tpl, $opts);
if(!is_file($this->_compile_dir."/".$file_name)) { if(!is_file($this->_compile_dir."/".$file_name)) {
return $this->compile($tpl, true, $opts); return $this->compile($tpl, true, $opts);
} else { } else {
$cytro = $this; $fenom = $this;
return include($this->_compile_dir."/".$file_name); return include($this->_compile_dir."/".$file_name);
} }
} }
@ -659,7 +659,7 @@ class Cytro {
* @param bool $store store template on disk * @param bool $store store template on disk
* @param int $options * @param int $options
* @throws RuntimeException * @throws RuntimeException
* @return \Cytro\Template * @return \Fenom\Template
*/ */
public function compile($tpl, $store = true, $options = 0) { public function compile($tpl, $store = true, $options = 0) {
$options = $this->_options | $options; $options = $this->_options | $options;
@ -692,7 +692,7 @@ class Cytro {
* Remove all compiled templates * Remove all compiled templates
*/ */
public function clearAllCompiles() { public function clearAllCompiles() {
\Cytro\FSProvider::clean($this->_compile_dir); \Fenom\Provider::clean($this->_compile_dir);
} }
/** /**
@ -700,7 +700,7 @@ class Cytro {
* *
* @param string $code * @param string $code
* @param string $name * @param string $name
* @return Cytro\Template * @return Fenom\Template
*/ */
public function compileCode($code, $name = 'Runtime compile') { public function compileCode($code, $name = 'Runtime compile') {
return Template::factory($this, $this->_options)->source($name, $code); return Template::factory($this, $this->_options)->source($name, $code);

View File

@ -1,12 +1,12 @@
<?php <?php
namespace Cytro; namespace Fenom;
use Cytro, Cytro\FSProvider as FS; use Fenom, Fenom\Provider as FS;
class TestCase extends \PHPUnit_Framework_TestCase { class TestCase extends \PHPUnit_Framework_TestCase {
/** /**
* @var Cytro * @var Fenom
*/ */
public $cytro; public $fenom;
public $values = array( public $values = array(
"one" => 1, "one" => 1,
@ -18,14 +18,14 @@ class TestCase extends \PHPUnit_Framework_TestCase {
); );
public function setUp() { public function setUp() {
if(!file_exists(CYTRO_RESOURCES.'/compile')) { if(!file_exists(FENOM_RESOURCES.'/compile')) {
mkdir(CYTRO_RESOURCES.'/compile', 0777, true); mkdir(FENOM_RESOURCES.'/compile', 0777, true);
} else { } else {
FS::clean(CYTRO_RESOURCES.'/compile/'); FS::clean(FENOM_RESOURCES.'/compile/');
} }
$this->cytro = Cytro::factory(CYTRO_RESOURCES.'/template', CYTRO_RESOURCES.'/compile'); $this->fenom = Fenom::factory(FENOM_RESOURCES.'/template', FENOM_RESOURCES.'/compile');
$this->cytro->addModifier('dots', __CLASS__.'::dots'); $this->fenom->addModifier('dots', __CLASS__.'::dots');
$this->cytro->addModifier('concat', __CLASS__.'::concat'); $this->fenom->addModifier('concat', __CLASS__.'::concat');
} }
public static function dots($value) { public static function dots($value) {
@ -37,15 +37,15 @@ class TestCase extends \PHPUnit_Framework_TestCase {
} }
public static function setUpBeforeClass() { public static function setUpBeforeClass() {
if(!file_exists(CYTRO_RESOURCES.'/template')) { if(!file_exists(FENOM_RESOURCES.'/template')) {
mkdir(CYTRO_RESOURCES.'/template', 0777, true); mkdir(FENOM_RESOURCES.'/template', 0777, true);
} else { } else {
FS::clean(CYTRO_RESOURCES.'/template/'); FS::clean(FENOM_RESOURCES.'/template/');
} }
} }
public function tpl($name, $code) { public function tpl($name, $code) {
file_put_contents(CYTRO_RESOURCES.'/template/'.$name, $code); file_put_contents(FENOM_RESOURCES.'/template/'.$name, $code);
} }
/** /**
@ -57,7 +57,7 @@ class TestCase extends \PHPUnit_Framework_TestCase {
* @param bool $dump dump source and result code (for debug) * @param bool $dump dump source and result code (for debug)
*/ */
public function exec($code, $vars, $result, $dump = false) { public function exec($code, $vars, $result, $dump = false) {
$tpl = $this->cytro->compileCode($code, "runtime.tpl"); $tpl = $this->fenom->compileCode($code, "runtime.tpl");
if($dump) { if($dump) {
echo "\n========= DUMP BEGIN ===========\n".$code."\n--- to ---\n".$tpl->getBody()."\n========= DUMP END =============\n"; echo "\n========= DUMP BEGIN ===========\n".$code."\n--- to ---\n".$tpl->getBody()."\n========= DUMP END =============\n";
} }
@ -66,7 +66,7 @@ class TestCase extends \PHPUnit_Framework_TestCase {
public function execTpl($name, $code, $vars, $result, $dump = false) { public function execTpl($name, $code, $vars, $result, $dump = false) {
$this->tpl($name, $code); $this->tpl($name, $code);
$tpl = $this->cytro->getTemplate($name); $tpl = $this->fenom->getTemplate($name);
if($dump) { if($dump) {
echo "\n========= DUMP BEGIN ===========\n".$code."\n--- to ---\n".$tpl->getBody()."\n========= DUMP END =============\n"; echo "\n========= DUMP BEGIN ===========\n".$code."\n--- to ---\n".$tpl->getBody()."\n========= DUMP END =============\n";
} }
@ -78,25 +78,25 @@ class TestCase extends \PHPUnit_Framework_TestCase {
* @param string $code source of the template * @param string $code source of the template
* @param string $exception exception class * @param string $exception exception class
* @param string $message exception message * @param string $message exception message
* @param int $options Cytro's options * @param int $options Fenom's options
*/ */
public function execError($code, $exception, $message, $options = 0) { public function execError($code, $exception, $message, $options = 0) {
$opt = $this->cytro->getOptions(); $opt = $this->fenom->getOptions();
$this->cytro->setOptions($options); $this->fenom->setOptions($options);
try { try {
$this->cytro->compileCode($code, "inline.tpl"); $this->fenom->compileCode($code, "inline.tpl");
} catch(\Exception $e) { } catch(\Exception $e) {
$this->assertSame($exception, get_class($e), "Exception $code"); $this->assertSame($exception, get_class($e), "Exception $code");
$this->assertStringStartsWith($message, $e->getMessage()); $this->assertStringStartsWith($message, $e->getMessage());
$this->cytro->setOptions($opt); $this->fenom->setOptions($opt);
return; return;
} }
$this->cytro->setOptions($opt); $this->fenom->setOptions($opt);
$this->fail("Code $code must be invalid"); $this->fail("Code $code must be invalid");
} }
public function assertRender($tpl, $result, $debug = false) { public function assertRender($tpl, $result, $debug = false) {
$template = $this->cytro->compileCode($tpl); $template = $this->fenom->compileCode($tpl);
if($debug) { if($debug) {
print_r("$tpl:\n".$template->getBody()); print_r("$tpl:\n".$template->getBody());
} }

View File

@ -4,9 +4,9 @@ require_once __DIR__."/../vendor/autoload.php";
define('CYTRO_RESOURCES', __DIR__."/resources"); define('FENOM_RESOURCES', __DIR__."/resources");
require_once CYTRO_RESOURCES."/actions.php"; require_once FENOM_RESOURCES."/actions.php";
require_once __DIR__."/TestCase.php"; require_once __DIR__."/TestCase.php";
function drop() { function drop() {

View File

@ -1,22 +1,22 @@
<?php <?php
use Cytro\Render, use Fenom\Render,
Cytro\FSProvider as FS; Fenom\Provider as FS;
class CytroTest extends \Cytro\TestCase { class FenomTest extends \Fenom\TestCase {
public function testAddRender() { public function testAddRender() {
$test = $this; $test = $this;
$this->cytro->addTemplate(new Render($this->cytro, function($tpl) use ($test) { $this->fenom->addTemplate(new Render($this->fenom, function($tpl) use ($test) {
/** @var \PHPUnit_Framework_TestCase $test */ /** @var \PHPUnit_Framework_TestCase $test */
$test->assertInstanceOf('Cytro\Render', $tpl); $test->assertInstanceOf('Fenom\Render', $tpl);
echo "Inline render"; echo "Inline render";
}, array( }, array(
"name" => 'render.tpl', "name" => 'render.tpl',
"scm" => false "scm" => false
))); )));
$this->assertSame("Inline render", $this->cytro->fetch('render.tpl', array())); $this->assertSame("Inline render", $this->fenom->fetch('render.tpl', array()));
} }
public function testCompileFile() { public function testCompileFile() {
@ -26,71 +26,71 @@ class CytroTest extends \Cytro\TestCase {
); );
$this->tpl('template1.tpl', 'Template 1 a'); $this->tpl('template1.tpl', 'Template 1 a');
$this->tpl('template2.tpl', 'Template 2 b'); $this->tpl('template2.tpl', 'Template 2 b');
$this->assertSame("Template 1 a", $this->cytro->fetch('template1.tpl', $a)); $this->assertSame("Template 1 a", $this->fenom->fetch('template1.tpl', $a));
$this->assertSame("Template 2 b", $this->cytro->fetch('template2.tpl', $a)); $this->assertSame("Template 2 b", $this->fenom->fetch('template2.tpl', $a));
$this->assertInstanceOf('Cytro\Render', $this->cytro->getTemplate('template1.tpl')); $this->assertInstanceOf('Fenom\Render', $this->fenom->getTemplate('template1.tpl'));
$this->assertInstanceOf('Cytro\Render', $this->cytro->getTemplate('template2.tpl')); $this->assertInstanceOf('Fenom\Render', $this->fenom->getTemplate('template2.tpl'));
$this->assertSame(3, iterator_count(new FilesystemIterator(CYTRO_RESOURCES.'/compile'))); $this->assertSame(3, iterator_count(new FilesystemIterator(FENOM_RESOURCES.'/compile')));
} }
public function testStorage() { public function testStorage() {
$this->tpl('custom.tpl', 'Custom template'); $this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
//$this->cytro->clearCompiledTemplate('custom.tpl', false); //$this->fenom->clearCompiledTemplate('custom.tpl', false);
//$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array())); //$this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
$this->tpl('custom.tpl', 'Custom template 2'); $this->tpl('custom.tpl', 'Custom template 2');
$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
} }
public function testCheckMTime() { public function testCheckMTime() {
$this->cytro->setOptions(Cytro::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->tpl('custom.tpl', 'Custom template'); $this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
sleep(1); sleep(1);
$this->tpl('custom.tpl', 'Custom template (new)'); $this->tpl('custom.tpl', 'Custom template (new)');
$this->assertSame("Custom template (new)", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom template (new)", $this->fenom->fetch('custom.tpl', array()));
} }
public function testForceCompile() { public function testForceCompile() {
$this->cytro->setOptions(Cytro::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->tpl('custom.tpl', 'Custom template'); $this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom template", $this->fenom->fetch('custom.tpl', array()));
$this->tpl('custom.tpl', 'Custom template (new)'); $this->tpl('custom.tpl', 'Custom template (new)');
$this->assertSame("Custom template (new)", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom template (new)", $this->fenom->fetch('custom.tpl', array()));
} }
public function testSetModifier() { public function testSetModifier() {
$this->cytro->addModifier("mymod", "myMod"); $this->fenom->addModifier("mymod", "myMod");
$this->tpl('custom.tpl', 'Custom modifier {$a|mymod}'); $this->tpl('custom.tpl', 'Custom modifier {$a|mymod}');
$this->assertSame("Custom modifier (myMod)Custom(/myMod)", $this->cytro->fetch('custom.tpl', array("a" => "Custom"))); $this->assertSame("Custom modifier (myMod)Custom(/myMod)", $this->fenom->fetch('custom.tpl', array("a" => "Custom")));
} }
/** /**
* @group add_functions * @group add_functions
*/ */
public function testSetFunctions() { public function testSetFunctions() {
$this->cytro->setOptions(Cytro::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->cytro->addFunction("myfunc", "myFunc"); $this->fenom->addFunction("myfunc", "myFunc");
$this->cytro->addBlockFunction("myblockfunc", "myBlockFunc"); $this->fenom->addBlockFunction("myblockfunc", "myBlockFunc");
$this->tpl('custom.tpl', 'Custom function {myfunc name="foo"}'); $this->tpl('custom.tpl', 'Custom function {myfunc name="foo"}');
$this->assertSame("Custom function MyFunc:foo", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom function MyFunc:foo", $this->fenom->fetch('custom.tpl', array()));
$this->tpl('custom.tpl', 'Custom function {myblockfunc name="foo"} this block1 {/myblockfunc}'); $this->tpl('custom.tpl', 'Custom function {myblockfunc name="foo"} this block1 {/myblockfunc}');
$this->assertSame("Custom function Block:foo:this block1:Block", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom function Block:foo:this block1:Block", $this->fenom->fetch('custom.tpl', array()));
} }
public function testSetCompilers() { public function testSetCompilers() {
$this->cytro->setOptions(Cytro::FORCE_COMPILE); $this->fenom->setOptions(Fenom::FORCE_COMPILE);
$this->cytro->addCompiler("mycompiler", 'myCompiler'); $this->fenom->addCompiler("mycompiler", 'myCompiler');
$this->cytro->addBlockCompiler("myblockcompiler", 'myBlockCompilerOpen', 'myBlockCompilerClose', array( $this->fenom->addBlockCompiler("myblockcompiler", 'myBlockCompilerOpen', 'myBlockCompilerClose', array(
'tag' => 'myBlockCompilerTag' 'tag' => 'myBlockCompilerTag'
)); ));
$this->tpl('custom.tpl', 'Custom compiler {mycompiler name="bar"}'); $this->tpl('custom.tpl', 'Custom compiler {mycompiler name="bar"}');
$this->assertSame("Custom compiler PHP_VERSION: ".PHP_VERSION." (for bar)", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom compiler PHP_VERSION: ".PHP_VERSION." (for bar)", $this->fenom->fetch('custom.tpl', array()));
$this->tpl('custom.tpl', 'Custom compiler {myblockcompiler name="bar"} block1 {tag name="baz"} block2 {/myblockcompiler}'); $this->tpl('custom.tpl', 'Custom compiler {myblockcompiler name="bar"} block1 {tag name="baz"} block2 {/myblockcompiler}');
$this->assertSame("Custom compiler PHP_VERSION: ".PHP_VERSION." (for bar) block1 Tag baz of compiler block2 End of compiler", $this->cytro->fetch('custom.tpl', array())); $this->assertSame("Custom compiler PHP_VERSION: ".PHP_VERSION." (for bar) block1 Tag baz of compiler block2 End of compiler", $this->fenom->fetch('custom.tpl', array()));
} }
} }

View File

@ -1,6 +1,6 @@
<?php <?php
namespace Cytro; namespace Fenom;
class CommentTest extends TestCase { class CommentTest extends TestCase {

View File

@ -1,13 +1,13 @@
<?php <?php
namespace Cytro; namespace Fenom;
class CustomProviderTest extends TestCase { class CustomProviderTest extends TestCase {
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->cytro->addProvider("my", new FSProvider(CYTRO_RESOURCES.'/provider')); $this->fenom->addProvider("my", new Provider(FENOM_RESOURCES.'/provider'));
} }
public function testCustom() { public function testCustom() {

View File

@ -1,13 +1,13 @@
<?php <?php
namespace Cytro; namespace Fenom;
use Cytro, Cytro\TestCase; use Fenom, Fenom\TestCase;
class ExtendsTemplateTest extends TestCase { class ExtendsTemplateTest extends TestCase {
public function _testSandbox() { public function _testSandbox() {
$this->cytro = Cytro::factory(CYTRO_RESOURCES.'/provider', CYTRO_RESOURCES.'/compile'); $this->fenom = Fenom::factory(FENOM_RESOURCES.'/provider', FENOM_RESOURCES.'/compile');
try { try {
print_r($this->cytro->getTemplate('use/child.tpl')->getBody()); print_r($this->fenom->getTemplate('use/child.tpl')->getBody());
} catch (\Exception $e) { } catch (\Exception $e) {
echo "$e"; echo "$e";
} }
@ -114,24 +114,24 @@ class ExtendsTemplateTest extends TestCase {
$tpls = self::generate('{block "%s"}%s{/block}', '{extends "level.%d.tpl"}', self::templates($vars)); $tpls = self::generate('{block "%s"}%s{/block}', '{extends "level.%d.tpl"}', self::templates($vars));
foreach($tpls as $name => $tpl) { foreach($tpls as $name => $tpl) {
$this->tpl($name, $tpl["src"]); $this->tpl($name, $tpl["src"]);
$this->assertSame($this->cytro->fetch($name, $vars), $tpl["dst"]); $this->assertSame($this->fenom->fetch($name, $vars), $tpl["dst"]);
} }
return; return;
$vars["default"]++; $vars["default"]++;
$this->cytro->flush(); $this->fenom->flush();
$tpls = self::generate('{block "{$%s}"}%s{/block}', '{extends "level.%d.tpl"}', self::templates($vars)); $tpls = self::generate('{block "{$%s}"}%s{/block}', '{extends "level.%d.tpl"}', self::templates($vars));
arsort($tpls); arsort($tpls);
foreach($tpls as $name => $tpl) { foreach($tpls as $name => $tpl) {
$this->tpl("d.".$name, $tpl["src"]); $this->tpl("d.".$name, $tpl["src"]);
$this->assertSame($this->cytro->fetch("d.".$name, $vars), $tpl["dst"]); $this->assertSame($this->fenom->fetch("d.".$name, $vars), $tpl["dst"]);
} }
$vars["default"]++; $vars["default"]++;
$this->cytro->flush(); $this->fenom->flush();
$tpls = self::generate('{block "%s"}%s{/block}', '{extends "$level.%d.tpl"}', self::templates($vars)); $tpls = self::generate('{block "%s"}%s{/block}', '{extends "$level.%d.tpl"}', self::templates($vars));
arsort($tpls); arsort($tpls);
foreach($tpls as $name => $tpl) { foreach($tpls as $name => $tpl) {
$this->tpl("x.".$name, $tpl["src"]); $this->tpl("x.".$name, $tpl["src"]);
$this->assertSame($this->cytro->fetch("x.".$name, $vars), $tpl["dst"]); $this->assertSame($this->fenom->fetch("x.".$name, $vars), $tpl["dst"]);
} }
} }
@ -139,8 +139,8 @@ class ExtendsTemplateTest extends TestCase {
* @group use * @group use
*/ */
public function testUse() { public function testUse() {
$this->cytro = Cytro::factory(CYTRO_RESOURCES.'/provider', CYTRO_RESOURCES.'/compile'); $this->fenom = Fenom::factory(FENOM_RESOURCES.'/provider', FENOM_RESOURCES.'/compile');
$this->assertSame("<html>\n block 1 blocks \n block 2 child \n</html>", $this->cytro->fetch('use/child.tpl')); $this->assertSame("<html>\n block 1 blocks \n block 2 child \n</html>", $this->fenom->fetch('use/child.tpl'));
} }
public function _testParent() { public function _testParent() {

View File

@ -1,5 +1,5 @@
<?php <?php
namespace Cytro; namespace Fenom;
class MacrosTest extends TestCase { class MacrosTest extends TestCase {
@ -45,30 +45,30 @@ class MacrosTest extends TestCase {
} }
public function testMacros() { public function testMacros() {
$tpl = $this->cytro->compile('math.tpl'); $tpl = $this->fenom->compile('math.tpl');
$this->assertStringStartsWith('x + y = ', trim($tpl->macros["plus"]["body"])); $this->assertStringStartsWith('x + y = ', trim($tpl->macros["plus"]["body"]));
$this->assertSame('Math: x + y = 5 , x - y - z = 6', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('Math: x + y = 5 , x - y - z = 6', Modifier::strip($tpl->fetch(array()), true));
} }
public function testImport() { public function testImport() {
$tpl = $this->cytro->compile('import.tpl'); $tpl = $this->fenom->compile('import.tpl');
$this->assertSame('Imp: x + y = 3 , x - y - z = 3', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('Imp: x + y = 3 , x - y - z = 3', Modifier::strip($tpl->fetch(array()), true));
} }
public function testImportCustom() { public function testImportCustom() {
$tpl = $this->cytro->compile('import_custom.tpl'); $tpl = $this->fenom->compile('import_custom.tpl');
$this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true));
} }
/** /**
* @expectedExceptionMessage Undefined macro 'plus' * @expectedExceptionMessage Undefined macro 'plus'
* @expectedException \Cytro\CompileException * @expectedException \Fenom\CompileException
*/ */
public function testImportMiss() { public function testImportMiss() {
$tpl = $this->cytro->compile('import_miss.tpl'); $tpl = $this->fenom->compile('import_miss.tpl');
$this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true)); $this->assertSame('a: x + y = 3 , x - y - z = 3 , new minus macros .', Modifier::strip($tpl->fetch(array()), true));
} }

View File

@ -1,5 +1,5 @@
<?php <?php
namespace Cytro; namespace Fenom;
class ModifiersTest extends TestCase { class ModifiersTest extends TestCase {
@ -34,7 +34,7 @@ class ModifiersTest extends TestCase {
* @param bool $middle * @param bool $middle
*/ */
public function testTruncate($in, $out, $count, $delim = '...', $by_words = false, $middle = false) { public function testTruncate($in, $out, $count, $delim = '...', $by_words = false, $middle = false) {
$tpl = $this->cytro->compileCode('{$text|truncate:$count:$delim:$by_words:$middle}'); $tpl = $this->fenom->compileCode('{$text|truncate:$count:$delim:$by_words:$middle}');
$this->assertEquals($out, $tpl->fetch(array( $this->assertEquals($out, $tpl->fetch(array(
"text" => $in, "text" => $in,
"count" => $count, "count" => $count,
@ -65,7 +65,7 @@ class ModifiersTest extends TestCase {
* @param $out * @param $out
*/ */
public function testUpLow($modifier, $in, $out) { public function testUpLow($modifier, $in, $out) {
$tpl = $this->cytro->compileCode('{$text|'.$modifier.'}'); $tpl = $this->fenom->compileCode('{$text|'.$modifier.'}');
$this->assertEquals($out, $tpl->fetch(array( $this->assertEquals($out, $tpl->fetch(array(
"text" => $in, "text" => $in,
))); )));
@ -91,7 +91,7 @@ class ModifiersTest extends TestCase {
* @param $out * @param $out
*/ */
public function testLength($in, $out) { public function testLength($in, $out) {
$tpl = $this->cytro->compileCode('{$data|length}'); $tpl = $this->fenom->compileCode('{$data|length}');
$this->assertEquals($out, $tpl->fetch(array( $this->assertEquals($out, $tpl->fetch(array(
"data" => $in, "data" => $in,
))); )));

View File

@ -1,10 +1,10 @@
<?php <?php
namespace Cytro; namespace Fenom;
use Cytro; use Fenom;
class FSProviderTest extends \Cytro\TestCase { class FSProviderTest extends \Fenom\TestCase {
/** /**
* @var FSProvider * @var Provider
*/ */
public $provider; public $provider;
@ -12,7 +12,7 @@ class FSProviderTest extends \Cytro\TestCase {
parent::setUp(); parent::setUp();
$this->tpl("template1.tpl", 'Template 1 {$a}'); $this->tpl("template1.tpl", 'Template 1 {$a}');
$this->tpl("template2.tpl", 'Template 2 {$a}'); $this->tpl("template2.tpl", 'Template 2 {$a}');
$this->provider = new FSProvider(CYTRO_RESOURCES.'/template'); $this->provider = new Provider(FENOM_RESOURCES.'/template');
} }
public function testIsTemplateExists() { public function testIsTemplateExists() {
@ -23,8 +23,8 @@ class FSProviderTest extends \Cytro\TestCase {
public function testGetSource() { public function testGetSource() {
$src = $this->provider->getSource("template1.tpl", $time); $src = $this->provider->getSource("template1.tpl", $time);
clearstatcache(); clearstatcache();
$this->assertEquals(file_get_contents(CYTRO_RESOURCES.'/template/template1.tpl'), $src); $this->assertEquals(file_get_contents(FENOM_RESOURCES.'/template/template1.tpl'), $src);
$this->assertEquals(filemtime(CYTRO_RESOURCES.'/template/template1.tpl'), $time); $this->assertEquals(filemtime(FENOM_RESOURCES.'/template/template1.tpl'), $time);
} }
/** /**
@ -37,7 +37,7 @@ class FSProviderTest extends \Cytro\TestCase {
public function testGetLastModified() { public function testGetLastModified() {
$time = $this->provider->getLastModified("template1.tpl"); $time = $this->provider->getLastModified("template1.tpl");
clearstatcache(); clearstatcache();
$this->assertEquals(filemtime(CYTRO_RESOURCES.'/template/template1.tpl'), $time); $this->assertEquals(filemtime(FENOM_RESOURCES.'/template/template1.tpl'), $time);
} }
/** /**
@ -52,7 +52,7 @@ class FSProviderTest extends \Cytro\TestCase {
$this->assertSame($tpls, array_keys($times)); $this->assertSame($tpls, array_keys($times));
clearstatcache(); clearstatcache();
foreach($times as $template => $time) { foreach($times as $template => $time) {
$this->assertEquals(filemtime(CYTRO_RESOURCES."/template/$template"), $time); $this->assertEquals(filemtime(FENOM_RESOURCES."/template/$template"), $time);
} }
} }

View File

@ -1,7 +1,7 @@
<?php <?php
namespace Cytro; namespace Fenom;
use Cytro, use Fenom,
Cytro\Render; Fenom\Render;
class RenderTest extends \PHPUnit_Framework_TestCase { class RenderTest extends \PHPUnit_Framework_TestCase {
@ -11,7 +11,7 @@ class RenderTest extends \PHPUnit_Framework_TestCase {
public static $render; public static $render;
public static function setUpBeforeClass() { public static function setUpBeforeClass() {
self::$render = new Render(Cytro::factory("."), function ($tpl) { self::$render = new Render(Fenom::factory("."), function ($tpl) {
echo "It is render's function ".$tpl["render"]; echo "It is render's function ".$tpl["render"];
}, array( }, array(
"name" => "render.tpl" "name" => "render.tpl"
@ -19,7 +19,7 @@ class RenderTest extends \PHPUnit_Framework_TestCase {
} }
public function testCreate() { public function testCreate() {
$r = new Render(Cytro::factory("."), function () { $r = new Render(Fenom::factory("."), function () {
echo "Test render"; echo "Test render";
}, array( }, array(
"name" => "test.render.tpl" "name" => "test.render.tpl"
@ -43,7 +43,7 @@ class RenderTest extends \PHPUnit_Framework_TestCase {
* @expectedExceptionMessage template error * @expectedExceptionMessage template error
*/ */
public function testFetchException() { public function testFetchException() {
$render = new Render(Cytro::factory("."), function () { $render = new Render(Fenom::factory("."), function () {
echo "error"; echo "error";
throw new \RuntimeException("template error"); throw new \RuntimeException("template error");
}, array( }, array(

View File

@ -1,23 +1,23 @@
<?php <?php
namespace Cytro; namespace Fenom;
class ScopeTest extends TestCase { class ScopeTest extends TestCase {
public function openTag($tokenizer, $scope) { public function openTag($tokenizer, $scope) {
$this->assertInstanceOf('Cytro\Tokenizer', $tokenizer); $this->assertInstanceOf('Fenom\Tokenizer', $tokenizer);
$this->assertInstanceOf('Cytro\Scope', $scope); $this->assertInstanceOf('Fenom\Scope', $scope);
$scope["value"] = true; $scope["value"] = true;
return "open-tag"; return "open-tag";
} }
public function closeTag($tokenizer, $scope) { public function closeTag($tokenizer, $scope) {
$this->assertInstanceOf('Cytro\Tokenizer', $tokenizer); $this->assertInstanceOf('Fenom\Tokenizer', $tokenizer);
$this->assertInstanceOf('Cytro\Scope', $scope); $this->assertInstanceOf('Fenom\Scope', $scope);
$this->assertTrue($scope["value"]); $this->assertTrue($scope["value"]);
return "close-tag"; return "close-tag";
} }
public function testBlock() { public function testBlock() {
/*$scope = new Scope($this->cytro, new Template($this->cytro), 1, array( /*$scope = new Scope($this->fenom, new Template($this->fenom), 1, array(
"open" => array($this, "openTag"), "open" => array($this, "openTag"),
"close" => array($this, "closeTag") "close" => array($this, "closeTag")
), 0); ), 0);

View File

@ -1,13 +1,13 @@
<?php <?php
namespace Cytro; namespace Fenom;
class TagsTest extends TestCase { class TagsTest extends TestCase {
public function _testSandbox() { public function _testSandbox() {
try { try {
var_dump($this->cytro->compileCode('{for $i=0 to=5}{cycle ["one", "two"]}, {/for}')->getBody()); var_dump($this->fenom->compileCode('{for $i=0 to=5}{cycle ["one", "two"]}, {/for}')->getBody());
} catch(\Exception $e) { } catch(\Exception $e) {
echo "$e"; echo "$e";
} }

View File

@ -1,19 +1,19 @@
<?php <?php
namespace Cytro; namespace Fenom;
use Cytro\Template, use Fenom\Template,
Cytro, Fenom,
Cytro\Render; Fenom\Render;
/** /**
* Test template parsing * Test template parsing
* *
* @package Cytro * @package Fenom
*/ */
class TemplateTest extends TestCase { class TemplateTest extends TestCase {
public function setUp() { public function setUp() {
parent::setUp(); parent::setUp();
$this->cytro->addTemplate(new Render($this->cytro, function ($tpl) { $this->fenom->addTemplate(new Render($this->fenom, function ($tpl) {
echo "<b>Welcome, ".$tpl["username"]." (".$tpl["email"].")</b>"; echo "<b>Welcome, ".$tpl["username"]." (".$tpl["email"].")</b>";
}, array( }, array(
"name" => "welcome.tpl" "name" => "welcome.tpl"
@ -76,14 +76,14 @@ class TemplateTest extends TestCase {
public static function providerVarsInvalid() { public static function providerVarsInvalid() {
return array( return array(
array('hello, {$a.}!', 'Cytro\CompileException', "Unexpected end of expression"), array('hello, {$a.}!', 'Fenom\CompileException', "Unexpected end of expression"),
array('hello, {$b[c}!', 'Cytro\CompileException', "Unexpected end of expression"), array('hello, {$b[c}!', 'Fenom\CompileException', "Unexpected end of expression"),
array('hello, {$b.c]}!', 'Cytro\CompileException', "Unexpected token ']'"), array('hello, {$b.c]}!', 'Fenom\CompileException', "Unexpected token ']'"),
array('hello, {$b[ ]}!', 'Cytro\CompileException', "Unexpected token ']'"), array('hello, {$b[ ]}!', 'Fenom\CompileException', "Unexpected token ']'"),
array('hello, {$b[9/].c}!', 'Cytro\CompileException', "Unexpected token ']'"), array('hello, {$b[9/].c}!', 'Fenom\CompileException', "Unexpected token ']'"),
array('hello, {$b[3]$c}!', 'Cytro\CompileException', "Unexpected token '\$c'"), array('hello, {$b[3]$c}!', 'Fenom\CompileException', "Unexpected token '\$c'"),
array('hello, {$b[3]c}!', 'Cytro\CompileException', "Unexpected token 'c'"), array('hello, {$b[3]c}!', 'Fenom\CompileException', "Unexpected token 'c'"),
array('hello, {$b.obj->valid()}!', 'Cytro\SecurityException', "Forbidden to call methods", Cytro::DENY_METHODS), array('hello, {$b.obj->valid()}!', 'Fenom\SecurityException', "Forbidden to call methods", Fenom::DENY_METHODS),
); );
} }
@ -138,12 +138,12 @@ class TemplateTest extends TestCase {
public static function providerModifiersInvalid() { public static function providerModifiersInvalid() {
return array( return array(
array('Mod: {$lorem|}!', 'Cytro\CompileException', "Unexpected end of expression"), array('Mod: {$lorem|}!', 'Fenom\CompileException', "Unexpected end of expression"),
array('Mod: {$lorem|str_rot13}!', 'Cytro\CompileException', "Modifier str_rot13 not found", Cytro::DENY_INLINE_FUNCS), array('Mod: {$lorem|str_rot13}!', 'Fenom\CompileException', "Modifier str_rot13 not found", Fenom::DENY_INLINE_FUNCS),
array('Mod: {$lorem|my_encode}!', 'Cytro\CompileException', "Modifier my_encode not found"), array('Mod: {$lorem|my_encode}!', 'Fenom\CompileException', "Modifier my_encode not found"),
array('Mod: {$lorem|truncate:}!', 'Cytro\CompileException', "Unexpected end of expression"), array('Mod: {$lorem|truncate:}!', 'Fenom\CompileException', "Unexpected end of expression"),
array('Mod: {$lorem|truncate:abs}!', 'Cytro\CompileException', "Unexpected token 'abs'"), array('Mod: {$lorem|truncate:abs}!', 'Fenom\CompileException', "Unexpected token 'abs'"),
array('Mod: {$lorem|truncate:80|}!', 'Cytro\CompileException', "Unexpected end of expression"), array('Mod: {$lorem|truncate:80|}!', 'Fenom\CompileException', "Unexpected end of expression"),
); );
} }
@ -185,15 +185,15 @@ class TemplateTest extends TestCase {
public static function providerExpressionsInvalid() { public static function providerExpressionsInvalid() {
return array( return array(
array('If: {-"hi"} end', 'Cytro\CompileException', "Unexpected token '-'"), array('If: {-"hi"} end', 'Fenom\CompileException', "Unexpected token '-'"),
array('If: {($a++)++} end', 'Cytro\CompileException', "Unexpected token '++'"), array('If: {($a++)++} end', 'Fenom\CompileException', "Unexpected token '++'"),
array('If: {$a + * $c} end', 'Cytro\CompileException', "Unexpected token '*'"), array('If: {$a + * $c} end', 'Fenom\CompileException', "Unexpected token '*'"),
array('If: {/$a} end', 'Cytro\CompileException', "Unexpected token '\$a'"), array('If: {/$a} end', 'Fenom\CompileException', "Unexpected token '\$a'"),
array('If: {$a == 5 > 4} end', 'Cytro\CompileException', "Unexpected token '>'"), array('If: {$a == 5 > 4} end', 'Fenom\CompileException', "Unexpected token '>'"),
array('If: {$a != 5 <= 4} end', 'Cytro\CompileException', "Unexpected token '<='"), array('If: {$a != 5 <= 4} end', 'Fenom\CompileException', "Unexpected token '<='"),
array('If: {$a != 5 => 4} end', 'Cytro\CompileException', "Unexpected token '=>'"), array('If: {$a != 5 => 4} end', 'Fenom\CompileException', "Unexpected token '=>'"),
array('If: {$a + (*6)} end', 'Cytro\CompileException', "Unexpected token '*'"), array('If: {$a + (*6)} end', 'Fenom\CompileException', "Unexpected token '*'"),
array('If: {$a + ( 6} end', 'Cytro\CompileException', "Brackets don't match"), array('If: {$a + ( 6} end', 'Fenom\CompileException', "Brackets don't match"),
); );
} }
@ -230,8 +230,8 @@ class TemplateTest extends TestCase {
public static function providerIncludeInvalid() { public static function providerIncludeInvalid() {
return array( return array(
array('Include {include} template', 'Cytro\CompileException', "Unexpected end of expression"), array('Include {include} template', 'Fenom\CompileException', "Unexpected end of expression"),
array('Include {include another="welcome.tpl"} template', 'Cytro\CompileException', "Unexpected token '='"), array('Include {include another="welcome.tpl"} template', 'Fenom\CompileException', "Unexpected token '='"),
); );
} }
@ -271,10 +271,10 @@ class TemplateTest extends TestCase {
public static function providerIfInvalid() { public static function providerIfInvalid() {
return array( return array(
array('If: {if} block1 {/if} end', 'Cytro\CompileException', "Unexpected end of expression"), array('If: {if} block1 {/if} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('If: {if 1} block1 {elseif} block2 {/if} end', 'Cytro\CompileException', "Unexpected end of expression"), array('If: {if 1} block1 {elseif} block2 {/if} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('If: {if 1} block1 {else} block2 {elseif 0} block3 {/if} end', 'Cytro\CompileException', "Incorrect use of the tag {elseif}"), array('If: {if 1} block1 {else} block2 {elseif 0} block3 {/if} end', 'Fenom\CompileException', "Incorrect use of the tag {elseif}"),
array('If: {if 1} block1 {else} block2 {/if} block3 {elseif 0} end', 'Cytro\CompileException', "Unexpected tag 'elseif' (this tag can be used with 'if')"), array('If: {if 1} block1 {else} block2 {/if} block3 {elseif 0} end', 'Fenom\CompileException', "Unexpected tag 'elseif' (this tag can be used with 'if')"),
); );
} }
@ -312,20 +312,20 @@ class TemplateTest extends TestCase {
public static function providerCreateVarInvalid() { public static function providerCreateVarInvalid() {
return array( return array(
array('Create: {var $v} Result: {$v} end', 'Cytro\CompileException', "Unclosed tag: {var} opened"), array('Create: {var $v} Result: {$v} end', 'Fenom\CompileException', "Unclosed tag: {var} opened"),
array('Create: {var $v = } Result: {$v} end', 'Cytro\CompileException', "Unexpected end of expression"), array('Create: {var $v = } Result: {$v} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Create: {var $v = 1++} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '++'"), array('Create: {var $v = 1++} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '++'"),
array('Create: {var $v = c} Result: {$v} end', 'Cytro\CompileException', "Unexpected token 'c'"), array('Create: {var $v = c} Result: {$v} end', 'Fenom\CompileException', "Unexpected token 'c'"),
array('Create: {var $v = ($a)++} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '++'"), array('Create: {var $v = ($a)++} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '++'"),
array('Create: {var $v = --$a++} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '++'"), array('Create: {var $v = --$a++} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '++'"),
array('Create: {var $v = $a|upper++} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '++'"), array('Create: {var $v = $a|upper++} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '++'"),
array('Create: {var $v = max($a,2)++} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '++'"), array('Create: {var $v = max($a,2)++} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '++'"),
array('Create: {var $v = max($a,2)} Result: {$v} end', 'Cytro\CompileException', "Modifier max not found", Cytro::DENY_INLINE_FUNCS), array('Create: {var $v = max($a,2)} Result: {$v} end', 'Fenom\CompileException', "Modifier max not found", Fenom::DENY_INLINE_FUNCS),
array('Create: {var $v = 4*} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '*'"), array('Create: {var $v = 4*} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '*'"),
array('Create: {var $v = ""$a} Result: {$v} end', 'Cytro\CompileException', "Unexpected token '\$a'"), array('Create: {var $v = ""$a} Result: {$v} end', 'Fenom\CompileException', "Unexpected token '\$a'"),
array('Create: {var $v = [1,2} Result: {$v} end', 'Cytro\CompileException', "Unexpected end of expression"), array('Create: {var $v = [1,2} Result: {$v} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Create: {var $v = empty(2)} Result: {$v} end', 'Cytro\CompileException', "Unexpected token 2, isset() and empty() accept only variables"), array('Create: {var $v = empty(2)} Result: {$v} end', 'Fenom\CompileException', "Unexpected token 2, isset() and empty() accept only variables"),
array('Create: {var $v = isset(2)} Result: {$v} end', 'Cytro\CompileException', "Unexpected token 2, isset() and empty() accept only variables"), array('Create: {var $v = isset(2)} Result: {$v} end', 'Fenom\CompileException', "Unexpected token 2, isset() and empty() accept only variables"),
); );
} }
@ -418,27 +418,27 @@ class TemplateTest extends TestCase {
public static function providerForeachInvalid() { public static function providerForeachInvalid() {
return array( return array(
array('Foreach: {foreach} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected end of tag {foreach}"), array('Foreach: {foreach} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of tag {foreach}"),
array('Foreach: {foreach $list} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected end of expression"), array('Foreach: {foreach $list} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Foreach: {foreach $list+1 as $e} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '+'"), array('Foreach: {foreach $list+1 as $e} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('Foreach: {foreach array_random() as $e} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'array_random'"), array('Foreach: {foreach array_random() as $e} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'array_random'"),
array('Foreach: {foreach $list as $e+1} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '+'"), array('Foreach: {foreach $list as $e+1} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('Foreach: {foreach $list as $k+1 => $e} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '+'"), array('Foreach: {foreach $list as $k+1 => $e} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('Foreach: {foreach $list as max($i,1) => $e} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'max'"), array('Foreach: {foreach $list as max($i,1) => $e} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'max'"),
array('Foreach: {foreach $list as max($e,1)} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'max'"), array('Foreach: {foreach $list as max($e,1)} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'max'"),
array('Foreach: {foreach $list => $e} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '=>'"), array('Foreach: {foreach $list => $e} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '=>'"),
array('Foreach: {foreach $list $k => $e} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '\$k'"), array('Foreach: {foreach $list $k => $e} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '\$k'"),
array('Foreach: {foreach $list as $k =>} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected end of expression"), array('Foreach: {foreach $list as $k =>} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Foreach: {foreach last=$l $list as $e } {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'last' in tag {foreach}"), array('Foreach: {foreach last=$l $list as $e } {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'last' in tag {foreach}"),
array('Foreach: {foreach $list as $e unknown=1} {$e}, {/foreach} end', 'Cytro\CompileException', "Unknown parameter 'unknown'"), array('Foreach: {foreach $list as $e unknown=1} {$e}, {/foreach} end', 'Fenom\CompileException', "Unknown parameter 'unknown'"),
array('Foreach: {foreach $list as $e index=$i+1} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '+'"), array('Foreach: {foreach $list as $e index=$i+1} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('Foreach: {foreach $list as $e first=$f+1} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '+'"), array('Foreach: {foreach $list as $e first=$f+1} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('Foreach: {foreach $list as $e last=$l+1} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token '+'"), array('Foreach: {foreach $list as $e last=$l+1} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('Foreach: {foreach $list as $e index=max($i,1)} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'max'"), array('Foreach: {foreach $list as $e index=max($i,1)} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'max'"),
array('Foreach: {foreach $list as $e first=max($i,1)} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'max'"), array('Foreach: {foreach $list as $e first=max($i,1)} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'max'"),
array('Foreach: {foreach $list as $e last=max($i,1)} {$e}, {/foreach} end', 'Cytro\CompileException', "Unexpected token 'max'"), array('Foreach: {foreach $list as $e last=max($i,1)} {$e}, {/foreach} end', 'Fenom\CompileException', "Unexpected token 'max'"),
array('Foreach: {foreach $list as $e} {$e}, {foreachelse} {break} {/foreach} end', 'Cytro\CompileException', "Improper usage of the tag {break}"), array('Foreach: {foreach $list as $e} {$e}, {foreachelse} {break} {/foreach} end', 'Fenom\CompileException', "Improper usage of the tag {break}"),
array('Foreach: {foreach $list as $e} {$e}, {foreachelse} {continue} {/foreach} end', 'Cytro\CompileException', "Improper usage of the tag {continue}"), array('Foreach: {foreach $list as $e} {$e}, {foreachelse} {continue} {/foreach} end', 'Fenom\CompileException', "Improper usage of the tag {continue}"),
); );
} }
@ -483,9 +483,9 @@ class TemplateTest extends TestCase {
public static function providerSwitchInvalid() { public static function providerSwitchInvalid() {
return array( return array(
array('Switch: {switch}{case 1} one {break}{/switch} end', 'Cytro\CompileException', "Unexpected end of expression"), array('Switch: {switch}{case 1} one {break}{/switch} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Switch: {switch 1}{case} one {break}{/switch} end', 'Cytro\CompileException', "Unexpected end of expression"), array('Switch: {switch 1}{case} one {break}{/switch} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('Switch: {switch 1}{break}{case} one {/switch} end', 'Cytro\CompileException', "Improper usage of the tag {break}"), array('Switch: {switch 1}{break}{case} one {/switch} end', 'Fenom\CompileException', "Improper usage of the tag {break}"),
); );
} }
@ -501,7 +501,7 @@ class TemplateTest extends TestCase {
public static function providerWhileInvalid() { public static function providerWhileInvalid() {
return array( return array(
array('While: {while} block {/while} end', 'Cytro\CompileException', "Unexpected end of expression"), array('While: {while} block {/while} end', 'Fenom\CompileException', "Unexpected end of expression"),
); );
} }
@ -529,29 +529,29 @@ class TemplateTest extends TestCase {
public static function providerForInvalid() { public static function providerForInvalid() {
return array( return array(
array('For: {for} block1 {/for} end', 'Cytro\CompileException', "Unexpected end of expression"), array('For: {for} block1 {/for} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('For: {for $a=} block1 {/for} end', 'Cytro\CompileException', "Unexpected end of expression"), array('For: {for $a=} block1 {/for} end', 'Fenom\CompileException', "Unexpected end of expression"),
array('For: {for $a+1=3 to=6} block1 {/for} end', 'Cytro\CompileException', "Unexpected token '+'"), array('For: {for $a+1=3 to=6} block1 {/for} end', 'Fenom\CompileException', "Unexpected token '+'"),
array('For: {for max($a,$b)=3 to=6} block1 {/for} end', 'Cytro\CompileException', "Unexpected token 'max'"), array('For: {for max($a,$b)=3 to=6} block1 {/for} end', 'Fenom\CompileException', "Unexpected token 'max'"),
array('For: {for to=6 $a=3} block1 {/for} end', 'Cytro\CompileException', "Unexpected token 'to'"), array('For: {for to=6 $a=3} block1 {/for} end', 'Fenom\CompileException', "Unexpected token 'to'"),
array('For: {for index=$i $a=3 to=6} block1 {/for} end', 'Cytro\CompileException', "Unexpected token 'index'"), array('For: {for index=$i $a=3 to=6} block1 {/for} end', 'Fenom\CompileException', "Unexpected token 'index'"),
array('For: {for first=$i $a=3 to=6} block1 {/for} end', 'Cytro\CompileException', "Unexpected token 'first'"), array('For: {for first=$i $a=3 to=6} block1 {/for} end', 'Fenom\CompileException', "Unexpected token 'first'"),
array('For: {for last=$i $a=3 to=6} block1 {/for} end', 'Cytro\CompileException', "Unexpected token 'last'"), array('For: {for last=$i $a=3 to=6} block1 {/for} end', 'Fenom\CompileException', "Unexpected token 'last'"),
array('For: {for $a=4 to=6 unk=4} block1 {/for} end', 'Cytro\CompileException', "Unknown parameter 'unk'"), array('For: {for $a=4 to=6 unk=4} block1 {/for} end', 'Fenom\CompileException', "Unknown parameter 'unk'"),
array('For: {for $a=4 to=6} $a: {$a}, {forelse} {break} {/for} end', 'Cytro\CompileException', "Improper usage of the tag {break}"), array('For: {for $a=4 to=6} $a: {$a}, {forelse} {break} {/for} end', 'Fenom\CompileException', "Improper usage of the tag {break}"),
array('For: {for $a=4 to=6} $a: {$a}, {forelse} {continue} {/for} end', 'Cytro\CompileException', "Improper usage of the tag {continue}"), array('For: {for $a=4 to=6} $a: {$a}, {forelse} {continue} {/for} end', 'Fenom\CompileException', "Improper usage of the tag {continue}"),
); );
} }
public static function providerLayersInvalid() { public static function providerLayersInvalid() {
return array( return array(
array('Layers: {foreach $list as $e} block1 {if 1} {foreachelse} {/if} {/foreach} end', 'Cytro\CompileException', "Unexpected tag 'foreachelse' (this tag can be used with 'foreach')"), array('Layers: {foreach $list as $e} block1 {if 1} {foreachelse} {/if} {/foreach} end', 'Fenom\CompileException', "Unexpected tag 'foreachelse' (this tag can be used with 'foreach')"),
array('Layers: {foreach $list as $e} block1 {if 1} {/foreach} {/if} end', 'Cytro\CompileException', "Unexpected closing of the tag 'foreach'"), array('Layers: {foreach $list as $e} block1 {if 1} {/foreach} {/if} end', 'Fenom\CompileException', "Unexpected closing of the tag 'foreach'"),
array('Layers: {for $a=4 to=6} block1 {if 1} {forelse} {/if} {/for} end', 'Cytro\CompileException', "Unexpected tag 'forelse' (this tag can be used with 'for')"), array('Layers: {for $a=4 to=6} block1 {if 1} {forelse} {/if} {/for} end', 'Fenom\CompileException', "Unexpected tag 'forelse' (this tag can be used with 'for')"),
array('Layers: {for $a=4 to=6} block1 {if 1} {/for} {/if} end', 'Cytro\CompileException', "Unexpected closing of the tag 'for'"), array('Layers: {for $a=4 to=6} block1 {if 1} {/for} {/if} end', 'Fenom\CompileException', "Unexpected closing of the tag 'for'"),
array('Layers: {switch 1} {if 1} {case 1} {/if} {/switch} end', 'Cytro\CompileException', "Unexpected tag 'case' (this tag can be used with 'switch')"), array('Layers: {switch 1} {if 1} {case 1} {/if} {/switch} end', 'Fenom\CompileException', "Unexpected tag 'case' (this tag can be used with 'switch')"),
array('Layers: {/switch} end', 'Cytro\CompileException', "Unexpected closing of the tag 'switch'"), array('Layers: {/switch} end', 'Fenom\CompileException', "Unexpected closing of the tag 'switch'"),
array('Layers: {if 1} end', 'Cytro\CompileException', "Unclosed tag: {if}"), array('Layers: {if 1} end', 'Fenom\CompileException', "Unclosed tag: {if}"),
); );
} }

View File

@ -1,6 +1,6 @@
<?php <?php
namespace Cytro; namespace Fenom;
use Cytro\Tokenizer; use Fenom\Tokenizer;
class TokenizerTest extends \PHPUnit_Framework_TestCase { class TokenizerTest extends \PHPUnit_Framework_TestCase {
@ -54,7 +54,7 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase {
try { try {
$tokens->skip(T_STRING)->skip('(')->skip(':'); $tokens->skip(T_STRING)->skip('(')->skip(':');
} catch(\Exception $e) { } catch(\Exception $e) {
$this->assertInstanceOf('Cytro\UnexpectedTokenException', $e); $this->assertInstanceOf('Fenom\UnexpectedTokenException', $e);
$this->assertStringStartsWith("Unexpected token '3' in expression, expect ':'", $e->getMessage()); $this->assertStringStartsWith("Unexpected token '3' in expression, expect ':'", $e->getMessage());
} }
$this->assertTrue($tokens->valid()); $this->assertTrue($tokens->valid());

View File

@ -12,20 +12,20 @@ function myBlockFunc($params, $content) {
return "Block:".$params["name"].':'.trim($content).':Block'; return "Block:".$params["name"].':'.trim($content).':Block';
} }
function myCompiler(Cytro\Tokenizer $tokenizer, Cytro\Template $tpl) { function myCompiler(Fenom\Tokenizer $tokenizer, Fenom\Template $tpl) {
$p = $tpl->parseParams($tokenizer); $p = $tpl->parseParams($tokenizer);
return 'echo "PHP_VERSION: ".PHP_VERSION." (for ".'.$p["name"].'.")";'; return 'echo "PHP_VERSION: ".PHP_VERSION." (for ".'.$p["name"].'.")";';
} }
function myBlockCompilerOpen(Cytro\Tokenizer $tokenizer, Cytro\Scope $scope) { function myBlockCompilerOpen(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope) {
return myCompiler($tokenizer, $scope->tpl); return myCompiler($tokenizer, $scope->tpl);
} }
function myBlockCompilerClose(Cytro\Tokenizer $tokenizer, Cytro\Scope $scope) { function myBlockCompilerClose(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope) {
return 'echo "End of compiler";'; return 'echo "End of compiler";';
} }
function myBlockCompilerTag(Cytro\Tokenizer $tokenizer, Cytro\Scope $scope) { function myBlockCompilerTag(Fenom\Tokenizer $tokenizer, Fenom\Scope $scope) {
$p = $scope->tpl->parseParams($tokenizer); $p = $scope->tpl->parseParams($tokenizer);
return 'echo "Tag ".'.$p["name"].'." of compiler";'; return 'echo "Tag ".'.$p["name"].'." of compiler";';
} }