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

SummaryFilter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
c 0
b 0
f 0
lcom 0
cbo 3
dl 0
loc 28
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 20 3
A get() 0 4 1
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