Completed
Pull Request — master (#27)
by Hari
09:21
created

PublishCommandHandler::mappingsEqual()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 7
ccs 0
cts 7
cp 0
rs 9.2
cc 4
eloc 5
nc 4
nop 2
crap 20
1
<?php
2
3
/*
4
 * This file is part of the puli/asset-plugin package.
5
 *
6
 * (c) Bernhard Schussek <[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 Puli\Cli\Handler;
13
14
use Puli\Manager\Api\Asset\AssetManager;
15
use Puli\Manager\Api\Asset\AssetMapping;
16
use Puli\Manager\Api\Installation\InstallationManager;
17
use Puli\Manager\Api\Installation\InstallationParams;
18
use Puli\Manager\Api\Server\Server;
19
use Puli\Manager\Api\Server\ServerManager;
20
use RuntimeException;
21
use Webmozart\Console\Api\Args\Args;
22
use Webmozart\Console\Api\IO\IO;
23
use Webmozart\Console\UI\Component\Table;
24
use Webmozart\Console\UI\Style\TableStyle;
25
use Webmozart\Expression\Expr;
26
use Webmozart\PathUtil\Path;
27
28
/**
29
 * @since  1.0
30
 *
31
 * @author Bernhard Schussek <[email protected]>
32
 */
33
class PublishCommandHandler
34
{
35
    /**
36
     * @var AssetManager
37
     */
38
    private $assetManager;
39
40
    /**
41
     * @var InstallationManager
42
     */
43
    private $installationManager;
44
45
    /**
46
     * @var ServerManager
47
     */
48
    private $serverManager;
49
50
    /**
51
     * @var string
52
     */
53
    private $currentPath = '/';
54
55
    public function __construct(AssetManager $assetManager, InstallationManager $installationManager, ServerManager $serveRManager)
56
    {
57
        $this->assetManager = $assetManager;
58
        $this->installationManager = $installationManager;
59
        $this->serverManager = $serveRManager;
60
    }
61
62
    public function handleList(Args $args, IO $io)
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
63
    {
64
        /** @var AssetMapping[][] $mappingsByServer */
65
        $mappingsByServer = array();
66
67
        /** @var Server[] $servers */
68
        $servers = array();
69
        $nonExistingServers = array();
70
71
        // Assemble mappings and validate servers
72
        foreach ($this->assetManager->getAssetMappings() as $mapping) {
73
            $serverName = $mapping->getServerName();
74
75
            if (!isset($mappingsByServer[$serverName])) {
76
                $mappingsByServer[$serverName] = array();
77
78
                if ($this->serverManager->hasServer($serverName)) {
79
                    $servers[$serverName] = $this->serverManager->getServer($serverName);
80
                } else {
81
                    $nonExistingServers[$serverName] = true;
82
                }
83
            }
84
85
            $mappingsByServer[$serverName][] = $mapping;
86
        }
87
88
        if (empty($mappingsByServer)) {
89
            $io->writeLine('No public resources. Use "puli publish <path> <server>" to publish resources.');
90
91
            return 0;
92
        }
93
94
        if (count($servers) > 0) {
95
            $io->writeLine('The following resources are published:');
96
            $io->writeLine('');
97
98
            foreach ($servers as $serverName => $server) {
99
                $serverTitle = 'Server <bu>'.$serverName.'</bu>';
100
101
                $io->writeLine(sprintf('    <b>%s</b>', $serverTitle));
102
                $io->writeLine(sprintf('    Location:   <c2>%s</c2>', $server->getDocumentRoot()));
103
                $io->writeLine(sprintf('    Installer:  %s', $server->getInstallerName()));
104
                $io->writeLine(sprintf('    URL Format: <c1>%s</c1>', $server->getUrlFormat()));
105
                $io->writeLine('');
106
107
                $this->printMappingTable($io, $mappingsByServer[$serverName]);
108
                $io->writeLine('');
109
            }
110
111
            $io->writeLine('Use "puli publish --install" to install the resources on your servers.');
112
        }
113
114
        if (count($servers) > 0 && count($nonExistingServers) > 0) {
115
            $io->writeLine('');
116
        }
117
118
        if (count($nonExistingServers) > 0) {
119
            $io->writeLine('The following public resources are disabled since their server does not exist:');
120
            $io->writeLine('');
121
122
            foreach ($nonExistingServers as $serverName => $_) {
123
                $io->writeLine(sprintf('    <b>Server <bu>%s</bu></b>', $serverName));
124
                $io->writeLine('');
125
126
                $this->printMappingTable($io, $mappingsByServer[$serverName], false);
127
                $io->writeLine('');
128
            }
129
130
            $io->writeLine('Use "puli server add <name> <document-root>" to add a server.');
131
        }
132
133
        return 0;
134
    }
135
136 View Code Duplication
    public function handleAdd(Args $args)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
    {
138
        $flags = $args->isOptionSet('force') ? AssetManager::IGNORE_SERVER_NOT_FOUND : 0;
139
        $path = Path::makeAbsolute($args->getArgument('path'), $this->currentPath);
140
141
        $this->assetManager->addRootAssetMapping(new AssetMapping(
142
            $path,
143
            $args->getArgument('server'),
144
            $args->getArgument('server-path')
145
        ), $flags);
146
147
        return 0;
148
    }
149
150
    public function handleUpdate(Args $args)
151
    {
152
        $flags = $args->isOptionSet('force')
153
            ? AssetManager::OVERRIDE | AssetManager::IGNORE_SERVER_NOT_FOUND
154
            : AssetManager::OVERRIDE;
155
        $mappingToUpdate = $this->getMappingByUuidPrefix($args->getArgument('uuid'));
156
        $path = $mappingToUpdate->getGlob();
157
        $serverPath = $mappingToUpdate->getServerPath();
158
        $serverName = $mappingToUpdate->getServerName();
159
160
        if ($args->isOptionSet('path')) {
161
            $path = Path::makeAbsolute($args->getOption('path'), $this->currentPath);
162
        }
163
164
        if ($args->isOptionSet('server-path')) {
165
            $serverPath = $args->getOption('server-path');
166
        }
167
168
        if ($args->isOptionSet('server')) {
169
            $serverName = $args->getOption('server');
170
        }
171
172
        $updatedMapping = new AssetMapping($path, $serverName, $serverPath, $mappingToUpdate->getUuid());
173
174
        if ($this->mappingsEqual($mappingToUpdate, $updatedMapping)) {
175
            throw new RuntimeException('Nothing to update.');
176
        }
177
178
        $this->assetManager->addRootAssetMapping($updatedMapping, $flags);
179
180
        return 0;
181
    }
182
183
    public function handleDelete(Args $args)
184
    {
185
        $mapping = $this->getMappingByUuidPrefix($args->getArgument('uuid'));
186
187
        $this->assetManager->removeRootAssetMapping($mapping->getUuid());
188
189
        return 0;
190
    }
191
192
    public function handleInstall(Args $args, IO $io)
193
    {
194
        if ($args->isArgumentSet('server')) {
195
            $expr = Expr::method('getServerName', Expr::same($args->getArgument('server')));
196
            $mappings = $this->assetManager->findAssetMappings($expr);
197
        } else {
198
            $mappings = $this->assetManager->getAssetMappings();
199
        }
200
201
        if (!$mappings) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $mappings of type Puli\Manager\Api\Asset\AssetMapping[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
202
            $io->writeLine('Nothing to install.');
203
204
            return 0;
205
        }
206
207
        /** @var InstallationParams[] $paramsToInstall */
208
        $paramsToInstall = array();
209
210
        // Prepare and validate the installation of all matching mappings
211
        foreach ($mappings as $mapping) {
212
            $paramsToInstall[] = $this->installationManager->prepareInstallation($mapping);
213
        }
214
215
        foreach ($paramsToInstall as $params) {
216
            foreach ($params->getResources() as $resource) {
217
                $serverPath = rtrim($params->getDocumentRoot(), '/').$params->getServerPathForResource($resource);
218
219
                $io->writeLine(sprintf(
220
                    'Installing <c1>%s</c1> into <c2>%s</c2> via <u>%s</u>...',
221
                    $resource->getRepositoryPath(),
222
                    trim($serverPath, '/'),
223
                    $params->getInstallerDescriptor()->getName()
224
                ));
225
226
                $this->installationManager->installResource($resource, $params);
227
            }
228
        }
229
230
        return 0;
231
    }
232
233
    /**
234
     * @param IO             $io
235
     * @param AssetMapping[] $mappings
236
     * @param bool           $enabled
237
     */
238
    private function printMappingTable(IO $io, array $mappings, $enabled = true)
239
    {
240
        $table = new Table(TableStyle::borderless());
241
242
        $globTag = $enabled ? 'c1' : 'bad';
243
        $pathTag = $enabled ? 'c2' : 'bad';
244
245
        foreach ($mappings as $mapping) {
246
            $uuid = substr($mapping->getUuid()->toString(), 0, 6);
247
            $glob = $mapping->getGlob();
248
            $serverPath = $mapping->getServerPath();
249
250
            if (!$enabled) {
251
                $uuid = sprintf('<bad>%s</bad>', $uuid);
252
            }
253
254
            $table->addRow(array(
255
                $uuid,
256
                sprintf('<%s>%s</%s>', $globTag, $glob, $globTag),
257
                sprintf('<%s>%s</%s>', $pathTag, $serverPath, $pathTag),
258
            ));
259
        }
260
261
        $table->render($io, 8);
262
    }
263
264
    /**
265
     * @param string $uuidPrefix
266
     *
267
     * @return AssetMapping
268
     */
269 View Code Duplication
    private function getMappingByUuidPrefix($uuidPrefix)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
270
    {
271
        $expr = Expr::method('getUuid', Expr::startsWith($uuidPrefix));
272
273
        $mappings = $this->assetManager->findAssetMappings($expr);
274
275
        if (!$mappings) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $mappings of type Puli\Manager\Api\Asset\AssetMapping[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
276
            throw new RuntimeException(sprintf(
277
                'The mapping with the UUID prefix "%s" does not exist.',
278
                $uuidPrefix
279
            ));
280
        }
281
282
        if (count($mappings) > 1) {
283
            throw new RuntimeException(sprintf(
284
                'More than one mapping matches the UUID prefix "%s".',
285
                $uuidPrefix
286
            ));
287
        }
288
289
        return reset($mappings);
290
    }
291
292
    private function mappingsEqual(AssetMapping $mapping1, AssetMapping $mapping2)
293
    {
294
        return $mapping1->getUuid() === $mapping2->getUuid() &&
295
            $mapping1->getGlob() === $mapping2->getGlob() &&
296
            $mapping1->getServerPath() === $mapping2->getServerPath() &&
297
            $mapping1->getServerName() === $mapping2->getServerName();
298
    }
299
}
300