Theme::validate()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.8437

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 5
cts 8
cp 0.625
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
nop 0
crap 4.8437
1
<?php declare(strict_types=1);
2
3
namespace Bigwhoop\Trumpet\Presentation\Theming;
4
5
abstract class Theme
6
{
7
    /** @var string */
8
    protected $basePath = '';
9
    
10 1
    public function __construct(string $basePath)
11
    {
12 1
        $this->basePath = $basePath;
13
14 1
        $this->validate();
15 1
    }
16
17 1
    protected function validate()
18
    {
19 1
        if (!is_dir($this->basePath) || !is_readable($this->basePath)) {
20
            throw new ThemeException("Theme path '{$this->basePath}' must be a readable directory.");
21
        }
22
23 1
        $layoutPath = $this->getLayoutPath();
24 1
        if (!file_exists($layoutPath)) {
25
            $fileName = basename($layoutPath);
26
            
27
            throw new ThemeException("Theme must contain a '{$fileName}' file. Could not find one at '{$layoutPath}'.");
28
        }
29 1
    }
30
    
31
    abstract public function render(array $params): string;
32
    abstract protected function getLayoutPath(): string;
33
    
34
    protected function getAssetPath(string $name): string
35
    {
36
        return $this->basePath.'/assets/'.$name;
37
    }
38
    
39
    public function getAsset(string $name): Asset
40
    {
41
        $path = $this->getAssetPath($name);
42
        if (!file_exists($path)) {
43
            throw new ThemeException("Theme asset '$name' must exist. Could not find it at '$path'.");
44
        }
45
46
        $asset = new Asset();
47
        $asset->content = file_get_contents($path);
48
49
        switch (pathinfo($name, PATHINFO_EXTENSION)) {
50
            case 'css':  $asset->contentType = 'text/css';        break;
51
            case 'js':   $asset->contentType = 'text/javascript'; break;
52
            case 'jpg':  $asset->contentType = 'image/jpeg';      break;
53
            case 'gif':  $asset->contentType = 'image/gif';       break;
54
            case 'png':  $asset->contentType = 'image/png';       break;
55
        }
56
57
        return $asset;
58
    }
59
}
60