Completed
Push — pac-89--debug-report ( d250e8...fe1e24 )
by Marcus
06:10
created

DebugUtil::getApplication()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Utils\DebugUtil
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2020 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import-cli
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Utils;
22
23
use Doctrine\Common\Collections\Collection;
24
use TechDivision\Import\SystemLoggerTrait;
25
use TechDivision\Import\ApplicationInterface;
26
use TechDivision\Import\Services\RegistryProcessorInterface;
27
use TechDivision\Import\Configuration\ConfigurationInterface;
28
use TechDivision\Import\Listeners\Renderer\RendererInterface;
29
30
/**
31
 * A utility class to create cache keys.
32
 *
33
 * @author    Tim Wagner <[email protected]>
34
 * @copyright 2020 TechDivision GmbH <[email protected]>
35
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
36
 * @link      https://github.com/techdivision/import-cli
37
 * @link      http://www.techdivision.com
38
 */
39
class DebugUtil implements DebugUtilInterface
40
{
41
42
    /**
43
     * The trait that provides basic system logger functionality.
44
     *
45
     * @var \TechDivision\Import\SystemLoggerTrait
46
     */
47
    use SystemLoggerTrait;
48
49
    /**
50
     * The import processor instance.
51
     *
52
     * @var \TechDivision\Import\Services\RegistryProcessorInterface
53
     */
54
    private $registryProcessor;
55
56
    /**
57
     * The configuration instance.
58
     *
59
     * @var \TechDivision\Import\Configuration\ConfigurationInterface
60
     */
61
    private $configuration;
62
63
    /**
64
     * The debug dump renderer.
65
     *
66
     * @var \TechDivision\Import\Listeners\Renderer\RendererInterface
67
     */
68
    private $renderer;
69
70
    /**
71
     * Initializes the plugin with the application instance.
72
     *
73
     * @param \TechDivision\Import\Services\RegistryProcessorInterface  $registryProcessor The registry processor instance
74
     * @param \TechDivision\Import\Configuration\ConfigurationInterface $configuration     The configuration instance
75
     * @param \Doctrine\Common\Collections\Collection                   $systemLoggers     The array with the system loggers instances
76
     * @param \TechDivision\Import\Listeners\Renderer\RendererInterface $renderer          The debug dump renderer instance
77
     */
78
    public function __construct(
79
        RegistryProcessorInterface $registryProcessor,
80
        ConfigurationInterface $configuration,
81
        Collection $systemLoggers,
82
        RendererInterface $renderer
83
    ) {
84
        $this->registryProcessor = $registryProcessor;
85
        $this->configuration = $configuration;
86
        $this->systemLoggers = $systemLoggers;
0 ignored issues
show
Documentation Bug introduced by
It seems like $systemLoggers of type object<Doctrine\Common\Collections\Collection> is incompatible with the declared type array of property $systemLoggers.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
87
        $this->renderer = $renderer;
88
    }
89
90
    /**
91
     * Return's the registry processor instance.
92
     *
93
     * @return \TechDivision\Import\Services\RegistryProcessorInterface The registry processor instance
94
     */
95
    private function getRegistryProcessor() : RegistryProcessorInterface
96
    {
97
        return $this->registryProcessor;
98
    }
99
100
    /**
101
     * Return's the configuration instance.
102
     *
103
     * @return \TechDivision\Import\Configuration\ConfigurationInterface The configuration instance
104
     */
105
    private function getConfiguration() : ConfigurationInterface
106
    {
107
        return $this->configuration;
108
    }
109
110
    /**
111
     * Return's the debug dump renderer instance.
112
     *
113
     * @return \TechDivision\Import\Listeners\Renderer\RendererInterface The debug dump renderer instance
114
     */
115
    private function getRenderer() : RendererInterface
116
    {
117
        return $this->renderer;
118
    }
119
120
    /**
121
     * The method to extract an archive that has already been created by a previous
122
     * import back into the source directory.
123
     *
124
     * @param string $serial The serial of the archive to extract
125
     *
126
     * @return void
127
     * @throws \Exception Is thrown, if the archive can not be extracted back into the source directory
128
     */
129
    public function extractArchive(string $serial) : void
130
    {
131
132
        // clear the filecache
133
        clearstatcache();
134
135
        // load the actual status
136
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
137
138
        // query whether or not the configured source directory is available
139
        if (isset($status[RegistryKeys::SOURCE_DIRECTORY])) {
140
            $sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY];
141
        } else {
142
            throw new \Exception('Source directory is not available!');
143
        }
144
145
        // try to load the archive directory
146
        $archiveDir = $this->getConfiguration()->getArchiveDir();
147
148
        // query whether or not the specified archive directory already exists
149
        if ($archiveDir === null) {
150
            $archiveDir = sprintf('var/import_history');
151
        }
152
153
        // initialize the ZIP instance
154
        $zip = new \ZipArchive();
155
156
        // prepare the archive filename
157
        $archiveFile = sprintf('%s/%s.zip', $archiveDir, $serial);
158
159
        // query whether or not the directory already exists
160
        if (is_dir($sourceDir)) {
161
            // log a warning and stop extracting the files
162
            $this->getSystemLogger()->warning(
163
                sprintf(
164
                    'Won\'t extract artefacts of "%s" for serial "%s" to directory "%s", because directory already exists',
165
                    $archiveFile,
166
                    $serial,
167
                    $sourceDir
168
                )
169
            );
170
171
            // stop processing the file extraction of the ZIP file
172
            return;
173
        }
174
175
        // try to open and extract the ZIP archive
176
        if (is_file($archiveFile)) {
177
            if ($zip->open($archiveFile) === true) {
178
                $zip->extractTo($sourceDir);
179
                $zip->close();
180
            } else {
181
                throw new \Exception(sprintf('Can\'t extract archive "%s" back into source directory', $archiveFile));
182
            }
183
        } else {
184
            $this->getSystemLogger()->debug(sprintf('"%s" is not available and can not be extracted therefore', $archiveFile));
185
        }
186
187
        // log a message that the file has successfully been extracted
188
        $this->getSystemLogger()->info(sprintf('Successfully extracted artefacts for serial "%s" to directory %s', $serial, $sourceDir));
189
    }
190
191
    /**
192
     * The method to create the debugging artefacts in the appropriate directory.
193
     *
194
     * @param string $serial The serial to prepare the dump for
195
     *
196
     * @return void
197
     * @throws \Exception Is thrown, if the configuration can not be dumped
198
     */
199 View Code Duplication
    public function prepareDump(string $serial) : void
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...
200
    {
201
202
        // load the actual status
203
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
204
205
        // clear the filecache
206
        clearstatcache();
207
208
        // query whether or not the configured source directory is available
209
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
210
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
211
        }
212
213
        // render the debug artefacts
214
        $this->getRenderer()->render($serial);
0 ignored issues
show
Unused Code introduced by
The call to RendererInterface::render() has too many arguments starting with $serial.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
215
216
        // log a message that the debug artefacts has successfully been rendered
217
        $this->getSystemLogger()->info(sprintf('Successfully rendered the debug artefacts for serial "%s"', $serial));
218
    }
219
220
    /**
221
     * The method to create the debug dump with all artefacts and reports.
222
     *
223
     * @param string $serial The serial to create the dump for
224
     *
225
     * @return string $filename The name of the dumpfile
226
     * @throws \InvalidArgumentException Is thrown, if the passed serial has no matching import to create the dump for
227
     */
228
    public function createDump(string $serial) : string
229
    {
230
231
        // initialize the dump filename
232
        $dumpFile = null;
0 ignored issues
show
Unused Code introduced by
$dumpFile is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
233
234
        // load the actual status
235
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
236
237
        // clear the filecache
238
        clearstatcache();
239
240
        // query whether or not the configured source directory is available
241
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
242
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
243
        }
244
245
        // create the ZIP archive
246
        $dumpFile = new \ZipArchive();
247
        $dumpFile->open($dumpFilename = sprintf('%s/%s.zip', sys_get_temp_dir(), $serial), \ZipArchive::CREATE);
248
249
        // init file iterator on source directory
250
        $fileIterator = new \FilesystemIterator($sourceDir);
251
252
        // iterate through all files and add them to the ZIP archive
253
        /** @var \SplFileInfo $filename */
254
        foreach ($fileIterator as $filename) {
255
            if ($filename->isFile()) {
256
                $dumpFile->addFile($filename, basename($filename));
257
            }
258
        }
259
260
        // save the ZIP archive
261
        $dumpFile->close();
262
263
        // log a message that the dump has successfully been created
264
        $this->getSystemLogger()->info(sprintf('Successfully created dump "%s" with artefacts for serial "%s"', $dumpFilename, $serial));
265
266
        // return the filename of the dump
267
        return $dumpFilename;
268
    }
269
}
270