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

MobileTemplateFinder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 2
dl 0
loc 48
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B __invoke() 0 17 5
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