Passed
Push — master ( a657bc...a42b30 )
by
unknown
61:11 queued 10s
created

TwigFactory::getLoader()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare( strict_types = 1 );
4
5
namespace WMDE\Fundraising\Frontend\Factories;
6
7
use Twig\Environment;
8
use Twig\Lexer;
9
use Twig\Loader\FilesystemLoader;
10
use Twig\Loader\LoaderInterface;
11
use Twig\TwigFilter;
12
use WMDE\Fundraising\Frontend\Presentation\FilePrefixer;
13
14
abstract class TwigFactory {
15
16
	private array $config;
17
	private string $cachePath;
18
	private string $locale;
19
20
	public function __construct( array $config, string $cachePath, string $locale ) {
21
		$this->config = $config;
22
		$this->cachePath = $cachePath;
23 173
		$this->locale = $locale;
24 173
	}
25 173
26 173
	protected function newFilePrefixFilter( FilePrefixer $filePrefixer ): TwigFilter {
27 173
		return new TwigFilter( 'prefix_file', [ $filePrefixer, 'prefixFile' ] );
28
	}
29 173
30 173
	private function getLoader(): LoaderInterface {
31 1
		if ( !empty( $this->config['loaders']['filesystem'] ) ) {
32
			return new FilesystemLoader( $this->config['loaders']['filesystem'] );
33 172
		}
34 172
		throw new \UnexpectedValueException( 'Invalid Twig loader configuration - missing filesystem' );
35
	}
36
37
	protected function newTwigEnvironment( array $filters, array $functions, array $globals = [] ): Environment {
38
		$options = [
39
			'strict_variables' => isset( $this->config['strict-variables'] ) && $this->config['strict-variables'] === true,
40
			'cache' => empty( $this->config['enable-cache'] ) ? false : $this->config['enable-cache']
41
		];
42
		$twig = new Environment( $this->getLoader(), $options );
43 172
44 172
		foreach ( $globals as $name => $global ) {
45 172
			$twig->addGlobal( $name, $global );
46 172
		}
47
48
		foreach ( $functions as $function ) {
49
			$twig->addFunction( $function );
50
		}
51
52
		foreach ( $filters as $filter ) {
53
			$twig->addFilter( $filter );
54
		}
55 172
56 172
		$twig->setLexer( new Lexer( $twig, [
57
			'tag_comment' => [ '{#', '#}' ],
58 172
			'tag_block' => [ '{%', '%}' ],
59 171
			'tag_variable' => [ '{$', '$}' ]
60
		] ) );
61 172
62 172
		return $twig;
63 172
	}
64
65
}
66