Completed
Push — master ( 615409...a8a5b5 )
by Tim
11s
created

SubjectPlugin::isPartOfBunch()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 40
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 40
ccs 20
cts 20
cp 1
rs 8.8571
cc 3
eloc 21
nc 4
nop 2
crap 3
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\Subjects\SubjectFactoryInterface;
29
use TechDivision\Import\Exceptions\LineNotFoundException;
30
use TechDivision\Import\Exceptions\MissingOkFileException;
31
use TechDivision\Import\Subjects\ExportableSubjectInterface;
32
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
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
     * The subject factory instance.
76
     *
77
     * @var \TechDivision\Import\Subjects\SubjectFactoryInterface
78
     */
79
    protected $subjectFactory;
80
81
    /**
82
     * Initializes the plugin with the application instance.
83
     *
84
     * @param \TechDivision\Import\ApplicationInterface             $application     The application instance
85
     * @param \TechDivision\Import\Callbacks\CallbackVisitor        $callbackVisitor The callback visitor instance
86
     * @param \TechDivision\Import\Observers\ObserverVisitor        $observerVisitor The observer visitor instance
87
     * @param \TechDivision\Import\Subjects\SubjectFactoryInterface $subjectFactory  The subject factory instance
88
     */
89 3
    public function __construct(
90
        ApplicationInterface $application,
91
        CallbackVisitor $callbackVisitor,
92
        ObserverVisitor $observerVisitor,
93
        SubjectFactoryInterface $subjectFactory
94
    ) {
95
96
        // call the parent constructor
97 3
        parent::__construct($application);
98
99
        // initialize the callback/observer visitors
100 3
        $this->callbackVisitor = $callbackVisitor;
101 3
        $this->observerVisitor = $observerVisitor;
102 3
        $this->subjectFactory = $subjectFactory;
103 3
    }
104
105
106
    /**
107
     * Process the plugin functionality.
108
     *
109
     * @return void
110
     * @throws \Exception Is thrown, if the plugin can not be processed
111
     */
112 1
    public function process()
113
    {
114
        try {
115
            // immediately add the PID to lock this import process
116 1
            $this->lock();
117
118
            // load the plugin's subjects
119 1
            $subjects = $this->getPluginConfiguration()->getSubjects();
120
121
            // initialize the array for the status
122 1
            $status = array();
123
124
            // initialize the status information for the subjects
125
            /** @var \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject */
126 1
            foreach ($subjects as $subject) {
127
                $status[$subject->getPrefix()] = array();
128
            }
129
130
            // and update it in the registry
131 1
            $this->getRegistryProcessor()->mergeAttributesRecursive($this->getSerial(), $status);
132
133
            // process all the subjects found in the system configuration
134
            /** @var \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject */
135 1
            foreach ($subjects as $subject) {
136
                $this->processSubject($subject);
137
            }
138
139
            // update the number of imported bunches
140 1
            $this->getRegistryProcessor()->mergeAttributesRecursive(
141 1
                $this->getSerial(),
142 1
                array(RegistryKeys::BUNCHES => $this->bunches)
143
            );
144
145
            // stop the application if we don't process ANY bunch
146 1
            if ($this->bunches === 0) {
147 1
                $this->getApplication()->stop(
148 1
                    sprintf(
149 1
                        'Operation %s has been stopped by %s, because no import files has been found in directory %s',
150 1
                        $this->getConfiguration()->getOperationName(),
151 1
                        get_class($this),
152 1
                        $this->getConfiguration()->getSourceDir()
153
                    )
154
                );
155
            }
156
157
            // finally, if a PID has been set (because CSV files has been found),
158
            // remove it from the PID file to unlock the importer
159 1
            $this->unlock();
160
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
161
        } catch (\Exception $e) {
162
            // finally, if a PID has been set (because CSV files has been found),
163
            // remove it from the PID file to unlock the importer
164
            $this->unlock();
165
166
            // re-throw the exception
167
            throw $e;
168
        }
169 1
    }
170
171
    /**
172
     * Process the subject with the passed name/identifier.
173
     *
174
     * We create a new, fresh and separate subject for EVERY file here, because this would be
175
     * the starting point to parallelize the import process in a multithreaded/multiprocessed
176
     * environment.
177
     *
178
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject The subject configuration
179
     *
180
     * @return void
181
     * @throws \Exception Is thrown, if the subject can't be processed
182
     */
183
    protected function processSubject(SubjectConfigurationInterface $subject)
184
    {
185
186
        // clear the filecache
187
        clearstatcache();
188
189
        // load the actual status
190
        $status = $this->getRegistryProcessor()->getAttribute($serial = $this->getSerial());
191
192
        // query whether or not the configured source directory is available
193 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...
194
            throw new \Exception(sprintf('Source directory %s for subject %s is not available!', $sourceDir, $subject->getId()));
195
        }
196
197
        // initialize the array with the CSV files found in the source directory
198
        $files = glob(sprintf('%s/*.csv', $sourceDir));
199
200
        // sorting the files for the apropriate order
201
        usort($files, function ($a, $b) {
202
            return strcmp($a, $b);
203
        });
204
205
        // log a debug message
206
        $this->getSystemLogger()->debug(sprintf('Now checking directory %s for files to be imported', $sourceDir));
207
208
        // initialize the bunch number
209
        $bunches = 0;
210
211
        // load the container instance from the application
212
        $container = $this->getApplication()->getContainer();
0 ignored issues
show
Unused Code introduced by
$container 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...
213
214
        // iterate through all CSV files and process the subjects
215
        foreach ($files as $pathname) {
216
            // query whether or not that the file is part of the actual bunch
217
            if ($this->isPartOfBunch($subject->getPrefix(), $pathname)) {
218
                try {
219
                    // initialize the subject and import the bunch
220
                    $subjectInstance = $this->subjectFactory->createSubject($subject);
221
222
                    // setup the subject instance
223
                    $subjectInstance->setUp($serial);
224
225
                    // initialize the callbacks/observers
226
                    $this->callbackVisitor->visit($subjectInstance);
227
                    $this->observerVisitor->visit($subjectInstance);
228
229
                    // query whether or not the subject needs an OK file,
230
                    // if yes remove the filename from the file
231
                    if ($subjectInstance->isOkFileNeeded()) {
232
                        $this->removeFromOkFile($pathname);
233
                    }
234
235
                    // finally import the CSV file
236
                    $subjectInstance->import($serial, $pathname);
237
238
                    // query whether or not, we've to export artefacts
239
                    if ($subjectInstance instanceof ExportableSubjectInterface) {
240
                        $subjectInstance->export(
241
                            $this->matches[BunchKeys::FILENAME],
242
                            $this->matches[BunchKeys::COUNTER]
243
                        );
244
                    }
245
246
                    // raise the number of the imported bunches
247
                    $bunches++;
248
249
                    // tear down the subject instance
250
                    $subjectInstance->tearDown($serial);
251
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
252
                } catch (\Exception $e) {
253
                    // query whether or not, we've to export artefacts
254
                    if ($subjectInstance instanceof ExportableSubjectInterface) {
255
                        // tear down the subject instance
256
                        $subjectInstance->tearDown($serial);
257
                    }
258
259
                    // re-throw the exception
260
                    throw $e;
261
                }
262
            }
263
        }
264
265
        // raise the bunch number by the imported bunches
266
        $this->bunches = $this->bunches + $bunches;
267
268
        // reset the matches, because the exported artefacts
269
        $this->matches = array();
270
271
        // and and log a message that the subject has been processed
272
        $this->getSystemLogger()->debug(
273
            sprintf('Successfully processed subject %s with %d bunch(es)!', $subject->getId(), $bunches)
274
        );
275
    }
276
277
    /**
278
     * Queries whether or not, the passed filename is part of a bunch or not.
279
     *
280
     * @param string $prefix   The prefix to query for
281
     * @param string $filename The filename to query for
282
     *
283
     * @return boolean TRUE if the filename is part, else FALSE
284
     */
285 2
    protected function isPartOfBunch($prefix, $filename)
286
    {
287
288
        // initialize the pattern
289 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...
290
291
        // query whether or not, this is the first file to be processed
292 2
        if (sizeof($this->matches) === 0) {
293
            // initialize the pattern to query whether the FIRST file has to be processed or not
294 2
            $pattern = sprintf(
295 2
                '/^.*\/(?<%s>%s)_(?<%s>.*)_(?<%s>\d+)\\.csv$/',
296 2
                BunchKeys::PREFIX,
297 2
                $prefix,
298 2
                BunchKeys::FILENAME,
299 2
                BunchKeys::COUNTER
300
            );
301
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
302
        } else {
303
            // initialize the pattern to query whether the NEXT file is part of a bunch or not
304 2
            $pattern = sprintf(
305 2
                '/^.*\/(?<%s>%s)_(?<%s>%s)_(?<%s>\d+)\\.csv$/',
306 2
                BunchKeys::PREFIX,
307 2
                $this->matches[BunchKeys::PREFIX],
308 2
                BunchKeys::FILENAME,
309 2
                $this->matches[BunchKeys::FILENAME],
310 2
                BunchKeys::COUNTER
311
            );
312
        }
313
314
        // initialize the array for the matches
315 2
        $matches = array();
316
317
        // update the matches, if the pattern matches
318 2
        if ($result = preg_match($pattern, $filename, $matches)) {
319 2
            $this->matches = $matches;
320
        }
321
322
        // stop processing, if the filename doesn't match
323 2
        return (boolean) $result;
324
    }
325
326
    /**
327
     * Return's an array with the names of the expected OK files for the actual subject.
328
     *
329
     * @return array The array with the expected OK filenames
330
     */
331
    protected function getOkFilenames()
332
    {
333
334
        // load the array with the available bunch keys
335
        $bunchKeys = BunchKeys::getAllKeys();
336
337
        // initialize the array for the available okFilenames
338
        $okFilenames = array();
339
340
        // prepare the OK filenames based on the found CSV file information
341
        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...
342
            // intialize the array for the parts of the names (prefix, filename + counter)
343
            $parts = array();
344
            // load the parts from the matches
345
            for ($z = 0; $z < $i; $z++) {
346
                $parts[] = $this->matches[$bunchKeys[$z]];
347
            }
348
349
            // query whether or not, the OK file exists, if yes append it
350
            if (file_exists($okFilename = sprintf('%s/%s.ok', $this->getSourceDir(), implode('_', $parts)))) {
351
                $okFilenames[] = $okFilename;
352
            }
353
        }
354
355
        // prepare and return the pattern for the OK file
356
        return $okFilenames;
357
    }
358
359
    /**
360
     * Query whether or not, the passed CSV filename is in the OK file. If the filename was found,
361
     * it'll be returned and the method return TRUE.
362
     *
363
     * If the filename is NOT in the OK file, the method return's FALSE and the CSV should NOT be
364
     * imported/moved.
365
     *
366
     * @param string $filename The CSV filename to query for
367
     *
368
     * @return void
369
     * @throws \Exception Is thrown, if the passed filename is NOT in the OK file or it can NOT be removed from it
370
     */
371
    protected function removeFromOkFile($filename)
372
    {
373
374
        try {
375
            // try to load the expected OK filenames
376
            if (sizeof($okFilenames = $this->getOkFilenames()) === 0) {
377
                throw new MissingOkFileException(sprintf('Can\'t find a OK filename for file %s', $filename));
378
            }
379
380
            // iterate over the found OK filenames (should usually be only one, but could be more)
381
            foreach ($okFilenames as $okFilename) {
382
                // if the OK filename matches the CSV filename AND the OK file is empty
383
                if (basename($filename, '.csv') === basename($okFilename, '.ok') && filesize($okFilename) === 0) {
384
                    unlink($okFilename);
385
                    return;
386
                }
387
388
                // else, remove the CSV filename from the OK file
389
                $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...
390
                fclose($fh);
391
392
                // if the OK file is empty, delete the file
393
                if (filesize($okFilename) === 0) {
394
                    unlink($okFilename);
395
                }
396
397
                // return immediately
398
                return;
399
            }
400
401
            // throw an exception if either no OK file has been found,
402
            // or the CSV file is not in one of the OK files
403
            throw new \Exception(
404
                sprintf(
405
                    'Can\'t found filename %s in one of the expected OK files: %s',
406
                    $filename,
407
                    implode(', ', $okFilenames)
408
                )
409
            );
410
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
411
        } catch (LineNotFoundException $lne) {
412
            // wrap and re-throw the exception
413
            throw new \Exception(
414
                sprintf(
415
                    'Can\'t remove filename %s from OK file: %s',
416
                    $filename,
417
                    $okFilename
418
                ),
419
                null,
420
                $lne
421
            );
422
        }
423
    }
424
}
425