Add licenses

This commit is contained in:
bzick 2013-04-28 18:08:57 +04:00
parent 614428e88d
commit 5a1097d5a6
22 changed files with 91 additions and 47 deletions

View File

@ -1,7 +1,7 @@
Cytro - awesome template engine for PHP
==========================
> Composer package: `{"bzick/cytro": "dev-master"}`. See on [Packagist.org](https://packagist.org/packages/bzick/aspect)
> Composer package: `{"bzick/cytro": "dev-master"}`. See on [Packagist.org](https://packagist.org/packages/bzick/cytro)
[![Build Status](https://travis-ci.org/bzick/aspect.png?branch=master)](https://travis-ci.org/bzick/cytro)
## [About](./docs/about.md) :: [Documentation](./docs/main.md) :: [Benchmark](./docs/benchmark.md) :: [Articles](./docs/articles.md)

3
authors.md Normal file
View File

@ -0,0 +1,3 @@
Project Founder and Developer:
- Ivan Shalganov <ivan.shalganov@gmail.com>

View File

@ -13,9 +13,9 @@ Benchmark::run("twig", 'echo/twig.tpl', __DIR__.'/echo/data.json', false, '!comp
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("aspect", 'echo/smarty.tpl', __DIR__.'/echo/data.json', false, '!compiled and !loaded');
Benchmark::run("aspect", 'echo/smarty.tpl', __DIR__.'/echo/data.json', false, 'compiled and !loaded');
Benchmark::run("aspect", 'echo/smarty.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');

View File

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

View File

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

View File

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

View File

@ -84,7 +84,7 @@ See also [security options](./settings.md)
### Scalar values
Строки в Aspect обрабатываются идентично правилам подстановки переменных в строки в PHP, т.е. в двойных кавычках переменная заменяется на её значение, в одинарных замены не происходит.
Строки в Cytro обрабатываются идентично правилам подстановки переменных в строки в PHP, т.е. в двойных кавычках переменная заменяется на её значение, в одинарных замены не происходит.
```smarty
{var $foo="Username"}
@ -185,11 +185,11 @@ See also [security options](./settings.md)
### Ignoring temaplate code
В шаблонизаторе Aspect используются фигурные скобки для отделения HTML от кода Aspect.
В шаблонизаторе Cytro используются фигурные скобки для отделения HTML от кода Cytro.
Если требуется вывести текст, содержащий фигурные скобки помните о следующих возможностях:
1. Использование блочного тега `{ignore}{/ignore}`. Текст внутри этого тега текст не компилируется шаблонизатором и выводится как есть.
2. Если после открывающей фигурной скобки есть пробельный символ (пробел или `\t`) или перенос строки (`\r` или `\n`), то она не воспринимается как разделитель rкода Aspect и код после неё выводится как есть.
2. Если после открывающей фигурной скобки есть пробельный символ (пробел или `\t`) или перенос строки (`\r` или `\n`), то она не воспринимается как разделитель rкода Cytro и код после неё выводится как есть.
Пример:

View File

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

31
license.md Normal file
View File

@ -0,0 +1,31 @@
Copyright (c) 2013 by Ivan Shalganov.
Some rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* The names of the contributors may not be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
use Cytro\Template,
@ -223,12 +223,12 @@ class Cytro {
} else {
throw new InvalidArgumentException("Source must be a valid path or provider object");
}
$aspect = new static($provider);
$aspect->setCompileDir($compile_dir);
$cytro = new static($provider);
$cytro->setCompileDir($compile_dir);
if($options) {
$aspect->setOptions($options);
$cytro->setOptions($options);
}
return $aspect;
return $cytro;
}
/**
@ -610,7 +610,7 @@ class Cytro {
if(!is_file($this->_compile_dir."/".$file_name)) {
return $this->compile($tpl);
} else {
$aspect = $this;
$cytro = $this;
return include($this->_compile_dir."/".$file_name);
}
}

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;
@ -67,17 +67,18 @@ class Template extends Render {
/**
* Just factory
*
* @param \Cytro $aspect
* @param \Cytro $cytro
* @param $options
* @return Template
*/
public static function factory(Cytro $aspect, $options) {
return new static($aspect, $options);
public static function factory(Cytro $cytro, $options) {
return new static($cytro, $options);
}
/**
* @param Cytro $cytro Template storage
* @param $options
* @param int $options
* @return \Cytro\Template
*/
public function __construct(Cytro $cytro, $options) {
$this->_cytro = $cytro;
@ -88,7 +89,7 @@ class Template extends Render {
* Load source from provider
* @param string $name
* @param bool $compile
* @return \Cytro\Template
* @return $this
*/
public function load($name, $compile = true) {
$this->_name = $name;
@ -214,7 +215,17 @@ class Template extends Render {
* @param string $text
*/
private function _appendText($text) {
$this->_body .= str_replace("<?", '<?php echo "<?"; ?>'.PHP_EOL, $text);
if($this->_filter) {
if(strpos($text, "<?") === false) {
foreach(explode("<?", $text) as $fragment) {
}
} else {
$this->_body .= $text;
}
} else {
$this->_body .= str_replace("<?", '<?php echo "<?"; ?>'.PHP_EOL, $text);
}
}
/**
@ -277,7 +288,7 @@ class Template extends Render {
public function getTemplateCode() {
return "<?php \n".
"/** Cytro template '".$this->_name."' compiled at ".date('Y-m-d H:i:s')." */\n".
"return new Cytro\\Render(\$aspect, ".$this->_getClosureSource().", ".var_export(array(
"return new Cytro\\Render(\$cytro, ".$this->_getClosureSource().", ".var_export(array(
"options" => $this->_options,
"provider" => $this->_scm,
"name" => $this->_name,

View File

@ -4,7 +4,7 @@
*
* (c) 2013 Ivan Shalganov
*
* For the full copyright and license information, please view the LICENSE
* For the full copyright and license information, please view the license.md
* file that was distributed with this source code.
*/
namespace Cytro;
@ -32,8 +32,7 @@ defined('T_YIELD') || define('T_YIELD', 370);
* @property array $curr the current token
* @property array $next the next token
*
* @package aspect
* @author Ivan Shalganov <owner@bzick.net>
* @package Cytro
*/
class Tokenizer {
const TOKEN = 0;

View File

@ -147,7 +147,7 @@ class ExtendsTemplateTest extends TestCase {
// * @group extends
// */
// public function _testParentLevel() {
// //echo($this->aspect->getTemplate("parent.tpl")->_body); exit;
// //echo($this->cytro->getTemplate("parent.tpl")->_body); exit;
// $this->assertSame($this->cytro->fetch("parent.tpl", array("a" => "a char")), "Parent template\nBlock1: Block2: Block3: default");
// }
//
@ -155,7 +155,7 @@ class ExtendsTemplateTest extends TestCase {
// * @group extends
// */
// public function testChildLevel1() {
// //echo($this->aspect->fetch("child1.tpl", array("a" => "a char"))); exit;
// //echo($this->cytro->fetch("child1.tpl", array("a" => "a char"))); exit;
// }
//
// /**

View File

@ -17,7 +17,7 @@ class ScopeTest extends TestCase {
}
public function testBlock() {
/*$scope = new Scope($this->aspect, new Template($this->aspect), 1, array(
/*$scope = new Scope($this->cytro, new Template($this->cytro), 1, array(
"open" => array($this, "openTag"),
"close" => array($this, "closeTag")
), 0);

View File

@ -16,7 +16,7 @@ class TemplateTest extends TestCase {
}
/*public function testSandbox() {
var_dump($this->aspect->compileCode('{"$s:{$b+1}f d {$d}"}')->_body);
var_dump($this->cytro->compileCode('{"$s:{$b+1}f d {$d}"}')->_body);
exit;
}*/

View File

@ -36,9 +36,9 @@ class CytroTest extends \Cytro\TestCase {
public function testStorage() {
$this->tpl('custom.tpl', 'Custom template');
$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array()));
//$this->aspect->clearCompiledTemplate('custom.tpl', false);
//$this->cytro->clearCompiledTemplate('custom.tpl', false);
//$this->assertSame("Custom template", $this->aspect->fetch('custom.tpl', array()));
//$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array()));
$this->tpl('custom.tpl', 'Custom template 2');
$this->assertSame("Custom template", $this->cytro->fetch('custom.tpl', array()));