Completed
Push — master ( 74371a...6da8c0 )
by Vladimir
02:21
created

SummaryFilter::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Templating\Twig\Extension;
9
10
use allejo\stakx\Utilities\HtmlUtils;
11
12
class SummaryFilter extends AbstractTwigExtension implements TwigFilterInterface
13
{
14
    public function __invoke($value, $paragraphCount = 1)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
15
    {
16
        if (!extension_loaded('dom'))
17
        {
18
            @trigger_error('The DOM Extension is not loaded and is necessary for the "summary" Twig filter.', E_WARNING);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
19
            return $value;
20
        }
21
22
        $dom = new \DOMDocument();
23
        $paragraphs = HtmlUtils::htmlXPath($dom, $value, sprintf('//body/p[position() <= %d]', $paragraphCount));
24
25
        $summary = '';
26
27
        foreach ($paragraphs as $paragraph)
28
        {
29
            $summary .= $dom->saveHTML($paragraph);
30
        }
31
32
        return $summary;
33
    }
34
35
    public static function get()
36
    {
37
        return new \Twig_SimpleFilter('summary', new self());
38
    }
39
}
40