Completed
Push — 2.x ( 9f3108...60c803 )
by Akihito
01:32
created

MobileTemplateFinder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
crap 1
1
<?php
2
/**
3
 * This file is part of the Madapaja.TwigModule package.
4
 *
5
 * @license http://opensource.org/licenses/MIT MIT
6
 */
7
namespace Madapaja\TwigModule;
8
9
use Madapaja\TwigModule\Annotation\TwigPaths;
10
11
class MobileTemplateFinder implements TemplateFinderInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    private $userAgent;
17
18
    /**
19
     * @var TemplateFinder
20
     */
21
    private $templateFinder;
22
23
    /**
24
     * @var array
25
     */
26
    private $paths;
27
28
    /**
29
     * @TwigPaths("paths")
30
     */
31 3
    public function __construct($userAgent = '', array $paths = [])
32
    {
33 3
        $this->userAgent = $userAgent;
34 3
        $this->templateFinder = new TemplateFinder;
35 3
        $this->paths = $paths;
36 3
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41 2
    public function __invoke(string $name) : string
42
    {
43 2
        $templatePath = $this->templateFinder->__invoke($name);
44 2
        $detect = new \Mobile_Detect(null, $this->userAgent);
45 2
        $isMobile = $detect->isMobile() && ! $detect->isTablet();
46 2
        if ($isMobile) {
47 1
            $mobilePath = str_replace('.html.twig', '.mobile.twig', $templatePath);
48 1
            foreach ($this->paths as $path) {
49 1
                $mobileFile = sprintf('%s/%s', $path, $mobilePath);
50 1
                if (file_exists($mobileFile)) {
51 1
                    return $mobilePath;
52
                }
53
            }
54
        }
55
56 1
        return $templatePath;
57
    }
58
}
59