Completed
Push — master ( a7caf4...17170d )
by Tim
10s
created

SubjectPlugin::getOkFilenames()   B

Complexity

Conditions 4
Paths 5

Size

Total Lines 27
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 27
c 0
b 0
f 0
ccs 0
cts 15
cp 0
rs 8.5806
cc 4
eloc 10
nc 5
nop 0
crap 20
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\Subjects\ExportableSubjectInterface;
27
use TechDivision\Import\Cli\Exceptions\LineNotFoundException;
28
use TechDivision\Import\Cli\Exceptions\FileNotFoundException;
29
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
30
31
/**
32
 * Plugin that processes the subjects.
33
 *
34
 * @author    Tim Wagner <[email protected]>
35
 * @copyright 2016 TechDivision GmbH <[email protected]>
36
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
37
 * @link      https://github.com/techdivision/import
38
 * @link      http://www.techdivision.com
39
 */
40
class SubjectPlugin extends AbstractPlugin
41
{
42
43
    /**
44
     * The matches for the last processed CSV filename.
45
     *
46
     * @var array
47
     */
48
    protected $matches = array();
49
50
    /**
51
     * The number of imported bunches.
52
     *
53
     * @var integer
54
     */
55
    protected $bunches = 0;
56
57
    /**
58
     * Process the plugin functionality.
59
     *
60
     * @return void
61
     * @throws \Exception Is thrown, if the plugin can not be processed
62
     */
63
    public function process()
64
    {
65
        try {
66
            // immediately add the PID to lock this import process
67
            $this->lock();
68
69
            // load system logger and registry
70
            $importProcessor = $this->getImportProcessor();
71
72
            // start the transaction
73
            $importProcessor->getConnection()->beginTransaction();
74
75
            // load the plugin's subjects
76
            $subjects = $this->getPluginConfiguration()->getSubjects();
77
78
            // initialize the status information for the subjects */
79
            /** @var \TechDivision\Import\Configuration\SubjectInterface $subject */
80
            foreach ($subjects as $subject) {
81
                $status[$subject->getPrefix()] = array();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$status was never initialized. Although not strictly required by PHP, it is generally a good practice to add $status = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
82
            }
83
84
            // append it to the registry
85
            $this->getRegistryProcessor()->mergeAttributesRecursive($this->getSerial(), $status);
0 ignored issues
show
Bug introduced by
The variable $status does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
86
87
            // process all the subjects found in the system configuration
88
            foreach ($subjects as $subject) {
89
                $this->processSubject($subject);
90
            }
91
92
            // update the number of imported bunches
93
            $this->getRegistryProcessor()->mergeAttributesRecursive(
94
                $this->getSerial(),
95
                array(RegistryKeys::BUNCHES => $this->bunches)
96
            );
97
98
            // finally, if a PID has been set (because CSV files has been found),
99
            // remove it from the PID file to unlock the importer
100
            $this->unlock();
101
102
            // commit the transaction
103
            $importProcessor->getConnection()->commit();
104
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
105
        } catch (\Exception $e) {
106
            // finally, if a PID has been set (because CSV files has been found),
107
            // remove it from the PID file to unlock the importer
108
            $this->unlock();
109
            // rollback the transaction
110
            $importProcessor->getConnection()->rollBack();
0 ignored issues
show
Bug introduced by
The variable $importProcessor does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
111
112
            // re-throw the exception
113
            throw $e;
114
        }
115
    }
116
117
    /**
118
     * Process the subject with the passed name/identifier.
119
     *
120
     * We create a new, fresh and separate subject for EVERY file here, because this would be
121
     * the starting point to parallelize the import process in a multithreaded/multiprocessed
122
     * environment.
123
     *
124
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject The subject configuration
125
     *
126
     * @return void
127
     * @throws \Exception Is thrown, if the subject can't be processed
128
     */
129
    protected function processSubject(SubjectConfigurationInterface $subject)
130
    {
131
132
        // clear the filecache
133
        clearstatcache();
134
135
        // load the actual status
136
        $status = $this->getRegistryProcessor()->getAttribute($serial = $this->getSerial());
137
138
        // query whether or not the configured source directory is available
139 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...
140
            throw new \Exception(sprintf('Source directory %s for subject %s is not available!', $sourceDir, $subject->getClassName()));
141
        }
142
143
        // initialize the array with the CSV files found in the source directory
144
        $files = glob(sprintf('%s/*.csv', $sourceDir));
145
146
        // sorting the files for the apropriate order
147
        usort($files, function ($a, $b) {
148
            return strcmp($a, $b);
149
        });
150
151
        // log a debug message
152
        $this->getSystemLogger()->debug(sprintf('Now checking directory %s for files to be imported', $sourceDir));
153
154
        // initialize the bunch number
155
        $bunches = 0;
156
157
        // iterate through all CSV files and process the subjects
158
        foreach ($files as $pathname) {
159
            // query whether or not that the file is part of the actual bunch
160
            if ($this->isPartOfBunch($subject->getPrefix(), $pathname)) {
161
                // initialize the subject and import the bunch
162
                $subjectInstance = $this->subjectFactory($subject);
163
164
                // query whether or not the subject needs an OK file,
165
                // if yes remove the filename from the file
166
                if ($subjectInstance->isOkFileNeeded()) {
167
                    $this->removeFromOkFile($pathname);
168
                }
169
170
                // finally import the CSV file
171
                $subjectInstance->import($serial, $pathname);
172
173
                // query whether or not, we've to export artefacts
174
                if ($subjectInstance instanceof ExportableSubjectInterface) {
175
                    $subjectInstance->export(
176
                        $this->matches[BunchKeys::FILENAME],
177
                        $this->matches[BunchKeys::COUNTER]
178
                    );
179
                }
180
181
                // raise the number of the imported bunches
182
                $bunches++;
183
            }
184
        }
185
186
        // raise the bunch number by the imported bunches
187
        $this->bunches = $this->bunches + $bunches;
188
189
        // reset the matches, because the exported artefacts
190
        $this->matches = array();
191
192
        // and and log a message that the subject has been processed
193
        $this->getSystemLogger()->debug(
194
            sprintf('Successfully processed subject %s with %d bunch(es)!', $subject->getClassName(), $bunches)
195
        );
196
    }
197
198
    /**
199
     * Factory method to create new handler instances.
200
     *
201
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subjectConfiguration The subject configuration
202
     *
203
     * @return object The handler instance
204
     */
205
    protected function subjectFactory(SubjectConfigurationInterface $subjectConfiguration)
206
    {
207
208
        // load the subject class name
209
        $className = $subjectConfiguration->getClassName();
210
211
        // initialize the instances
212
        $productProcessor = null;
213
        $systemLogger = $this->getSystemLogger();
214
        $registryProcessor = $this->getRegistryProcessor();
215
216
        // instanciate and set the product processor, if specified
217
        if ($processorFactory = $subjectConfiguration->getProcessorFactory()) {
218
            $productProcessor = $processorFactory::factory(
219
                $this->getImportProcessor()->getConnection(),
220
                $subjectConfiguration
221
            );
222
        }
223
224
        // initialize a new handler with the passed class name
225
        return new $className(
226
            $systemLogger,
227
            $subjectConfiguration,
228
            $registryProcessor,
229
            $productProcessor
230
        );
231
    }
232
233
    /**
234
     * Queries whether or not, the passed filename is part of a bunch or not.
235
     *
236
     * @param string $prefix   The prefix to query for
237
     * @param string $filename The filename to query for
238
     *
239
     * @return boolean TRUE if the filename is part, else FALSE
240
     */
241
    protected function isPartOfBunch($prefix, $filename)
242
    {
243
244
        // initialize the pattern
245
        $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...
246
247
        // query whether or not, this is the first file to be processed
248
        if (sizeof($this->matches) === 0) {
249
            // initialize the pattern to query whether the FIRST file has to be processed or not
250
            $pattern = sprintf(
251
                '/^.*\/(?<%s>%s)_(?<%s>.*)_(?<%s>\d+)\\.csv$/',
252
                BunchKeys::PREFIX,
253
                $prefix,
254
                BunchKeys::FILENAME,
255
                BunchKeys::COUNTER
256
            );
257
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
258
        } else {
259
            // initialize the pattern to query whether the NEXT file is part of a bunch or not
260
            $pattern = sprintf(
261
                '/^.*\/(?<%s>%s)_(?<%s>%s)_(?<%s>\d+)\\.csv$/',
262
                BunchKeys::PREFIX,
263
                $this->matches[BunchKeys::PREFIX],
264
                BunchKeys::FILENAME,
265
                $this->matches[BunchKeys::FILENAME],
266
                BunchKeys::COUNTER
267
            );
268
        }
269
270
        // initialize the array for the matches
271
        $matches = array();
272
273
        // update the matches, if the pattern matches
274
        if ($result = preg_match($pattern, $filename, $matches)) {
275
            $this->matches = $matches;
276
        }
277
278
        // stop processing, if the filename doesn't match
279
        return (boolean) $result;
280
    }
281
282
    /**
283
     * Return's an array with the names of the expected OK files for the actual subject.
284
     *
285
     * @return array The array with the expected OK filenames
286
     */
287
    protected function getOkFilenames()
288
    {
289
290
        // load the array with the available bunch keys
291
        $bunchKeys = BunchKeys::getAllKeys();
292
293
        // initialize the array for the available okFilenames
294
        $okFilenames = array();
295
296
        // prepare the OK filenames based on the found CSV file information
297
        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...
298
            // intialize the array for the parts of the names (prefix, filename + counter)
299
            $parts = array();
300
            // load the parts from the matches
301
            for ($z = 0; $z < $i; $z++) {
302
                $parts[] = $this->matches[$bunchKeys[$z]];
303
            }
304
305
            // query whether or not, the OK file exists, if yes append it
306
            if (file_exists($okFilename = sprintf('%s/%s.ok', $this->getSourceDir(), implode('_', $parts)))) {
307
                $okFilenames[] = $okFilename;
308
            }
309
        }
310
311
        // prepare and return the pattern for the OK file
312
        return $okFilenames;
313
    }
314
315
    /**
316
     * Query whether or not, the passed CSV filename is in the OK file. If the filename was found,
317
     * it'll be returned and the method return TRUE.
318
     *
319
     * If the filename is NOT in the OK file, the method return's FALSE and the CSV should NOT be
320
     * imported/moved.
321
     *
322
     * @param string $filename The CSV filename to query for
323
     *
324
     * @return void
325
     * @throws \Exception Is thrown, if the passed filename is NOT in the OK file or it can NOT be removed from it
326
     */
327
    protected function removeFromOkFile($filename)
328
    {
329
330
        try {
331
            // load the expected OK filenames
332
            $okFilenames = $this->getOkFilenames();
333
334
            // iterate over the found OK filenames (should usually be only one, but could be more)
335
            foreach ($okFilenames as $okFilename) {
336
                // if the OK filename matches the CSV filename AND the OK file is empty
337
                if (basename($filename, '.csv') === basename($okFilename, '.ok') && filesize($okFilename) === 0) {
338
                    unlink($okFilename);
339
                    return;
340
                }
341
342
                // else, remove the CSV filename from the OK file
343
                $this->removeLineFromFile(basename($filename), $okFilename);
344
                return;
345
            }
346
347
            // throw an exception if either no OK file has been found,
348
            // or the CSV file is not in one of the OK files
349
            throw new \Exception(
350
                sprintf(
351
                    'Can\'t found filename %s in one of the expected OK files: %s',
352
                    $filename,
353
                    implode(', ', $okFilenames)
354
                )
355
            );
356
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
357
        } catch (\Exception $e) {
358
            // wrap and re-throw the exception
359
            throw new \Exception(
360
                sprintf(
361
                    'Can\'t remove filename %s from OK file: %s',
362
                    $filename,
363
                    $okFilename
364
                ),
365
                null,
366
                $e
367
            );
368
        }
369
    }
370
}
371