Completed
Push — master ( 31d3da...cafd23 )
by Michal
05:15
created

Formatter::format()   B

Complexity

Conditions 10
Paths 2

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 11.7434

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 20
cts 27
cp 0.7407
rs 7.6666
c 0
b 0
f 0
cc 10
nc 2
nop 3
crap 11.7434

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
declare(strict_types=1);
3
4
namespace Webrouse\AssetMacro;
5
6
use Nette\Http\IRequest;
7
use Nette\Utils\Strings;
8
use Webrouse\AssetMacro\Exceptions\InvalidVariableException;
9
10
11
12 1
class Formatter implements IFormatter
13
{
14
	/** @var Config */
15
	private $config;
16
17
	/** @var string */
18
	private $baseUrl;
19
20
	/** @var string */
21
	private $basePath;
22
23
24 1
	public function __construct(Config $config, IRequest $httpRequest)
25
	{
26 1
		$this->config = $config;
27 1
		$url = $httpRequest->getUrl();
28 1
		$this->baseUrl = $url->getBaseUrl() . $this->config->getPublicPath();
29 1
		$this->basePath = $url->getBasePath() . $this->config->getPublicPath();
30 1
	}
31
32
33 1
	public function format(Asset $asset, string $format = '%url%', bool $absolute = false): string
34
	{
35 1
		$base = $absolute ? $this->baseUrl : $this->basePath;
36
37 1
		return Strings::replace($format,
38 1
			'/%([^%]+)%/',
39 1
			function ($matches) use ($asset, $format, $base) {
40 1
				switch ($matches[1]) {
41
					case 'content':
42 1
						$content = file_get_contents($asset->getAbsolutePath());
43 1
						return $content ? trim($content) : '';
44
					case 'raw':
45 1
						return $asset->getRevision()->getRawValue();
46
					case 'base':
47 1
						return $base;
48
					case 'basePath':
49 1
						return $this->basePath;
50
					case 'baseUrl':
51 1
						return $this->baseUrl;
52
					case 'path':
53 1
						return $asset->getRelativePath();
54
					case 'url':
55 1
						return sprintf('%s%s', $base, $asset->getRelativeUrl());
56
					default:
57 1
						$msg = sprintf(
58
							"Asset macro: Invalid variable '%s' in format '%s'. " .
59 1
							'Use one of allowed variables: %%raw%%, %%basePath%%, %%path%%, %%url%%.',
60 1
							$matches[1],
61 1
							$format
62
						);
63 1
						throw new InvalidVariableException($msg);
64
				}
65 1
			});
66
	}
67
}
68