Completed
Push — master ( a06a95...a1d542 )
by dan
15s
created

ImageEntityNameResolver::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
/**
3
 * This file is part of the IrishDan\ResponsiveImageBundle package.
4
 *
5
 * (c) Daniel Byrne <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source
8
 * code.
9
 */
10
11
namespace IrishDan\ResponsiveImageBundle;
12
13
use Symfony\Component\Cache\Simple\FilesystemCache;
14
15
16
class ImageEntityNameResolver
17
{
18
    const CACHE_KEY = 'responsive_image.image_entity';
19
    protected $className = null;
20
    protected $classLocator;
21
    protected $cache;
22
    protected $imageEntityParameter;
23
24
    public function __construct(ImageEntityClassLocator $classLocator, $imageEntityParameter = '')
25
    {
26
        $this->classLocator         = $classLocator;
27
        $this->imageEntityParameter = $imageEntityParameter;
28
    }
29
30
    public function classExists()
31
    {
32
        $class        = $this->getClassName();
33
        $locatedClass = $this->classLocator->getClassName();
34
35
        return ($class === $locatedClass) ? true : false;
36
    }
37
38
    /**
39
     * @return mixed
40
     */
41
    public function getClassName()
42
    {
43
        // If it's set here just return that.
44
        if (!empty($this->className)) {
45
            return $this->className;
46
        }
47
48
        // Use class name parameter if its been set
49
        if (!empty($this->imageEntityParameter)) {
50
            $this->className = $this->imageEntityParameter;
51
52
            return $this->className;
53
        }
54
55
        // Load it from cached data if it exists
56
        // as a last resort use the Class locator service.
57
        if (empty($this->cache)) {
58
            $this->cache = new FilesystemCache();
59
        }
60
61
        $cached = $this->cache->has(self::CACHE_KEY);
62
        if ($cached) {
63
            $classname = $this->cache->get(self::CACHE_KEY);
64
        }
65
66
        // LAt resort use the Class locator service
67
        if (empty($classname)) {
68
            $classname = $this->classLocator->getClassName();
69
        }
70
71
        // Set the value in as a property in this class
72
        // and set as a cached value for next time.
73
        if (!empty($classname)) {
74
            $this->className = $classname;
75
76
            if (!$cached) {
77
                // @TODO: Should set cache expiration
78
                $this->cache->set(self::CACHE_KEY, $classname);
79
            }
80
81
            return $this->className;
82
        }
83
84
        return false;
85
    }
86
87
    public function getCache()
88
    {
89
        return $this->cache;
90
    }
91
}
92