Skip to content

Commit 8aac53f

Browse files
authored
Merge pull request #51 from pug-php/feature/lazy-engine
Postpone engine initialization
2 parents d2f2dc9 + 5c5e64a commit 8aac53f

File tree

6 files changed

+109
-78
lines changed

6 files changed

+109
-78
lines changed

src/Pug/PugSymfonyEngine.php

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ protected function crawlDirectories(string $srcDir, array &$assetsDirectories, a
8282
}
8383

8484
if (is_dir($viewDirectory = $srcDir.'/'.$directory.'/Resources/views')) {
85-
if (is_null($baseDir)) {
85+
if ($baseDir === null) {
8686
$baseDir = $viewDirectory;
8787
}
8888

@@ -131,7 +131,15 @@ protected function getFileFromName(string $name, string $directory = null): stri
131131
*/
132132
public function share($variables, $value = null): self
133133
{
134-
$this->getRenderer()->share(...func_get_args());
134+
if (func_num_args() === 2) {
135+
$variables = [
136+
$variables => $value,
137+
];
138+
}
139+
140+
$variables = array_merge($this->getOptionDefault('shared_variables', []), $variables);
141+
142+
$this->setOption('shared_variables', $variables);
135143

136144
return $this;
137145
}
@@ -155,7 +163,11 @@ public function getCacheDir(): string
155163
*/
156164
public function getParameters(array $locals = []): array
157165
{
158-
$locals = array_merge($this->getOptionDefault('shared_variables'), $locals);
166+
$locals = array_merge(
167+
$this->getOptionDefault('globals', []),
168+
$this->getOptionDefault('shared_variables', []),
169+
$locals
170+
);
159171

160172
foreach (['context', 'blocks', 'macros', 'this'] as $forbiddenKey) {
161173
if (array_key_exists($forbiddenKey, $locals)) {
@@ -235,7 +247,7 @@ public function exists($name): bool
235247
*/
236248
public function supports($name): bool
237249
{
238-
foreach ($this->getOptionDefault('extensions', []) as $extension) {
250+
foreach ($this->getOptionDefault('extensions', ['.pug', '.jade']) as $extension) {
239251
if (substr($name, -strlen($extension)) === $extension) {
240252
return true;
241253
}

src/Pug/Symfony/Traits/HelpersHandler.php

Lines changed: 53 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -69,23 +69,6 @@ trait HelpersHandler
6969
*/
7070
protected $nodeHandler;
7171

72-
/**
73-
* @var array
74-
*/
75-
protected $templatingHelpers = [
76-
'actions',
77-
'assets',
78-
'code',
79-
'form',
80-
'request',
81-
'router',
82-
'security',
83-
'session',
84-
'slots',
85-
'stopwatch',
86-
'translator',
87-
];
88-
8972
/**
9073
* Get the Pug engine.
9174
*
@@ -94,10 +77,7 @@ trait HelpersHandler
9477
public function getRenderer(): Pug
9578
{
9679
if ($this->pug === null) {
97-
$cache = $this->getCacheDir();
98-
(new Filesystem())->mkdir($cache);
99-
100-
$this->pug = $this->createEngine($this->getRendererOptions($cache));
80+
$this->pug = $this->createEngine($this->getRendererOptions());
10181
$this->copyTwigFunctions();
10282
$this->initializePugPlugins();
10383
$this->share($this->getTwig()->getGlobals());
@@ -112,51 +92,60 @@ public function onNode(callable $nodeHandler): void
11292
$this->nodeHandler = $nodeHandler;
11393
}
11494

115-
protected function getRendererOptions(string $cache): array
95+
protected function getRendererOptions(): array
11696
{
117-
$environment = $this->kernel->getEnvironment();
118-
$projectDirectory = $this->kernel->getProjectDir();
119-
$assetsDirectories = [$projectDirectory.'/Resources/assets'];
120-
$viewDirectories = [$projectDirectory.'/templates'];
121-
122-
if (($loader = $this->getTwig()->getLoader()) instanceof FilesystemLoader &&
123-
is_array($paths = $loader->getPaths()) &&
124-
isset($paths[0])
125-
) {
126-
$viewDirectories[] = $paths[0];
127-
}
97+
if ($this->options === null) {
98+
$environment = $this->kernel->getEnvironment();
99+
$projectDirectory = $this->kernel->getProjectDir();
100+
$assetsDirectories = [$projectDirectory.'/Resources/assets'];
101+
$viewDirectories = [$projectDirectory.'/templates'];
102+
103+
if (($loader = $this->getTwig()->getLoader()) instanceof FilesystemLoader &&
104+
is_array($paths = $loader->getPaths()) &&
105+
isset($paths[0])
106+
) {
107+
$viewDirectories[] = $paths[0];
108+
}
128109

129-
$srcDir = $projectDirectory.'/src';
130-
$webDir = $projectDirectory.'/public';
131-
$baseDir = isset($this->userOptions['baseDir'])
132-
? $this->userOptions['baseDir']
133-
: $this->crawlDirectories($srcDir, $assetsDirectories, $viewDirectories);
134-
$baseDir = $baseDir && file_exists($baseDir) ? realpath($baseDir) : $baseDir;
135-
$this->defaultTemplateDirectory = $baseDir;
110+
$srcDir = $projectDirectory.'/src';
111+
$webDir = $projectDirectory.'/public';
112+
$baseDir = isset($this->userOptions['baseDir'])
113+
? $this->userOptions['baseDir']
114+
: $this->crawlDirectories($srcDir, $assetsDirectories, $viewDirectories);
115+
$baseDir = $baseDir && file_exists($baseDir) ? realpath($baseDir) : $baseDir;
116+
$this->defaultTemplateDirectory = $baseDir;
136117

137-
if (isset($this->userOptions['paths'])) {
138-
$viewDirectories = array_merge($viewDirectories, $this->userOptions['paths'] ?: []);
118+
if (isset($this->userOptions['paths'])) {
119+
$viewDirectories = array_merge($viewDirectories, $this->userOptions['paths'] ?: []);
120+
}
121+
122+
$debug = $this->kernel->isDebug();
123+
$options = array_merge([
124+
'debug' => $debug,
125+
'assetDirectory' => static::extractUniquePaths($assetsDirectories),
126+
'viewDirectories' => static::extractUniquePaths($viewDirectories),
127+
'baseDir' => $baseDir,
128+
'cache' => $debug ? false : $this->getCacheDir(),
129+
'environment' => $environment,
130+
'extension' => ['.pug', '.jade'],
131+
'outputDirectory' => $webDir,
132+
'prettyprint' => $debug,
133+
'on_node' => $this->nodeHandler,
134+
], $this->userOptions);
135+
$cache = $options['cache'] ?? $options['cache_dir'] ?? null;
136+
137+
if ($cache) {
138+
(new Filesystem())->mkdir($cache);
139+
}
140+
141+
$options['paths'] = array_unique(array_filter($options['viewDirectories'], function ($path) use ($baseDir) {
142+
return $path !== $baseDir;
143+
}));
144+
145+
$this->options = $options;
139146
}
140147

141-
$debug = $this->kernel->isDebug();
142-
$options = array_merge([
143-
'debug' => $debug,
144-
'assetDirectory' => static::extractUniquePaths($assetsDirectories),
145-
'viewDirectories' => static::extractUniquePaths($viewDirectories),
146-
'baseDir' => $baseDir,
147-
'cache' => $debug ? false : $cache,
148-
'environment' => $environment,
149-
'extension' => ['.pug', '.jade'],
150-
'outputDirectory' => $webDir,
151-
'prettyprint' => $debug,
152-
'on_node' => $this->nodeHandler,
153-
], $this->userOptions);
154-
155-
$options['paths'] = array_unique(array_filter($options['viewDirectories'], function ($path) use ($baseDir) {
156-
return $path !== $baseDir;
157-
}));
158-
159-
return $options;
148+
return $this->options;
160149
}
161150

162151
protected function createEngine(array $options): Pug
@@ -232,9 +221,11 @@ protected function interpolateTwigFunctions(string $code): string
232221
case ')':
233222
if ((--$opening) !== 0) {
234223
$argument .= ')';
224+
225+
break;
235226
}
236227

237-
break;
228+
break 2;
238229

239230
case ',':
240231
if ($opening > 1) {

src/Pug/Symfony/Traits/Options.php

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,18 @@
77
/**
88
* Trait Options.
99
*
10-
* @method Pug getRenderer()
10+
* @property Pug|null $pug
11+
*
12+
* @method Pug getRenderer()
13+
* @method array getRendererOptions()
1114
*/
1215
trait Options
1316
{
17+
/**
18+
* @var array
19+
*/
20+
protected $options;
21+
1422
/**
1523
* Get a Pug engine option or the default value passed as second parameter (null if omitted).
1624
*
@@ -21,6 +29,12 @@ trait Options
2129
*/
2230
public function getOptionDefault($name, $default = null)
2331
{
32+
if ($this->pug === null) {
33+
$options = $this->getRendererOptions();
34+
35+
return array_key_exists($name, $options) ? $options[$name] : $default;
36+
}
37+
2438
$pug = $this->getRenderer();
2539

2640
return method_exists($pug, 'hasOption') && !$pug->hasOption($name)
@@ -36,6 +50,13 @@ public function getOptionDefault($name, $default = null)
3650
*/
3751
public function setOption($name, $value): void
3852
{
53+
if ($this->pug === null) {
54+
$this->getRendererOptions();
55+
$this->options[$name] = $value;
56+
57+
return;
58+
}
59+
3960
$this->getRenderer()->setOption($name, $value);
4061
}
4162

@@ -46,6 +67,12 @@ public function setOption($name, $value): void
4667
*/
4768
public function setOptions(array $options): void
4869
{
70+
if ($this->pug === null) {
71+
$this->options = array_merge($this->getRendererOptions(), $options);
72+
73+
return;
74+
}
75+
4976
$this->getRenderer()->setOptions($options);
5077
}
5178

src/Pug/Twig/Environment.php

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -110,12 +110,12 @@ public function setContainer(ContainerInterface $container): void
110110
$this->container = $container;
111111
}
112112

113-
public function compileSourceBase(Source $source)
113+
public function compileSource(Source $source): string
114114
{
115115
$path = $source->getPath();
116116

117117
if ($this->pugSymfonyEngine->supports($path)) {
118-
$pug = $this->pugSymfonyEngine->getRenderer();
118+
$pug = $this->getRenderer();
119119
$code = $source->getCode();
120120
$php = $pug->compile($code, $path);
121121
$codeFirstLine = $this->isDebug() ? 31 : 25;
@@ -170,11 +170,6 @@ public function compileSourceBase(Source $source)
170170
return $html;
171171
}
172172

173-
public function compileSource(Source $source): string
174-
{
175-
return $this->compileSourceBase($source);
176-
}
177-
178173
public function loadTemplate(string $cls, string $name, int $index = null): Template
179174
{
180175
if ($index !== null) {
@@ -211,12 +206,13 @@ public function compileCode(TwigFunction $function, string $code)
211206
$parser = new Parser($this);
212207
$path = '__twig_function_'.$name.'_'.sha1($code).'.html.twig';
213208
$stream = $this->tokenize(new Source($code, $path, $path));
209+
$output = $this->compile($parser->parse($stream));
214210

215-
if (!preg_match('/^\s*echo\s(.*);\s*$/m', $this->compile($parser->parse($stream)), $match)) {
211+
if (!preg_match('/^\s*echo\s(.*);\s*$/m', $output, $match)) {
216212
throw new RuntimeException('Unable to compile '.$name.' function.');
217213
}
218214

219-
return trim($match[1]);
215+
return '('.trim($match[1]).')'."\n";
220216
}
221217

222218
protected static function getPrivateExtensionProperty(TwigEnvironment $twig, string $extension, string $property)

tests/Pug/PugSymfonyEngineTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,7 @@ public function testExists()
431431

432432
self::assertTrue($pugSymfony->exists('logout.pug'));
433433
self::assertFalse($pugSymfony->exists('login.pug'));
434+
self::assertTrue($pugSymfony->exists('bundle.pug'));
434435
}
435436

436437
public function testSupports()
@@ -613,6 +614,10 @@ public function testDefaultOption()
613614
$pugSymfony = new PugSymfonyEngine(self::$kernel);
614615

615616
self::assertSame(42, $pugSymfony->getOptionDefault('does-not-exist', 42));
617+
618+
$pugSymfony->getRenderer();
619+
620+
self::assertSame(42, $pugSymfony->getOptionDefault('does-not-exist', 42));
616621
}
617622

618623
public function testGetSharedVariables()
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
.foo(style='background-position: 50% -402px; background-image: ' + css_url('assets/img/patterns/5.png') + ';')
2-
.foo(style={'background-position': "50% -402px", 'background-image': css_url('assets/img/patterns/5.png')})
1+
.foo(style='background-position: 50% -402px; background-image: ' . css_url('assets/img/patterns/5.png') . ';')
2+
.foo(style=array('background-position' => "50% -402px", 'background-image' => css_url('assets/img/patterns/5.png')))

0 commit comments

Comments
 (0)