Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Latte 3 #70

Merged
merged 3 commits into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions .phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@
<rule ref="PSR1.Classes.ClassDeclaration.MultipleClasses">
<exclude-pattern>src/compatibility.php</exclude-pattern>
</rule>
<exclude-pattern>tests/PHPStan/latte-compatibility.php</exclude-pattern>
</ruleset>
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"nette/utils": "^3.2@dev",
"nette/forms": "^3.1@dev",
"nette/application": "^3.1.4@dev",
"latte/latte": "^2.9@dev"
"latte/latte": "^2.9@dev || ^3.0@dev"
},
"require-dev": {
"nette/tester": "2.4.2",
Expand Down Expand Up @@ -59,7 +59,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "1.9-dev"
"dev-master": "1.10-dev"
}
}
}
4 changes: 4 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ includes:
- vendor/spaze/phpstan-disallowed-calls/disallowed-insecure-calls.neon
- vendor/spaze/phpstan-disallowed-calls/disallowed-loose-calls.neon
- tests/PHPStan/disallowedCalls.neon
- tests/PHPStan/conditional.config.php

parameters:
level: max
Expand All @@ -23,6 +24,9 @@ parameters:
- LogicException
- Nette\InvalidStateException

bootstrapFiles:
- tests/PHPStan/latte-compatibility.php

ignoreErrors:
-
message: '#If condition is always false#'
Expand Down
2 changes: 2 additions & 0 deletions phpstan.tests.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@ parameters:

excludePaths:
- tests/temp/*
- tests/PHPStan/conditional.config.php
- tests/PHPStan/latte-compatibility.php
21 changes: 21 additions & 0 deletions src/FormRenderer/LatteExtensions/FormRendererLatteExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
declare(strict_types = 1);

namespace Nepada\FormRenderer\LatteExtensions;

use Latte;

final class FormRendererLatteExtension extends Latte\Extension
{

/**
* @return array<string, callable(Latte\Compiler\Tag, Latte\Compiler\TemplateParser): (Latte\Compiler\Node|\Generator|void)|\stdClass>
*/
public function getTags(): array
{
return [
'n:class' => [Nodes\NClassNode::class, 'create'],
];
}

}
51 changes: 51 additions & 0 deletions src/FormRenderer/LatteExtensions/Nodes/NClassNode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php
declare(strict_types = 1);

namespace Nepada\FormRenderer\LatteExtensions\Nodes;

use Latte\CompileException;
use Latte\Compiler\Nodes\Php\Expression\ArrayNode;
use Latte\Compiler\Nodes\StatementNode;
use Latte\Compiler\PrintContext;
use Latte\Compiler\Tag;
use Nepada\FormRenderer\Helpers;

/**
* Improved version of `n:class="..."` that supports array arguments, e.g. `n:class="firstClass, $condition ? [foo => true, bar => true], anotherClass"`.
* This is especially useful in combination with instances of Nette\Utils\Html, so you can do stuff like `n:class="foo, $el->class"`.
*/
final class NClassNode extends StatementNode
{

public ArrayNode $args;

/**
* @param Tag $tag
* @throws CompileException
*/
public static function create(Tag $tag): self
{
if ($tag->htmlElement !== null && $tag->htmlElement->getAttribute('class') !== null) {
throw new CompileException('It is not possible to combine class with n:class.', $tag->position);
}

$tag->expectArguments();
$node = new NClassNode();
$node->args = $tag->parser->parseArguments();
return $node;
}

public function print(PrintContext $context): string
{
$classListCode = '$ʟ_tmp = array_filter(array_merge(...array_map([\'' . Helpers::class . '\', \'parseClassList\'], %node)))';
$code = 'if (' . $classListCode . ') echo \' class="\', LR\Filters::escapeHtmlAttr(implode(\' \', array_unique($ʟ_tmp))), \'"\' %line;';

return $context->format($code, $this->args, $this->position);
}

public function &getIterator(): \Generator
{
yield $this->args;
}

}
11 changes: 8 additions & 3 deletions src/FormRenderer/TemplateRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use Latte;
use Nepada\FormRenderer\Filters\SafeTranslateFilterFactory;
use Nepada\FormRenderer\LatteExtensions\FormRendererLatteExtension;
use Nette;

class TemplateRenderer implements Nette\Forms\FormRenderer
Expand Down Expand Up @@ -71,9 +72,13 @@ private function createTemplate(): Nette\Bridges\ApplicationLatte\Template
}

$latte = $template->getLatte();
$latte->onCompile[] = function (Latte\Engine $latte): void {
Macros\FormRendererMacros::install($latte->getCompiler());
};
if (version_compare(Latte\Engine::VERSION, '3', '<')) {
$latte->onCompile[] = function (Latte\Engine $latte): void {
Macros\FormRendererMacros::install($latte->getCompiler());
};
} else {
$latte->addExtension(new FormRendererLatteExtension());
}

return $template;
}
Expand Down
6 changes: 3 additions & 3 deletions src/FormRenderer/templates/bootstrap4.latte
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@
$control->getControlPrototype()->class,
form-control,
($control|validationClass)
"/>
" />
{/define}

{define #input-type-select}
Expand Down Expand Up @@ -185,7 +185,7 @@
<label n:name="$control:" n:class="
$control->getLabelPrototype()->class,
$useCustomControls ? custom-control-label : form-check-label
"/>
" />
</div>
{/define}

Expand All @@ -202,7 +202,7 @@
<label n:name="$control:" n:class="
$control->getLabelPrototype()->class,
$useCustomControls ? custom-control-label : form-check-label
"/>
" />
</div>
{/define}

Expand Down
11 changes: 7 additions & 4 deletions src/FormRenderer/templates/default.latte
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,15 @@
{/define}

{define #controls}
{if}
<table n:inner-foreach="$group->getControls() as $control">
{try}
<table>
{foreach $group->getControls() as $control}
{continueIf $control->getOption('rendered') || $control->getOption('type') === 'hidden'}
{include #helpers-override-split, blockNamePrefix => pair, control => $control, parameters => [controlsIterator => $iterator]}
</table>
{/if $iterations}
{else}{rollback}
{/foreach}
</table>
{/try}
{/define}

{define #pair-type-default}
Expand Down
41 changes: 37 additions & 4 deletions tests/FormRenderer/HtmlAssert.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
namespace NepadaTests\FormRenderer;

use Nette;
use Nette\Utils\Strings;
use Tester\Assert;

final class HtmlAssert
Expand All @@ -14,14 +15,46 @@ final class HtmlAssert
public static function matchFile(string $file, string $actual, ?string $description = null): void
{
$expected = Nette\Utils\FileSystem::read($file);
Assert::match(self::normalizeWhiteSpace($expected), self::normalizeWhiteSpace($actual), $description);
Assert::match(self::normalize($expected), self::normalize($actual), $description);
}

private static function normalize(string $content): string
{
$content = self::normalizeWhiteSpace($content);
$content = self::normalizeHtmlAttributes($content);
$content = self::normalizeFormEnd($content);
return $content;
}

private static function normalizeWhiteSpace(string $content): string
{
$content = Nette\Utils\Strings::normalizeNewLines($content);
$content = Nette\Utils\Strings::replace($content, '~^[\t ]+|[\t ]+$~m', ''); // remove leading and trailing whitespace
$content = Nette\Utils\Strings::replace($content, "~\n+~", "\n"); // remove empty lines
$content = Strings::normalizeNewLines($content);
$content = Strings::replace($content, '~^[\t ]+|[\t ]+$~m', ''); // remove leading and trailing whitespace
$content = Strings::replace($content, "~\n+~", "\n"); // remove empty lines
return $content;
}

private static function normalizeHtmlAttributes(string $content): string
{
$content = Strings::replace(
$content,
'~(<[^>\s]+)\s*([^>]*?)\s*(/?>)~m',
function (array $matches): string {
$attributes = Strings::matchAll($matches[2], '~[^=\s]+(?:=(?:\'[^\']*\'|"[^"]*"))?~', PREG_PATTERN_ORDER)[0] ?? [];
$serializedAttributes = '';
if ($attributes !== []) {
sort($attributes);
$serializedAttributes = ' ' . implode(' ', $attributes);
}
return $matches[1] . $serializedAttributes . $matches[3];
},
);
return $content;
}

private static function normalizeFormEnd(string $content): string
{
$content = Strings::replace($content, '~>\s*</form>~m', ">\n</form>"); // remove whitespace difference between Latte 2 and Latte 3
return $content;
}

Expand Down
38 changes: 38 additions & 0 deletions tests/PHPStan/conditional.config.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php
declare(strict_types = 1);

$config = [];

if (version_compare(Latte\Engine::VERSION, '3.0', '<')) {
$config['parameters']['excludePaths']['analyse'][] = __DIR__ . '/../../src/FormRenderer/LatteExtensions/FormRendererLatteExtension.php';
$config['parameters']['excludePaths']['analyse'][] = __DIR__ . '/../../src/FormRenderer/LatteExtensions/Nodes/NClassNode.php';
$config['parameters']['ignoreErrors'][] = [
'message' => '~If condition is always true\\.~',
'path' => '../../src/FormRenderer/TemplateRenderer.php',
'count' => 1,
];
$config['parameters']['ignoreErrors'][] = [
'message' => '~Call to an undefined method Latte\\\\Engine::addExtension\\(\\)\\.~',
'path' => '../../src/FormRenderer/TemplateRenderer.php',
'count' => 1,
];
} else {
$config['parameters']['excludePaths']['analyse'][] = __DIR__ . '/../../src/FormRenderer/Macros/FormRendererMacros.php';
$config['parameters']['ignoreErrors'][] = [
'message' => '~If condition is always false\\.~',
'path' => '../../src/FormRenderer/TemplateRenderer.php',
'count' => 1,
];
$config['parameters']['ignoreErrors'][] = [
'message' => '~Access to an undefined property Latte\\\\Engine::\\$onCompile\\.~',
'path' => '../../src/FormRenderer/TemplateRenderer.php',
'count' => 1,
];
$config['parameters']['ignoreErrors'][] = [
'message' => '~Call to an undefined method Latte\\\\Engine::getCompiler\\(\\)\\.~',
'path' => '../../src/FormRenderer/TemplateRenderer.php',
'count' => 1,
];
}

return $config;
28 changes: 28 additions & 0 deletions tests/PHPStan/latte-compatibility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php
declare(strict_types = 1);

namespace Latte {

if (version_compare(\Latte\Engine::VERSION, '3.0', '<')) {

class Extension
{

}

}

}

namespace Latte\Macros {

if (!version_compare(\Latte\Engine::VERSION, '3.0', '<')) {

class MacroSet
{

}

}

}