Passed
Push — master ( 28a571...61bf45 )
by MusikAnimal
30:58 queued 28:02
created

AppExtension::csv()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Twig;
6
7
use Symfony\Component\DependencyInjection\ContainerInterface;
8
use Twig\Extension\AbstractExtension;
9
use Twig\TwigFunction;
10
11
class AppExtension extends AbstractExtension
12
{
13
    /** @var ContainerInterface The application's container interface. */
14
    protected $container;
15
16
    /** @var float Request time. */
17
    private $requestTime;
18
19
    /**
20
     * AppExtension constructor.
21
     * @param ContainerInterface $container
22
     */
23
    public function __construct(ContainerInterface $container)
24
    {
25
        $this->container = $container;
26
    }
27
28
    /**
29
     * Custom functions made available to Twig.
30
     * @return TwigFunction[]
31
     */
32
    public function getFunctions(): array
33
    {
34
        return [
35
            new TwigFunction('request_time', [$this, 'requestTime']),
36
            new TwigFunction('csv', [$this, 'csv'], ['is_safe' => ['html']]),
37
        ];
38
    }
39
40
    /**
41
     * Get the duration of the current HTTP request in seconds.
42
     * @return float
43
     */
44
    public function requestTime(): float
45
    {
46
        if (isset($this->requestTime)) {
47
            return $this->requestTime;
48
        }
49
50
        $startTime = $this->container->get('request_stack')
51
            ->getCurrentRequest()
52
            ->server
53
            ->get('REQUEST_TIME_FLOAT');
54
        $this->requestTime = microtime(true) - $startTime;
55
56
        return $this->requestTime;
57
    }
58
59
    /**
60
     * Properly escape the given string using double-quotes so that it is safe to use as a cell in CSV exports.
61
     * @param string $content
62
     * @return string
63
     */
64
    public function csv(string $content): string
65
    {
66
        return '"'.str_replace('"', '""', $content).'"';
67
    }
68
}
69