ConsoleController::warmupAction()   B
last analyzed

Complexity

Conditions 4
Paths 8

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.0047

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 24
ccs 14
cts 15
cp 0.9333
rs 8.6845
c 1
b 0
f 0
cc 4
eloc 14
nc 8
nop 0
crap 4.0047
1
<?php
2
3
namespace AssetManager\Controller;
4
5
use AssetManager\Core\Service\AssetManager;
6
use Zend\Console\Adapter\AdapterInterface as Console;
7
use Zend\Console\Request as ConsoleRequest;
8
use Zend\Mvc\Controller\AbstractActionController;
9
use Zend\Stdlib\RequestInterface;
10
use Zend\Stdlib\ResponseInterface;
11
12
/**
13
 * Class ConsoleController
14
 *
15
 * @package AssetManager\Controller
16
 */
17
class ConsoleController extends AbstractActionController
18
{
19
20
    /**
21
     * @var \Zend\Console\Adapter\AdapterInterface console object
22
     */
23
    protected $console;
24
25
    /**
26
     * @var AssetManager asset manager object
27
     */
28
    protected $assetManager;
29
30
    /**
31
     * @var array associative array represents app config
32
     */
33
    protected $appConfig;
34
35
    /**
36
     * @param Console $console
37
     * @param AssetManager $assetManager
38
     * @param array $appConfig
39
     */
40 1
    public function __construct(Console $console, AssetManager $assetManager, array $appConfig)
41
    {
42 1
        $this->console      = $console;
43 1
        $this->assetManager = $assetManager;
44 1
        $this->appConfig    = $appConfig;
45 1
    }
46
47
    /**
48
     * {@inheritdoc}
49
     * @param RequestInterface $request
50
     * @param ResponseInterface $response
51
     * @return mixed|ResponseInterface
52
     * @throws \RuntimeException
53
     */
54 1
    public function dispatch(RequestInterface $request, ResponseInterface $response = null)
55
    {
56 1
        if (!($request instanceof ConsoleRequest)) {
57
            throw new \RuntimeException('You can use this controller only from a console!');
58
        }
59
60 1
        return parent::dispatch($request, $response);
61
    }
62
63
    /**
64
     * Dumps all assets to cache directories.
65
     */
66 1
    public function warmupAction()
67
    {
68 1
        $request    = $this->getRequest();
69 1
        $purge      = $request->getParam('purge', false);
70 1
        $verbose    = $request->getParam('verbose', false) || $request->getParam('v', false);
71
72
        // purge cache for every configuration
73 1
        if ($purge) {
74
            $this->purgeCache($verbose);
75
        }
76
77 1
        $this->output('Collecting all assets...', $verbose);
78
79 1
        $collection = $this->assetManager->getResolver()->collect();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface AssetManager\Core\Resolver\ResolverInterface as the method collect() does only exist in the following implementations of said interface: AssetManager\Core\Resolver\AggregateResolver, AssetManager\Core\Resolver\AliasPathStackResolver, AssetManager\Core\Resolver\CollectionResolver, AssetManager\Core\Resolver\ConcatResolver, AssetManager\Core\Resolver\MapResolver, AssetManager\Core\Resolver\PathStackResolver, AssetManager\Core\Resolv...rioritizedPathsResolver, AssetManager\Core\Resolv...ivateCollectionResolver, InterfaceTestResolver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
80 1
        $this->output(sprintf('Collected %d assets, warming up...', count($collection)), $verbose);
81
82 1
        foreach ($collection as $path) {
83 1
            $asset = $this->assetManager->getResolver()->resolve($path);
84 1
            $this->assetManager->getAssetFilterManager()->setFilters($path, $asset);
0 ignored issues
show
Bug introduced by
It seems like $asset defined by $this->assetManager->get...olver()->resolve($path) on line 83 can be null; however, AssetManager\Core\Servic...erManager::setFilters() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
85 1
            $this->assetManager->getAssetCacheManager()->setCache($path, $asset)->dump();
0 ignored issues
show
Bug introduced by
It seems like $asset defined by $this->assetManager->get...olver()->resolve($path) on line 83 can be null; however, AssetManager\Core\Servic...acheManager::setCache() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
86
        }
87
88 1
        $this->output(sprintf('Warming up finished...', $verbose));
89 1
    }
90
91
    /**
92
     * Purges all directories defined as AssetManager cache dir.
93
     * @param bool $verbose verbose flag, default false
94
     * @return bool false if caching is not set, otherwise true
95
     */
96
    protected function purgeCache($verbose = false)
97
    {
98
99
        if (empty($this->appConfig['asset_manager']['caching'])) {
100
            return false;
101
        }
102
103
        foreach ($this->appConfig['asset_manager']['caching'] as $configName => $config) {
104
            if (empty($config['options']['dir'])) {
105
                continue;
106
            }
107
            $this->output(sprintf('Purging %s on "%s"...', $config['options']['dir'], $configName), $verbose);
108
109
            $node = $config['options']['dir'];
110
111
            if ($configName !== 'default') {
112
                $node .= '/'.$configName;
113
            }
114
115
            $this->recursiveRemove($node, $verbose);
116
        }
117
118
        return true;
119
    }
120
121
    /**
122
     * Removes given node from filesystem (recursively).
123
     * @param string $node - uri of node that should be removed from filesystem
124
     * @param bool $verbose verbose flag, default false
125
     */
126
    protected function recursiveRemove($node, $verbose = false)
127
    {
128
        if (is_dir($node)) {
129
            $objects = scandir($node);
130
131
            foreach ($objects as $object) {
132
                if ($object === '.' || $object === '..') {
133
                    continue;
134
                }
135
                $this->recursiveRemove($node . '/' . $object);
136
            }
137
        } elseif (is_file($node)) {
138
            $this->output(sprintf("unlinking %s...", $node), $verbose);
139
            unlink($node);
140
        }
141
    }
142
143
    /**
144
     * Outputs given $line if $verbose i truthy value.
145
     * @param $line
146
     * @param bool $verbose verbose flag, default true
147
     */
148 1
    protected function output($line, $verbose = true)
149
    {
150 1
        if ($verbose) {
151 1
            $this->console->writeLine($line);
152
        }
153 1
    }
154
}
155