Skip to content

Commit

Permalink
coding style
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Feb 4, 2021
1 parent f30943e commit 76d7be1
Show file tree
Hide file tree
Showing 29 changed files with 282 additions and 143 deletions.
65 changes: 47 additions & 18 deletions src/Latte/Compiler/Compiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ public function compile(array $tokens, string $className): string
}

foreach ($tokens as $this->position => $token) {
if ($this->inHead && !($token->type === $token::COMMENT
if ($this->inHead && !(
$token->type === $token::COMMENT
|| $token->type === $token::MACRO_TAG && ($this->flags[$token->name] ?? null) & IMacro::ALLOWED_IN_HEAD
|| $token->type === $token::TEXT && trim($token->text) === ''
)) {
Expand Down Expand Up @@ -236,7 +237,9 @@ public function getFunctions(): array
*/
public function getLine(): ?int
{
return isset($this->tokens[$this->position]) ? $this->tokens[$this->position]->line : null;
return isset($this->tokens[$this->position])
? $this->tokens[$this->position]->line
: null;
}


Expand Down Expand Up @@ -295,7 +298,11 @@ public function expandTokens(string $s): string

private function processText(Token $token): void
{
if ($this->lastAttrValue === '' && $this->context && Helpers::startsWith($this->context, self::CONTEXT_HTML_ATTRIBUTE)) {
if (
$this->lastAttrValue === ''
&& $this->context
&& Helpers::startsWith($this->context, self::CONTEXT_HTML_ATTRIBUTE)
) {
$this->lastAttrValue = $token->text;
}
$this->output .= $this->escape($token->text);
Expand All @@ -304,7 +311,11 @@ private function processText(Token $token): void

private function processMacroTag(Token $token): void
{
if ($this->context === self::CONTEXT_HTML_TAG || $this->context && Helpers::startsWith($this->context, self::CONTEXT_HTML_ATTRIBUTE)) {
if (
$this->context === self::CONTEXT_HTML_TAG
|| $this->context
&& Helpers::startsWith($this->context, self::CONTEXT_HTML_ATTRIBUTE)
) {
$this->lastAttrValue = true;
}

Expand Down Expand Up @@ -419,7 +430,9 @@ private function processHtmlTagEnd(Token $token): void
(($lower = strtolower($htmlNode->name)) === 'script' || $lower === 'style')
&& (!isset($htmlNode->attrs['type']) || preg_match('#(java|j|ecma|live)script|json|css#i', $htmlNode->attrs['type']))
) {
$this->context = $lower === 'script' ? self::CONTEXT_HTML_JS : self::CONTEXT_HTML_CSS;
$this->context = $lower === 'script'
? self::CONTEXT_HTML_JS
: self::CONTEXT_HTML_CSS;
}
}

Expand Down Expand Up @@ -462,7 +475,9 @@ private function processHtmlAttributeBegin(Token $token): void
&& (in_array($lower, ['href', 'src', 'action', 'formaction'], true)
|| ($lower === 'data' && strtolower($this->htmlNode->name) === 'object'))
) {
$this->context = $this->context === self::CONTEXT_HTML_TAG ? self::CONTEXT_HTML_ATTRIBUTE_UNQUOTED_URL : self::CONTEXT_HTML_ATTRIBUTE_URL;
$this->context = $this->context === self::CONTEXT_HTML_TAG
? self::CONTEXT_HTML_ATTRIBUTE_UNQUOTED_URL
: self::CONTEXT_HTML_ATTRIBUTE_URL;
}
}

Expand Down Expand Up @@ -500,8 +515,13 @@ private function escape(string $s): string
* Generates code for {macro ...} to the output.
* @internal
*/
public function openMacro(string $name, string $args = null, string $modifiers = null, bool $isRightmost = false, string $nPrefix = null): MacroNode
{
public function openMacro(
string $name,
string $args = null,
string $modifiers = null,
bool $isRightmost = false,
string $nPrefix = null
): MacroNode {
$node = $this->expandMacro($name, $args, $modifiers, $nPrefix);
if ($node->empty) {
$this->writeCode((string) $node->openingCode, $node->replaced, $isRightmost);
Expand All @@ -522,8 +542,13 @@ public function openMacro(string $name, string $args = null, string $modifiers =
* Generates code for {/macro ...} to the output.
* @internal
*/
public function closeMacro(string $name, string $args = null, string $modifiers = null, bool $isRightmost = false, string $nPrefix = null): MacroNode
{
public function closeMacro(
string $name,
string $args = null,
string $modifiers = null,
bool $isRightmost = false,
string $nPrefix = null
): MacroNode {
$node = $this->macroNode;

if (
Expand Down Expand Up @@ -713,14 +738,21 @@ public function expandMacro(string $name, string $args, string $modifiers = null

if (strpbrk($name, '=~%^&_')) {
if (in_array($this->context, [self::CONTEXT_HTML_ATTRIBUTE_URL, self::CONTEXT_HTML_ATTRIBUTE_UNQUOTED_URL], true)) {
if (!Helpers::removeFilter($modifiers, 'nocheck') && !preg_match('#\|datastream(?=\s|\||$)#Di', $modifiers)) {
if (
!Helpers::removeFilter($modifiers, 'nocheck')
&& !preg_match('#\|datastream(?=\s|\||$)#Di', $modifiers)
) {
$modifiers .= '|checkurl';
}
}

if (!Helpers::removeFilter($modifiers, 'noescape')) {
$modifiers .= '|escape';
if ($this->context === self::CONTEXT_HTML_JS && $name === '=' && preg_match('#["\'] *$#D', $this->tokens[$this->position - 1]->text)) {
if (
$this->context === self::CONTEXT_HTML_JS
&& $name === '='
&& preg_match('#["\'] *$#D', $this->tokens[$this->position - 1]->text)
) {
throw new CompileException("Do not place {$this->tokens[$this->position]->text} inside quotes.");
}
}
Expand Down Expand Up @@ -754,11 +786,8 @@ public function expandMacro(string $name, string $args, string $modifiers = null

private static function printEndTag($node): string
{
if ($node instanceof HtmlNode) {
return "</{$node->name}> for " . Parser::N_PREFIX
. implode(' and ' . Parser::N_PREFIX, array_keys($node->macroAttrs));
} else {
return "{/$node->name}";
}
return $node instanceof HtmlNode
? "</{$node->name}> for " . Parser::N_PREFIX . implode(' and ' . Parser::N_PREFIX, array_keys($node->macroAttrs))
: "{/$node->name}";
}
}
15 changes: 11 additions & 4 deletions src/Latte/Compiler/MacroNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,18 @@ class MacroNode
public $saved;


public function __construct(IMacro $macro, string $name, string $args = null, string $modifiers = null, self $parentNode = null, HtmlNode $htmlNode = null, string $prefix = null)
{
public function __construct(
IMacro $macro,
string $name,
string $args = null,
string $modifiers = null,
self $parentNode = null,
HtmlNode $htmlNode = null,
string $prefix = null
) {
$this->macro = $macro;
$this->name = (string) $name;
$this->modifiers = (string) $modifiers;
$this->name = $name;
$this->modifiers = $modifiers;
$this->parentNode = $parentNode;
$this->htmlNode = $htmlNode;
$this->prefix = $prefix;
Expand Down
2 changes: 1 addition & 1 deletion src/Latte/Compiler/MacroTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public function append($val, int $position = null)
if ($val != null) { // intentionally @
array_splice(
$this->tokens,
$position === null ? count($this->tokens) : $position,
$position ?? count($this->tokens),
0,
is_array($val) ? [$val] : $this->parse($val)
);
Expand Down
10 changes: 8 additions & 2 deletions src/Latte/Compiler/Parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ private function contextHtmlText()

if (!empty($matches['htmlcomment'])) { // <! <?
$this->addToken(Token::HTML_TAG_BEGIN, $matches[0]);
$end = $matches['htmlcomment'] === '!--' ? '--' : ($matches['htmlcomment'] === '?' && $this->xmlMode ? '\?' : '');
$end = $matches['htmlcomment'] === '!--'
? '--'
: ($matches['htmlcomment'] === '?' && $this->xmlMode ? '\?' : '');
$this->setContext(self::CONTEXT_HTML_COMMENT, $end);

} elseif (!empty($matches['tag'])) { // <tag or </tag
Expand Down Expand Up @@ -444,7 +446,11 @@ protected function filter(Token $token): void
} elseif ($token->type === Token::HTML_TAG_BEGIN && $this->lastHtmlTag === $this->syntaxEndTag) {
$this->syntaxEndLevel++;

} elseif ($token->type === Token::HTML_TAG_END && $this->lastHtmlTag === ('/' . $this->syntaxEndTag) && --$this->syntaxEndLevel === 0) {
} elseif (
$token->type === Token::HTML_TAG_END
&& $this->lastHtmlTag === ('/' . $this->syntaxEndTag)
&& --$this->syntaxEndLevel === 0
) {
$this->setSyntax($this->defaultSyntax);

} elseif ($token->type === Token::MACRO_TAG && $token->name === 'contentType') {
Expand Down
94 changes: 54 additions & 40 deletions src/Latte/Compiler/PhpWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,39 +69,42 @@ public function write(string $mask, ...$args): string
}
}

$code = preg_replace_callback('#([,+]\s*)?%(node_|\d+_|)(word|var|raw|array|args)(\?)?(\s*\+\s*)?()#',
function ($m) use ($word, &$args) {
[, $l, $source, $format, $cond, $r] = $m;

switch ($source) {
case 'node_':
$arg = $word; break;
case '':
$arg = current($args); next($args); break;
default:
$arg = $args[(int) $source]; break;
}
$code = preg_replace_callback(
'#([,+]\s*)?%(node_|\d+_|)(word|var|raw|array|args)(\?)?(\s*\+\s*)?()#',
function ($m) use ($word, &$args) {
[, $l, $source, $format, $cond, $r] = $m;

switch ($source) {
case 'node_':
$arg = $word; break;
case '':
$arg = current($args); next($args); break;
default:
$arg = $args[(int) $source]; break;
}

switch ($format) {
case 'word':
$code = $this->formatWord($arg); break;
case 'args':
$code = $this->formatArgs(); break;
case 'array':
$code = $this->formatArray();
$code = $cond && $code === '[]' ? '' : $code; break;
case 'var':
$code = var_export($arg, true); break;
case 'raw':
$code = (string) $arg; break;
}
switch ($format) {
case 'word':
$code = $this->formatWord($arg); break;
case 'args':
$code = $this->formatArgs(); break;
case 'array':
$code = $this->formatArray();
$code = $cond && $code === '[]' ? '' : $code; break;
case 'var':
$code = var_export($arg, true); break;
case 'raw':
$code = (string) $arg; break;
}

if ($cond && $code === '') {
return $r ? $l : $r;
} else {
return $l . $code . $r;
}
}, $mask);
if ($cond && $code === '') {
return $r ? $l : $r;
} else {
return $l . $code . $r;
}
},
$mask
);

$this->tokens->position = $pos;
return $code;
Expand Down Expand Up @@ -160,7 +163,7 @@ public function formatWord(string $s): string
*/
public function preprocess(MacroTokens $tokens = null): MacroTokens
{
$tokens = $tokens === null ? $this->tokens : $tokens;
$tokens = $tokens ?? $this->tokens;
$this->validateTokens($tokens);
$tokens = $this->removeCommentsPass($tokens);
$tokens = $this->replaceFunctionsPass($tokens);
Expand Down Expand Up @@ -262,7 +265,10 @@ public function shortTernaryPass(MacroTokens $tokens): MacroTokens
array_pop($inTernary);
array_pop($tmp);

} elseif ($tokens->isCurrent(',', ')', ']', '|') && end($inTernary) === $tokens->depth + $tokens->isCurrent(')', ']')) {
} elseif (
$tokens->isCurrent(',', ')', ']', '|')
&& end($inTernary) === $tokens->depth + $tokens->isCurrent(')', ']')
) {
$res->append(' : null');
array_pop($inTernary);
$errors += array_pop($tmp);
Expand Down Expand Up @@ -302,7 +308,13 @@ public function optionalChainingPass(MacroTokens $tokens): MacroTokens

do {
if ($tokens->nextToken('?')) {
if ($tokens->isNext() && (!$tokens->isNext($tokens::T_CHAR) || $tokens->isNext('(', '[', '{', ':', '!', '@', '\\'))) { // is it ternary operator?
if (
$tokens->isNext()
&& (
!$tokens->isNext($tokens::T_CHAR)
|| $tokens->isNext('(', '[', '{', ':', '!', '@', '\\')
)
) { // is it ternary operator?
$expr->append($addBraces . ' ?');
break;
}
Expand Down Expand Up @@ -385,12 +397,13 @@ public function quotingPass(MacroTokens $tokens): MacroTokens
{
$res = new MacroTokens;
while ($tokens->nextToken()) {
$res->append($tokens->isCurrent($tokens::T_SYMBOL)
$res->append(
$tokens->isCurrent($tokens::T_SYMBOL)
&& (!$tokens->isPrev() || $tokens->isPrev(',', '(', '[', '=>', ':', '?', '.', '<', '>', '<=', '>=', '===', '!==', '==', '!=', '<>', '&&', '||', '=', 'and', 'or', 'xor', '??'))
&& (!$tokens->isNext() || $tokens->isNext(',', ';', ')', ']', '=>', ':', '?', '.', '<', '>', '<=', '>=', '===', '!==', '==', '!=', '<>', '&&', '||', 'and', 'or', 'xor', '??'))
&& !preg_match('#^[A-Z_][A-Z0-9_]{2,}$#', $tokens->currentValue())
? "'" . $tokens->currentValue() . "'"
: $tokens->currentToken()
? "'" . $tokens->currentValue() . "'"
: $tokens->currentToken()
);
}
return $res;
Expand Down Expand Up @@ -532,9 +545,10 @@ public function modifierPass(MacroTokens $tokens, $var, bool $isContent = false)
$inside = true;
} else {
$name = strtolower($tokens->currentValue());
$res->prepend($isContent
? '$this->filters->filterContent(' . var_export($name, true) . ', $_fi, '
: '($this->filters->' . $name . ')('
$res->prepend(
$isContent
? '$this->filters->filterContent(' . var_export($name, true) . ', $_fi, '
: '($this->filters->' . $name . ')('
);
$inside = true;
}
Expand Down
18 changes: 15 additions & 3 deletions src/Latte/Compiler/TokenIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,14 @@ protected function next(): void
* @param array $wanted of desired token types or values
* @return mixed
*/
protected function scan(array $wanted, bool $onlyFirst, bool $advance, bool $strings = false, bool $until = false, bool $prev = false)
{
protected function scan(
array $wanted,
bool $onlyFirst,
bool $advance,
bool $strings = false,
bool $until = false,
bool $prev = false
) {
$res = $onlyFirst ? null : ($strings ? '' : []);
$pos = $this->position + ($prev ? -1 : 1);
do {
Expand All @@ -202,7 +208,13 @@ protected function scan(array $wanted, bool $onlyFirst, bool $advance, bool $str
}

$token = $this->tokens[$pos];
if (!$wanted || (in_array($token[Tokenizer::VALUE], $wanted, true) || in_array($token[Tokenizer::TYPE], $wanted, true)) ^ $until) {
if (
!$wanted
|| (
in_array($token[Tokenizer::VALUE], $wanted, true)
|| in_array($token[Tokenizer::TYPE], $wanted, true)
) ^ $until
) {
while ($advance && !$prev && $pos > $this->position) {
$this->next();
}
Expand Down
10 changes: 8 additions & 2 deletions src/Latte/Engine.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ public function compile(string $name): string
if (!$e instanceof CompileException) {
$e = new CompileException("Thrown exception '{$e->getMessage()}'", 0, $e);
}
$line = isset($tokens) ? $this->getCompiler()->getLine() : $this->getParser()->getLine();
$line = isset($tokens)
? $this->getCompiler()->getLine()
: $this->getParser()->getLine();
throw $e->setSource($source, $line, $name);
}

Expand Down Expand Up @@ -179,7 +181,11 @@ private function loadTemplate(string $name): void
return;
}

if (!is_dir($this->tempDirectory) && !@mkdir($this->tempDirectory) && !is_dir($this->tempDirectory)) { // @ - dir may already exist
if (
!is_dir($this->tempDirectory)
&& !@mkdir($this->tempDirectory)
&& !is_dir($this->tempDirectory)
) { // @ - dir may already exist
throw new \RuntimeException("Unable to create directory '$this->tempDirectory'. " . error_get_last()['message']);
}

Expand Down
Loading

0 comments on commit 76d7be1

Please sign in to comment.