Template   A
last analyzed

Complexity

Total Complexity 34

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Test Coverage

Coverage 27.08%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 96
c 2
b 0
f 0
dl 0
loc 197
ccs 26
cts 96
cp 0.2708
rs 9.68
wmc 34

7 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 15 1
A getEngine() 0 27 4
C buildNavigation() 0 44 12
A renderNavigation() 0 22 4
A getSeparator() 0 7 2
A __construct() 0 3 1
B registerFunctions() 0 47 10
1
<?php
2
3
namespace Todaymade\Daux\Format\HTML;
4
5
use League\Plates\Engine;
6
use Symfony\Component\Console\Output\OutputInterface;
7
use Todaymade\Daux\Config;
0 ignored issues
show
Bug introduced by Stéphane Goetz
This use statement conflicts with another class in this namespace, Todaymade\Daux\Format\HTML\Config. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use Todaymade\Daux\Daux;
9
use Todaymade\Daux\Tree\Content;
10
use Todaymade\Daux\Tree\Directory;
11
12
class Template
13
{
14
    protected $engine;
15
16
    protected $params;
17
18
    /**
19
     * @param string $base
20
     * @param string $theme
21
     */
22 2
    public function __construct(Config $params)
23
    {
24 2
        $this->params = $params;
25 2
    }
26
27 2
    public function getEngine(Config $params)
28
    {
29 2
        if ($this->engine) {
30
            return $this->engine;
31
        }
32
33 2
        $base = $params['templates'];
34 2
        $theme = $params['theme']['templates'];
35
36
        // Use internal templates if no templates
37
        // dir exists in the working directory
38 2
        if (!is_dir($base)) {
39 2
            $base = __DIR__ . '/../../../templates';
40
        }
41
42
        // Create new Plates instance
43 2
        $this->engine = new Engine($base);
44 2
        if (!is_dir($theme)) {
45 2
            $theme = $base;
46
        }
47 2
        $this->engine->addFolder('theme', $theme, true);
48
49 2
        Daux::writeln("Starting Template engine with basedir '$base' and theme folder '$theme'.", OutputInterface::VERBOSITY_VERBOSE);
50
51 2
        $this->registerFunctions($this->engine);
52
53 2
        return $this->engine;
54
    }
55
56
    /**
57
     * @param string $name
58
     * @param array $data
59
     * @return string
60
     */
61
    public function render($name, array $data = [])
62
    {
63
        $engine = $this->getEngine($data['params']);
64
65
        $engine->addData([
66
            'base_url' => $data['params']['base_url'],
67
            'base_page' => $data['params']['base_page'],
68
            'page' => $data['page'],
69
            'params' => $data['params'],
70
            'tree' => $data['params']['tree'],
71
        ]);
72
73
        Daux::writeln("Rendering template '$name'", OutputInterface::VERBOSITY_VERBOSE);
74
75
        return $engine->render($name, $data);
76
    }
77
78 2
    protected function registerFunctions($engine)
79
    {
80
        $engine->registerFunction('get_navigation', function ($tree, $path, $current_url, $base_page, $mode) {
81
            $nav = $this->buildNavigation($tree, $path, $current_url, $base_page, $mode);
82
83
            return $this->renderNavigation($nav);
84 2
        });
85
86
        $engine->registerFunction('translate', function ($key) {
87 2
            $language = $this->params['language'];
88
89 2
            if (isset($this->engine->getData('page')['page'])) {
90
                $page = $this->engine->getData('page');
91
                if (!empty($page['page']['language'])) {
92
                    $language = $page['page']['language'];
93
                }
94
            }
95
96 2
            if (array_key_exists($language, $this->params['strings'])) {
97 2
                if (array_key_exists($key, $this->params['strings'][$language])) {
98 2
                    return $this->params['strings'][$language][$key];
99
                }
100
            }
101
102
            if (array_key_exists($key, $this->params['strings']['en'])) {
103
                return $this->params['strings']['en'][$key];
104
            }
105
106
            return "Unknown key $key";
107 2
        });
108
109
        $engine->registerFunction('get_breadcrumb_title', function ($page, $base_page) {
110
            $title = '';
111
            $breadcrumb_trail = $page['breadcrumb_trail'];
112
            $separator = $this->getSeparator($page['breadcrumb_separator']);
113
            foreach ($breadcrumb_trail as $value) {
114
                $title .= '<a href="' . $base_page . $value['url'] . '">' . $value['title'] . '</a>' . $separator;
115
            }
116
            if ($page['filename'] === 'index' || $page['filename'] === '_index') {
117
                if ($page['title'] != '') {
118
                    $title = substr($title, 0, -1 * strlen($separator));
119
                }
120
            } else {
121
                $title .= '<a href="' . $base_page . $page['request'] . '">' . $page['title'] . '</a>';
122
            }
123
124
            return $title;
125 2
        });
126 2
    }
127
128
    private function renderNavigation($entries)
129
    {
130
        $nav = '';
131
        foreach ($entries as $entry) {
132
            if (array_key_exists('children', $entry)) {
133
                $icon = '<i class="Nav__arrow">&nbsp;</i>';
134
135
                if (array_key_exists('href', $entry)) {
136
                    $link = '<a href="' . $entry['href'] . '" class="folder">' . $icon . $entry['title'] . '</a>';
137
                } else {
138
                    $link = '<a href="#" class="aj-nav folder">' . $icon . $entry['title'] . '</a>';
139
                }
140
141
                $link .= $this->renderNavigation($entry['children']);
142
            } else {
143
                $link = '<a href="' . $entry['href'] . '">' . $entry['title'] . '</a>';
144
            }
145
146
            $nav .= "<li class='Nav__item $entry[class]'>$link</li>";
147
        }
148
149
        return "<ul class='Nav'>$nav</ul>";
150
    }
151
152
    private function buildNavigation(Directory $tree, $path, $current_url, $base_page, $mode)
153
    {
154
        $nav = [];
155
        foreach ($tree->getEntries() as $node) {
156
            $url = $node->getUri();
157
            if ($node instanceof Content) {
158
                if ($node->isIndex()) {
159
                    continue;
160
                }
161
162
                $link = ($path === '') ? $url : $path . '/' . $url;
163
164
                $nav[] = [
165
                    'title' => $node->getTitle(),
166
                    'href' => $base_page . $link,
167
                    'class' => $node->isHotPath() ? 'Nav__item--active' : '',
168
                ];
169
            } elseif ($node instanceof Directory) {
170
                if (!$node->hasContent()) {
171
                    continue;
172
                }
173
174
                $folder = [
175
                    'title' => $node->getTitle(),
176
                    'class' => $node->isHotPath() ? 'Nav__item--open' : '',
177
                ];
178
179
                if ($index = $node->getIndexPage()) {
180
                    $folder['href'] = $base_page . $index->getUrl();
181
                }
182
183
                //Child pages
184
                $new_path = ($path === '') ? $url : $path . '/' . $url;
185
                $folder['children'] = $this->buildNavigation($node, $new_path, $current_url, $base_page, $mode);
186
187
                if (!empty($folder['children'])) {
188
                    $folder['class'] .= ' has-children';
189
                }
190
191
                $nav[] = $folder;
192
            }
193
        }
194
195
        return $nav;
196
    }
197
198
    /**
199
     * @param string $separator
200
     * @return string
201
     */
202
    private function getSeparator($separator)
203
    {
204
        switch ($separator) {
205
            case 'Chevrons':
206
                return ' <svg class="Page__header--separator" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 477.175 477.175"><path d="M360.73 229.075l-225.1-225.1c-5.3-5.3-13.8-5.3-19.1 0s-5.3 13.8 0 19.1l215.5 215.5-215.5 215.5c-5.3 5.3-5.3 13.8 0 19.1 2.6 2.6 6.1 4 9.5 4 3.4 0 6.9-1.3 9.5-4l225.1-225.1c5.3-5.2 5.3-13.8.1-19z"/></svg> ';
207
            default:
208
                return $separator;
209
        }
210
    }
211
}
212