DriverAwareTrait   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 1
dl 0
loc 53
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A setDriver() 0 5 1
A getDriver() 0 15 3
A tryFallback() 0 8 3
1
<?php
2
/**
3
 * Phossa Project
4
 *
5
 * PHP version 5.4
6
 *
7
 * @category  Library
8
 * @package   Phossa2\Cache
9
 * @copyright Copyright (c) 2016 phossa.com
10
 * @license   http://mit-license.org/ MIT License
11
 * @link      http://www.phossa.com/
12
 */
13
/*# declare(strict_types=1); */
14
15
namespace Phossa2\Cache\Traits;
16
17
use Phossa2\Cache\Driver\NullDriver;
18
use Phossa2\Cache\Interfaces\DriverInterface;
19
use Phossa2\Cache\Interfaces\DriverAwareInterface;
20
use Phossa2\Cache\Interfaces\FallbackAwareInterface;
21
22
/**
23
 * DriverAwareTrait
24
 *
25
 * @package Phossa2\Cache
26
 * @author  Hong Zhang <[email protected]>
27
 * @see     DriverAwareInterface
28
 * @version 2.0.0
29
 * @since   2.0.0 added
30
 */
31
trait DriverAwareTrait
32
{
33
    /**
34
     * Cache driver
35
     *
36
     * @var    DriverInterface
37
     * @access protected
38
     */
39
    protected $driver;
40
41
    /**
42
     * {@inheritDoc}
43
     */
44
    public function setDriver(DriverInterface $driver)
45
    {
46
        $this->driver = $driver;
47
        return $this;
48
    }
49
50
    /**
51
     * {@inheritDoc}
52
     */
53
    public function getDriver()/*# : DriverInterface */
54
    {
55
        // not found
56
        if (is_null($this->driver)) {
57
            return new NullDriver();
58
        }
59
60
        // driver ok
61
        if ($this->driver->ping()) {
62
            return $this->driver;
63
        }
64
65
        // use fallback
66
        return $this->tryFallback();
67
    }
68
69
    /**
70
     * Try fallback driver. if fail, use NullDriver
71
     *
72
     * @return DriverInterface
73
     * @access protected
74
     */
75
    protected function tryFallback()/*# : DriverInterface */
76
    {
77
        if ($this instanceof FallbackAwareInterface && $this->hasFallback()) {
78
            return $this->getFallback();
79
        } else {
80
            return new NullDriver();
81
        }
82
    }
83
}
84