Completed
Pull Request — master (#68)
by Tim
03:18
created

SubjectPlugin::process()   B

Complexity

Conditions 5
Paths 35

Size

Total Lines 58
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 4
Bugs 0 Features 0
Metric Value
dl 0
loc 58
ccs 0
cts 30
cp 0
rs 8.7274
c 4
b 0
f 0
cc 5
eloc 24
nc 35
nop 0
crap 30

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * TechDivision\Import\Plugins\SubjectPlugin
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 2016 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
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Plugins;
22
23
use TechDivision\Import\Utils\BunchKeys;
24
use TechDivision\Import\Utils\RegistryKeys;
25
use TechDivision\Import\ApplicationInterface;
26
use TechDivision\Import\Callbacks\CallbackVisitor;
27
use TechDivision\Import\Observers\ObserverVisitor;
28
use TechDivision\Import\Exceptions\LineNotFoundException;
29
use TechDivision\Import\Exceptions\MissingOkFileException;
30
use TechDivision\Import\Subjects\ExportableSubjectInterface;
31
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
32
use TechDivision\Import\Configuration\PluginConfigurationInterface;
33
34
/**
35
 * Plugin that processes the subjects.
36
 *
37
 * @author    Tim Wagner <[email protected]>
38
 * @copyright 2016 TechDivision GmbH <[email protected]>
39
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
40
 * @link      https://github.com/techdivision/import
41
 * @link      http://www.techdivision.com
42
 */
43
class SubjectPlugin extends AbstractPlugin
44
{
45
46
    /**
47
     * The matches for the last processed CSV filename.
48
     *
49
     * @var array
50
     */
51
    protected $matches = array();
52
53
    /**
54
     * The number of imported bunches.
55
     *
56
     * @var integer
57
     */
58
    protected $bunches = 0;
59
60
    /**
61
     * The callback visitor instance.
62
     *
63
     * @var \TechDivision\Import\Callbacks\CallbackVisitor
64
     */
65
    protected $callbackVisitor;
66
67
    /**
68
     * The observer visitor instance.
69
     *
70
     * @var \TechDivision\Import\Observers\ObserverVisitor
71
     */
72
    protected $observerVisitor;
73
74
    /**
75
     * Initializes the plugin with the application instance.
76
     *
77
     * @param \TechDivision\Import\ApplicationInterface                       $application         The application instance
78
     * @param \TechDivision\Import\Configuration\PluginConfigurationInterface $pluginConfiguration The plugin configuration instance
79
     * @param \TechDivision\Import\Callbacks\CallbackVisitor                  $callbackVisitor     The callback visitor instance
80
     * @param \TechDivision\Import\Observers\ObserverVisitor                  $observerVisitor     The observer visitor instance
81
     */
82 2
    public function __construct(
83
        ApplicationInterface $application,
84
        PluginConfigurationInterface $pluginConfiguration,
85
        CallbackVisitor $callbackVisitor,
86
        ObserverVisitor $observerVisitor
87
    ) {
88
89
        // call the parent constructor
90 2
        parent::__construct($application, $pluginConfiguration);
91
92
        // initialize the callback/observer visitors
93 2
        $this->callbackVisitor = $callbackVisitor;
94 2
        $this->observerVisitor = $observerVisitor;
95 2
    }
96
97
98
    /**
99
     * Process the plugin functionality.
100
     *
101
     * @return void
102
     * @throws \Exception Is thrown, if the plugin can not be processed
103
     */
104
    public function process()
105
    {
106
        try {
107
            // immediately add the PID to lock this import process
108
            $this->lock();
109
110
            // load the plugin's subjects
111
            $subjects = $this->getPluginConfiguration()->getSubjects();
112
113
            // initialize the array for the status
114
            $status = array();
115
116
            // initialize the status information for the subjects
117
            /** @var \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject */
118
            foreach ($subjects as $subject) {
119
                $status[$subject->getPrefix()] = array();
120
            }
121
122
            // and update it in the registry
123
            $this->getRegistryProcessor()->mergeAttributesRecursive($this->getSerial(), $status);
124
125
            // process all the subjects found in the system configuration
126
            /** @var \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject */
127
            foreach ($subjects as $subject) {
128
                $this->processSubject($subject);
129
            }
130
131
            // update the number of imported bunches
132
            $this->getRegistryProcessor()->mergeAttributesRecursive(
133
                $this->getSerial(),
134
                array(RegistryKeys::BUNCHES => $this->bunches)
135
            );
136
137
            // stop the application if we don't process ANY bunch
138
            if ($this->bunches === 0) {
139
                $this->getApplication()->stop(
140
                    sprintf(
141
                        'Operation %s has been stopped by %s, because no import files has been found in directory %s',
142
                        $this->getConfiguration()->getOperationName(),
143
                        get_class($this),
144
                        $this->getConfiguration()->getSourceDir()
145
                    )
146
                );
147
            }
148
149
            // finally, if a PID has been set (because CSV files has been found),
150
            // remove it from the PID file to unlock the importer
151
            $this->unlock();
152
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
153
        } catch (\Exception $e) {
154
            // finally, if a PID has been set (because CSV files has been found),
155
            // remove it from the PID file to unlock the importer
156
            $this->unlock();
157
158
            // re-throw the exception
159
            throw $e;
160
        }
161
    }
162
163
    /**
164
     * Process the subject with the passed name/identifier.
165
     *
166
     * We create a new, fresh and separate subject for EVERY file here, because this would be
167
     * the starting point to parallelize the import process in a multithreaded/multiprocessed
168
     * environment.
169
     *
170
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject The subject configuration
171
     *
172
     * @return void
173
     * @throws \Exception Is thrown, if the subject can't be processed
174
     */
175
    protected function processSubject(SubjectConfigurationInterface $subject)
176
    {
177
178
        // clear the filecache
179
        clearstatcache();
180
181
        // load the actual status
182
        $status = $this->getRegistryProcessor()->getAttribute($serial = $this->getSerial());
183
184
        // query whether or not the configured source directory is available
185 View Code Duplication
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
186
            throw new \Exception(sprintf('Source directory %s for subject %s is not available!', $sourceDir, $subject->getId()));
187
        }
188
189
        // initialize the array with the CSV files found in the source directory
190
        $files = glob(sprintf('%s/*.csv', $sourceDir));
191
192
        // sorting the files for the apropriate order
193
        usort($files, function ($a, $b) {
194
            return strcmp($a, $b);
195
        });
196
197
        // log a debug message
198
        $this->getSystemLogger()->debug(sprintf('Now checking directory %s for files to be imported', $sourceDir));
199
200
        // initialize the bunch number
201
        $bunches = 0;
202
203
        // iterate through all CSV files and process the subjects
204
        foreach ($files as $pathname) {
205
            // query whether or not that the file is part of the actual bunch
206
            if ($this->isPartOfBunch($subject->getPrefix(), $pathname)) {
207
                try {
208
                    // initialize the subject and import the bunch
209
                    $subjectInstance = $this->subjectFactory($subject);
210
211
                    // setup the subject instance
212
                    $subjectInstance->setUp($serial);
213
214
                    // initialize the callbacks/observers
215
                    $this->callbackVisitor->visit($subjectInstance);
216
                    $this->observerVisitor->visit($subjectInstance);
217
218
                    // query whether or not the subject needs an OK file,
219
                    // if yes remove the filename from the file
220
                    if ($subjectInstance->isOkFileNeeded()) {
221
                        $this->removeFromOkFile($pathname);
222
                    }
223
224
                    // finally import the CSV file
225
                    $subjectInstance->import($serial, $pathname);
226
227
                    // query whether or not, we've to export artefacts
228
                    if ($subjectInstance instanceof ExportableSubjectInterface) {
229
                        $subjectInstance->export(
230
                            $this->matches[BunchKeys::FILENAME],
231
                            $this->matches[BunchKeys::COUNTER]
232
                        );
233
                    }
234
235
                    // raise the number of the imported bunches
236
                    $bunches++;
237
238
                    // tear down the subject instance
239
                    $subjectInstance->tearDown($serial);
240
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
241
                } catch (\Exception $e) {
242
                    // query whether or not, we've to export artefacts
243
                    if ($subjectInstance instanceof ExportableSubjectInterface) {
244
                        // tear down the subject instance
245
                        $subjectInstance->tearDown($serial);
0 ignored issues
show
Bug introduced by
The method tearDown() does not seem to exist on object<TechDivision\Impo...rtableSubjectInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
246
                    }
247
248
                    // re-throw the exception
249
                    throw $e;
250
                }
251
            }
252
        }
253
254
        // raise the bunch number by the imported bunches
255
        $this->bunches = $this->bunches + $bunches;
256
257
        // reset the matches, because the exported artefacts
258
        $this->matches = array();
259
260
        // and and log a message that the subject has been processed
261
        $this->getSystemLogger()->debug(
262
            sprintf('Successfully processed subject %s with %d bunch(es)!', $subject->getId(), $bunches)
263
        );
264
    }
265
266
    /**
267
     * Factory method to create new handler instances.
268
     *
269
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subjectConfiguration The subject configuration
270
     *
271
     * @return object The handler instance
272
     */
273
    protected function subjectFactory(SubjectConfigurationInterface $subjectConfiguration)
274
    {
275
        $this->getApplication()->getContainer()->set(sprintf('configuration.%s', $id = $subjectConfiguration->getId()), $subjectConfiguration);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<TechDivision\Import\ApplicationInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
276
        return $this->getApplication()->getContainer()->get($id);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<TechDivision\Import\ApplicationInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
277
    }
278
279
    /**
280
     * Queries whether or not, the passed filename is part of a bunch or not.
281
     *
282
     * @param string $prefix   The prefix to query for
283
     * @param string $filename The filename to query for
284
     *
285
     * @return boolean TRUE if the filename is part, else FALSE
286
     */
287 2
    protected function isPartOfBunch($prefix, $filename)
288
    {
289
290
        // initialize the pattern
291 2
        $pattern = '';
0 ignored issues
show
Unused Code introduced by
$pattern 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...
292
293
        // query whether or not, this is the first file to be processed
294 2
        if (sizeof($this->matches) === 0) {
295
            // initialize the pattern to query whether the FIRST file has to be processed or not
296 2
            $pattern = sprintf(
297 2
                '/^.*\/(?<%s>%s)_(?<%s>.*)_(?<%s>\d+)\\.csv$/',
298 2
                BunchKeys::PREFIX,
299 2
                $prefix,
300 2
                BunchKeys::FILENAME,
301
                BunchKeys::COUNTER
302 2
            );
303
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
304 2
        } else {
305
            // initialize the pattern to query whether the NEXT file is part of a bunch or not
306 2
            $pattern = sprintf(
307 2
                '/^.*\/(?<%s>%s)_(?<%s>%s)_(?<%s>\d+)\\.csv$/',
308 2
                BunchKeys::PREFIX,
309 2
                $this->matches[BunchKeys::PREFIX],
310 2
                BunchKeys::FILENAME,
311 2
                $this->matches[BunchKeys::FILENAME],
312
                BunchKeys::COUNTER
313 2
            );
314
        }
315
316
        // initialize the array for the matches
317 2
        $matches = array();
318
319
        // update the matches, if the pattern matches
320 2
        if ($result = preg_match($pattern, $filename, $matches)) {
321 2
            $this->matches = $matches;
322 2
        }
323
324
        // stop processing, if the filename doesn't match
325 2
        return (boolean) $result;
326
    }
327
328
    /**
329
     * Return's an array with the names of the expected OK files for the actual subject.
330
     *
331
     * @return array The array with the expected OK filenames
332
     */
333
    protected function getOkFilenames()
334
    {
335
336
        // load the array with the available bunch keys
337
        $bunchKeys = BunchKeys::getAllKeys();
338
339
        // initialize the array for the available okFilenames
340
        $okFilenames = array();
341
342
        // prepare the OK filenames based on the found CSV file information
343
        for ($i = 1; $i <= sizeof($bunchKeys); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
344
            // intialize the array for the parts of the names (prefix, filename + counter)
345
            $parts = array();
346
            // load the parts from the matches
347
            for ($z = 0; $z < $i; $z++) {
348
                $parts[] = $this->matches[$bunchKeys[$z]];
349
            }
350
351
            // query whether or not, the OK file exists, if yes append it
352
            if (file_exists($okFilename = sprintf('%s/%s.ok', $this->getSourceDir(), implode('_', $parts)))) {
353
                $okFilenames[] = $okFilename;
354
            }
355
        }
356
357
        // prepare and return the pattern for the OK file
358
        return $okFilenames;
359
    }
360
361
    /**
362
     * Query whether or not, the passed CSV filename is in the OK file. If the filename was found,
363
     * it'll be returned and the method return TRUE.
364
     *
365
     * If the filename is NOT in the OK file, the method return's FALSE and the CSV should NOT be
366
     * imported/moved.
367
     *
368
     * @param string $filename The CSV filename to query for
369
     *
370
     * @return void
371
     * @throws \Exception Is thrown, if the passed filename is NOT in the OK file or it can NOT be removed from it
372
     */
373
    protected function removeFromOkFile($filename)
374
    {
375
376
        try {
377
            // try to load the expected OK filenames
378
            if (sizeof($okFilenames = $this->getOkFilenames()) === 0) {
379
                throw new MissingOkFileException(sprintf('Can\'t find a OK filename for file %s', $filename));
380
            }
381
382
            // iterate over the found OK filenames (should usually be only one, but could be more)
383
            foreach ($okFilenames as $okFilename) {
384
                // if the OK filename matches the CSV filename AND the OK file is empty
385
                if (basename($filename, '.csv') === basename($okFilename, '.ok') && filesize($okFilename) === 0) {
386
                    unlink($okFilename);
387
                    return;
388
                }
389
390
                // else, remove the CSV filename from the OK file
391
                $this->removeLineFromFile(basename($filename), $fh = fopen($okFilename, 'r+'));
0 ignored issues
show
Documentation introduced by
$fh = fopen($okFilename, 'r+') is of type resource, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
392
                fclose($fh);
393
394
                // if the OK file is empty, delete the file
395
                if (filesize($okFilename) === 0) {
396
                    unlink($okFilename);
397
                }
398
399
                // return immediately
400
                return;
401
            }
402
403
            // throw an exception if either no OK file has been found,
404
            // or the CSV file is not in one of the OK files
405
            throw new \Exception(
406
                sprintf(
407
                    'Can\'t found filename %s in one of the expected OK files: %s',
408
                    $filename,
409
                    implode(', ', $okFilenames)
410
                )
411
            );
412
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
413
        } catch (LineNotFoundException $lne) {
414
            // wrap and re-throw the exception
415
            throw new \Exception(
416
                sprintf(
417
                    'Can\'t remove filename %s from OK file: %s',
418
                    $filename,
419
                    $okFilename
420
                ),
421
                null,
422
                $lne
423
            );
424
        }
425
    }
426
}
427