Completed
Push — master ( 98e7e2...07146b )
by WEBEWEB
08:26
created

renderDataTablesTHead()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 4
nc 6
nop 1
1
<?php
2
3
/**
4
 * This file is part of the jquery-datatables-bundle package.
5
 *
6
 * (c) 2018 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Bundle\JQuery\DataTablesBundle\Twig\Extension;
13
14
use Twig_Environment;
15
use WBW\Bundle\CoreBundle\Service\TwigEnvironmentTrait;
16
use WBW\Bundle\CoreBundle\Twig\Extension\AbstractTwigExtension;
17
use WBW\Bundle\CoreBundle\Twig\Extension\RendererTwigExtension;
18
use WBW\Bundle\CoreBundle\Twig\Extension\RendererTwigExtensionTrait;
19
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesColumnInterface;
20
use WBW\Bundle\JQuery\DataTablesBundle\API\DataTablesWrapperInterface;
21
use WBW\Bundle\JQuery\DataTablesBundle\Helper\DataTablesWrapperHelper;
22
use WBW\Library\Core\Argument\StringHelper;
23
use WBW\Library\Core\Exception\IO\FileNotFoundException;
24
25
/**
26
 * Abstract DataTables Twig extension.
27
 *
28
 * @author webeweb <https://github.com/webeweb/>
29
 * @package WBW\Bundle\JQuery\DataTablesBundle\Twig\Extension
30
 * @abstract
31
 */
32
abstract class AbstractDataTablesTwigExtension extends AbstractTwigExtension {
33
34
    use RendererTwigExtensionTrait;
35
    use TwigEnvironmentTrait;
36
37
    /**
38
     * jQuery DataTables.
39
     *
40
     * @var string
41
     */
42
    const JQUERY_DATATABLES = <<<'EOT'
43
    $(document).ready(function () {
44
        var %var% = $("%selector%").DataTable(%options%);
45
    });
46
EOT;
47
48
    /**
49
     * jQuery DataTables.
50
     *
51
     * @var string
52
     */
53
    const JQUERY_DATATABLES_STANDALONE = <<<'EOT'
54
    $(document).ready(function () {
55
        $("%selector%").DataTable(%options%);
56
    });
57
EOT;
58
59
    /**
60
     * Constructor.
61
     *
62
     * @param Twig_Environment $twigEnvironment The Twig environment.
63
     * @param RendererTwigExtension $rendererTwigExtension The renderer Twig extension.
64
     */
65
    protected function __construct(Twig_Environment $twigEnvironment, RendererTwigExtension $rendererTwigExtension) {
66
        parent::__construct($twigEnvironment);
67
        $this->setRendererTwigExtension($rendererTwigExtension);
68
    }
69
70
    /**
71
     * Encode the options.
72
     *
73
     * @param array $options The options.
74
     * @return string Returns the encoded options.
75
     */
76
    protected function encodeOptions(array $options) {
77
        if (0 === count($options)) {
78
            return "{}";
79
        }
80
        ksort($options);
81
        $output = json_encode($options, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
82
        return str_replace("\n", "\n        ", $output);
83
    }
84
85
    /**
86
     * Displays a jQuery DataTables.
87
     *
88
     * @param DataTablesWrapperInterface $dtWrapper The wrapper.
89
     * @param string $selector The selector.
90
     * @param string $language The language.
91
     * @return string Returns the jQuery DataTables.
92
     * @throws FileNotFoundException Throws a file not found exception if the language file does not exist.
93
     */
94
    protected function jQueryDataTables(DataTablesWrapperInterface $dtWrapper, $selector, $language) {
95
96
        // Get the options.
97
        $dtOptions = DataTablesWrapperHelper::getOptions($dtWrapper);
98
99
        // Initialize the parameters.
100
        $var     = DataTablesWrapperHelper::getName($dtWrapper);
101
        $options = $dtOptions;
102
        if (null !== $language) {
103
            $options["language"] = ["url" => DataTablesWrapperHelper::getLanguageURL($language)];
104
        }
105
106
        //
107
        $searches = ["%var%", "%selector%", "%options%"];
108
        $replaces = [$var, null === $selector ? "#" . $var : $selector, $this->encodeOptions($options)];
109
110
        // Return the Javascript.
111
        $javascript = StringHelper::replace(self::JQUERY_DATATABLES, $searches, $replaces);
112
        return $this->getRendererTwigExtension()->coreScriptFilter($javascript);
113
    }
114
115
    /**
116
     * Displays a jQuery DataTables "Standalone".
117
     *
118
     * @param string $selector The selector.
119
     * @param string $language The language.
120
     * @param array $options The options.
121
     * @return string Returns the jQuery DataTables "Standalone".
122
     * @throws FileNotFoundException Throws a file not found exception if the language file does not exist.
123
     */
124
    protected function jQueryDataTablesStandalone($selector, $language, array $options) {
125
126
        // Initialize the language.
127
        if (null !== $language) {
128
            $options["language"] = ["url" => DataTablesWrapperHelper::getLanguageURL($language)];
129
        }
130
131
        //
132
        $searches = ["%selector%", "%options%"];
133
        $replaces = [$selector, $this->encodeOptions($options)];
134
135
        // Return the Javascript.
136
        $javascript = StringHelper::replace(self::JQUERY_DATATABLES_STANDALONE, $searches, $replaces);
137
        return $this->getRendererTwigExtension()->coreScriptFilter($javascript);
138
    }
139
140
    /**
141
     * Render a DataTables.
142
     *
143
     * @param DataTablesWrapperInterface $dtWrapper The wrapper.
144
     * @param string $class The class.
145
     * @param boolean $includeTHead Include thead ?.
146
     * @param boolean $includeTFoot Include tfoot ?
147
     * @returns string Returns the rendered DataTables.
148
     */
149
    protected function renderDataTables(DataTablesWrapperInterface $dtWrapper, $class, $includeTHead, $includeTFoot) {
150
151
        // Initialize the template.
152
        $template = "<table %attributes%>\n%innerHTML%</table>";
153
154
        // Initialize the attributes.
155
        $attributes = [];
156
157
        $attributes["class"] = ["table", $class];
158
        $attributes["id"]    = DataTablesWrapperHelper::getName($dtWrapper);
159
160
        // Initialize the parameters.
161
        $thead = true === $includeTHead ? $this->renderDataTablesTHead($dtWrapper) : "";
162
        $tfoot = true === $includeTFoot ? $this->renderDataTablesTFoot($dtWrapper) : "";
163
164
        // Return the HTML.
165
        return StringHelper::replace($template, ["%attributes%", "%innerHTML%"], [StringHelper::parseArray($attributes), $thead . $tfoot]);
166
    }
167
168
    /**
169
     * Render a column.
170
     *
171
     * @param DataTablesColumnInterface $dtColumn The column.
172
     * @return string Returns the rendered column.
173
     */
174
    private function renderDataTablesColumn(DataTablesColumnInterface $dtColumn, $scopeRow = false) {
175
176
        // Initialize the template.
177
        $template = "            <th%attributes%>%innerHTML%</th>";
178
179
        // Initialize the attributes.
180
        $attributes = [];
181
182
        $attributes["scope"] = true === $scopeRow ? "row" : null;
183
        $attributes["class"] = $dtColumn->getClassname();
184
        $attributes["width"] = $dtColumn->getWidth();
185
186
        // Initialize the parameters.
187
        $innerHTML = $dtColumn->getTitle();
188
189
        // Return the HTML.
190
        return StringHelper::replace($template, ["%attributes%", "%innerHTML%"], [preg_replace("/^\ $/", "", " " . StringHelper::parseArray($attributes)), $innerHTML]);
191
    }
192
193
    /**
194
     * Render a footer.
195
     *
196
     * @param DataTablesWrapperInterface $dtWrapper The wrapper.
197
     * @return string Returns the rendered footer.
198
     */
199
    private function renderDataTablesTFoot(DataTablesWrapperInterface $dtWrapper) {
200
201
        // Initialize the template.
202
        $template = "    <tfoot>\n        <tr>\n%innerHTML%        </tr>\n    </tfoot>\n";
203
204
        // Initialize the parameters.
205
        $innerHTML = "";
206
        foreach ($dtWrapper->getColumns() as $dtColumn) {
207
            $column = $this->renderDataTablesColumn($dtColumn);
208
            if ("" === $column) {
209
                continue;
210
            }
211
            $innerHTML .= $column . "\n";
212
        }
213
214
        // Return the HTML.
215
        return "" === $innerHTML ? "" : StringHelper::replace($template, ["%innerHTML%"], [$innerHTML]);
216
    }
217
218
    /**
219
     * Render a header.
220
     *
221
     * @param DataTablesWrapperInterface $dtWrapper The wrapper.
222
     * @return string Returns the rendered header.
223
     */
224
    private function renderDataTablesTHead(DataTablesWrapperInterface $dtWrapper) {
225
226
        // Initialize the templates.
227
        $template = "    <thead>\n        <tr>\n%innerHTML%        </tr>\n    </thead>\n";
228
229
        // Count the columns.
230
        $count = count($dtWrapper->getColumns());
231
232
        // Initialize the parameters.
233
        $innerHTML = "";
234
        for ($i = 0; $i < $count; ++$i) {
235
            $dtColumn = array_values($dtWrapper->getColumns())[$i];
236
            $column   = $this->renderDataTablesColumn($dtColumn, 0 === $i);
237
            if ("" === $column) {
238
                continue;
239
            }
240
            $innerHTML .= $column . "\n";
241
        }
242
243
        // Return the HTML.
244
        return "" === $innerHTML ? "" : StringHelper::replace($template, ["%innerHTML%"], [$innerHTML]);
245
    }
246
247
}
248