Completed
Push — master ( c32e20...5b9784 )
by Alejandro
15s
created

CacheFactory::getAdapter()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 1
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
ccs 6
cts 6
cp 1
crap 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Factory;
5
6
use Doctrine\Common\Cache;
7
use Interop\Container\ContainerInterface;
8
use Interop\Container\Exception\ContainerException;
9
use Shlinkio\Shlink\Common;
10
use Shlinkio\Shlink\Core\Options\AppOptions;
11
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
12
use Zend\ServiceManager\Exception\ServiceNotFoundException;
13
use Zend\ServiceManager\Factory\FactoryInterface;
14
15
class CacheFactory implements FactoryInterface
16
{
17
    const VALID_CACHE_ADAPTERS = [
18
        Cache\ApcuCache::class,
19
        Cache\ArrayCache::class,
20
        Cache\FilesystemCache::class,
21
        Cache\PhpFileCache::class,
22
        Cache\MemcachedCache::class,
23
    ];
24
25
    /**
26
     * Create an object
27
     *
28
     * @param  ContainerInterface $container
29
     * @param  string $requestedName
30
     * @param  null|array $options
31
     * @return object
32
     * @throws ServiceNotFoundException if unable to resolve the service.
33
     * @throws ServiceNotCreatedException if an exception is raised when
34
     *     creating a service.
35
     * @throws ContainerException if any other error occurs
36
     */
37 6
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
38
    {
39 6
        $appOptions = $container->get(AppOptions::class);
40 6
        $adapter = $this->getAdapter($container);
41 6
        $adapter->setNamespace($appOptions->__toString());
42
43 6
        return $adapter;
44
    }
45
46
    /**
47
     * @param ContainerInterface $container
48
     * @return Cache\CacheProvider
49
     */
50 6
    protected function getAdapter(ContainerInterface $container)
51
    {
52
        // Try to get the adapter from config
53 6
        $config = $container->get('config');
54 6
        if (isset($config['cache'], $config['cache']['adapter'])
55 6
            && in_array($config['cache']['adapter'], self::VALID_CACHE_ADAPTERS)
56
        ) {
57 3
            return $this->resolveCacheAdapter($config['cache']);
58
        }
59
60
        // If the adapter has not been set in config, create one based on environment
61 3
        return Common\env('APP_ENV', 'pro') === 'pro' ? new Cache\ApcuCache() : new Cache\ArrayCache();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Shlinkio\Shlink\...mon\Cache\ArrayCache(); (Doctrine\Common\Cache\Ap...Common\Cache\ArrayCache) is incompatible with the return type documented by Shlinkio\Shlink\Common\F...acheFactory::getAdapter of type Doctrine\Common\Cache\CacheProvider.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
62
    }
63
64
    /**
65
     * @param array $cacheConfig
66
     * @return Cache\CacheProvider
67
     */
68 3
    protected function resolveCacheAdapter(array $cacheConfig)
69
    {
70 3
        switch ($cacheConfig['adapter']) {
71
            case Cache\ArrayCache::class:
72
            case Cache\ApcuCache::class:
73 1
                return new $cacheConfig['adapter']();
74
            case Cache\FilesystemCache::class:
75
            case Cache\PhpFileCache::class:
76 1
                return new $cacheConfig['adapter']($cacheConfig['options']['dir']);
77
            case Cache\MemcachedCache::class:
78 1
                $memcached = new \Memcached();
79 1
                $servers = isset($cacheConfig['options']['servers']) ? $cacheConfig['options']['servers'] : [];
80
81 1
                foreach ($servers as $server) {
82 1
                    if (! isset($server['host'])) {
83
                        continue;
84
                    }
85 1
                    $port = isset($server['port']) ? (int) $server['port'] : 11211;
86
87 1
                    $memcached->addServer($server['host'], $port);
88
                }
89
90 1
                $cache = new Cache\MemcachedCache();
91 1
                $cache->setMemcached($memcached);
92 1
                return $cache;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $cache; (Doctrine\Common\Cache\MemcachedCache) is incompatible with the return type documented by Shlinkio\Shlink\Common\F...ry::resolveCacheAdapter of type Doctrine\Common\Cache\CacheProvider.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
93
            default:
94
                return new Cache\ArrayCache();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Doctrine\Common\Cache\ArrayCache(); (Doctrine\Common\Cache\ArrayCache) is incompatible with the return type documented by Shlinkio\Shlink\Common\F...ry::resolveCacheAdapter of type Doctrine\Common\Cache\CacheProvider.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
95
        }
96
    }
97
}
98