AppExtension::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
/*
3
 * Copyright (C) 2020  Jan Böhmer
4
 *
5
 * This program is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Affero General Public License as published
7
 * by the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Affero General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Affero General Public License
16
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
namespace App\Twig;
20
21
use Carbon\Carbon;
22
use Symfony\Component\HttpFoundation\RequestStack;
23
use Twig\Extension\AbstractExtension;
24
use Twig\TwigFilter;
25
26
class AppExtension extends AbstractExtension
27
{
28
    private $requestStack;
29
30
    public function __construct(RequestStack $requestStack)
31
    {
32
        $this->requestStack = $requestStack;
33
    }
34
35
    public function getFilters(): array
36
    {
37
        return [
38
            new TwigFilter('formatBytes', [$this, 'formatBytes']),
39
            new TwigFilter('format_datetime_diff', [$this, 'formatDatetimeDiff']),
40
            new TwigFilter('flip', 'array_flip')
41
        ];
42
    }
43
44
    public function formatDatetimeDiff($dateTime, $other = null, array $options = [
45
        'parts' => 2,
46
    ]): string
47
    {
48
        Carbon::setLocale($this->requestStack->getCurrentRequest()->getLocale() ?? 'de');
49
50
        return Carbon::parse($dateTime)->diffForHumans($other, $options);
51
    }
52
53
    /**
54
     * Convert a bytes count into a human-readable form (10000 -> 10K).
55
     *
56
     * @param int $precision
57
     */
58
    public function formatBytes(int $bytes, $precision = 2): string
59
    {
60
        $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
61
        $factor = floor((strlen($bytes) - 1) / 3);
62
63
        return sprintf("%.{$precision}f", $bytes / (1024 ** $factor)).@$size[$factor];
64
    }
65
}
66