Cache::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Concise package.
5
 *
6
 * (c) Antoine Corcy <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Concise\Provider;
13
14
use Concise\Provider;
15
use Stash\Interfaces\PoolInterface;
16
17
/**
18
 * Cache URLs
19
 *
20
 * @author Márk Sági-Kazár <[email protected]>
21
 */
22
class Cache implements Provider
23
{
24
    /**
25
     * @var Provider
26
     */
27
    protected $provider;
28
29
    /**
30
     * @var PoolInterface
31
     */
32
    protected $pool;
33
34
    /**
35
     * @param Provider $provider
36
     */
37 4
    public function __construct(Provider $provider, PoolInterface $pool)
38
    {
39 4
        $this->provider = $provider;
40 4
        $this->pool = $pool;
41 4
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 1
    public function shorten($url)
47
    {
48 1
        return $this->transformUrl($url, 'shorten');
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 1
    public function expand($url)
55
    {
56 1
        return $this->transformUrl($url, 'expand');
57
    }
58
59
    /**
60
     * Shorten or expand a URL checking it in the cache first
61
     *
62
     * @param string $url
63
     * @param string $transformation
64
     *
65
     * @return string
66
     */
67 2
    protected function transformUrl($url, $transformation)
68
    {
69 2
        $cachedUrl = $this->pool->getItem(md5($url));
70
71 2
        if ($cachedUrl->isMiss()) {
72 1
            $url = $this->provider->$transformation($url);
73
74 1
            $cachedUrl->set($url);
75 1
        } else {
76 1
            $url = $cachedUrl->get();
77
        }
78
79 2
        return $url;
80
    }
81
}
82