Completed
Push — master ( f60ac0...8504d1 )
by Tim
06:02 queued 03:28
created

SubjectPlugin::processSubject()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 68
Code Lines 25

Duplication

Lines 3
Ratio 4.41 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 3
loc 68
ccs 0
cts 33
cp 0
rs 8.5748
c 0
b 0
f 0
cc 6
eloc 25
nc 7
nop 1
crap 42

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\Subjects\ExportableSubjectInterface;
26
use TechDivision\Import\Configuration\SubjectConfigurationInterface;
27
use TechDivision\Import\Utils\Generators\CoreConfigDataUidGenerator;
28
29
/**
30
 * Plugin that processes the subjects.
31
 *
32
 * @author    Tim Wagner <[email protected]>
33
 * @copyright 2016 TechDivision GmbH <[email protected]>
34
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
35
 * @link      https://github.com/techdivision/import
36
 * @link      http://www.techdivision.com
37
 */
38
class SubjectPlugin extends AbstractPlugin
39
{
40
41
    /**
42
     * The matches for the last processed CSV filename.
43
     *
44
     * @var array
45
     */
46
    protected $matches = array();
47
48
    /**
49
     * The number of imported bunches.
50
     *
51
     * @var integer
52
     */
53
    protected $bunches = 0;
54
55
    /**
56
     * Process the plugin functionality.
57
     *
58
     * @return void
59
     * @throws \Exception Is thrown, if the plugin can not be processed
60
     */
61
    public function process()
62
    {
63
        try {
64
            // immediately add the PID to lock this import process
65
            $this->lock();
66
67
            // load the plugin's subjects
68
            $subjects = $this->getPluginConfiguration()->getSubjects();
69
70
            // initialize the array for the status
71
            $status = array();
72
73
            // initialize the status information for the subjects
74
            /** @var \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject */
75
            foreach ($subjects as $subject) {
76
                $status[$subject->getPrefix()] = array();
77
            }
78
79
            // and update it in the registry
80
            $this->getRegistryProcessor()->mergeAttributesRecursive($this->getSerial(), $status);
81
82
            // process all the subjects found in the system configuration
83
            /** @var \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject */
84
            foreach ($subjects as $subject) {
85
                $this->processSubject($subject);
86
            }
87
88
            // update the number of imported bunches
89
            $this->getRegistryProcessor()->mergeAttributesRecursive(
90
                $this->getSerial(),
91
                array(RegistryKeys::BUNCHES => $this->bunches)
92
            );
93
94
            // finally, if a PID has been set (because CSV files has been found),
95
            // remove it from the PID file to unlock the importer
96
            $this->unlock();
97
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
98
        } catch (\Exception $e) {
99
            // finally, if a PID has been set (because CSV files has been found),
100
            // remove it from the PID file to unlock the importer
101
            $this->unlock();
102
103
            // re-throw the exception
104
            throw $e;
105
        }
106
    }
107
108
    /**
109
     * Process the subject with the passed name/identifier.
110
     *
111
     * We create a new, fresh and separate subject for EVERY file here, because this would be
112
     * the starting point to parallelize the import process in a multithreaded/multiprocessed
113
     * environment.
114
     *
115
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject The subject configuration
116
     *
117
     * @return void
118
     * @throws \Exception Is thrown, if the subject can't be processed
119
     */
120
    protected function processSubject(SubjectConfigurationInterface $subject)
121
    {
122
123
        // clear the filecache
124
        clearstatcache();
125
126
        // load the actual status
127
        $status = $this->getRegistryProcessor()->getAttribute($serial = $this->getSerial());
128
129
        // query whether or not the configured source directory is available
130 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...
131
            throw new \Exception(sprintf('Source directory %s for subject %s is not available!', $sourceDir, $subject->getClassName()));
132
        }
133
134
        // initialize the array with the CSV files found in the source directory
135
        $files = glob(sprintf('%s/*.csv', $sourceDir));
136
137
        // sorting the files for the apropriate order
138
        usort($files, function ($a, $b) {
139
            return strcmp($a, $b);
140
        });
141
142
        // log a debug message
143
        $this->getSystemLogger()->debug(sprintf('Now checking directory %s for files to be imported', $sourceDir));
144
145
        // initialize the bunch number
146
        $bunches = 0;
147
148
        // iterate through all CSV files and process the subjects
149
        foreach ($files as $pathname) {
150
            // query whether or not that the file is part of the actual bunch
151
            if ($this->isPartOfBunch($subject->getPrefix(), $pathname)) {
152
                // initialize the subject and import the bunch
153
                $subjectInstance = $this->subjectFactory($subject);
154
155
                // query whether or not the subject needs an OK file,
156
                // if yes remove the filename from the file
157
                if ($subjectInstance->isOkFileNeeded()) {
158
                    $this->removeFromOkFile($pathname);
159
                }
160
161
                // finally import the CSV file
162
                $subjectInstance->import($serial, $pathname);
163
164
                // query whether or not, we've to export artefacts
165
                if ($subjectInstance instanceof ExportableSubjectInterface) {
166
                    $subjectInstance->export(
167
                        $this->matches[BunchKeys::FILENAME],
168
                        $this->matches[BunchKeys::COUNTER]
169
                    );
170
                }
171
172
                // raise the number of the imported bunches
173
                $bunches++;
174
            }
175
        }
176
177
        // raise the bunch number by the imported bunches
178
        $this->bunches = $this->bunches + $bunches;
179
180
        // reset the matches, because the exported artefacts
181
        $this->matches = array();
182
183
        // and and log a message that the subject has been processed
184
        $this->getSystemLogger()->debug(
185
            sprintf('Successfully processed subject %s with %d bunch(es)!', $subject->getClassName(), $bunches)
186
        );
187
    }
188
189
    /**
190
     * Factory method to create new handler instances.
191
     *
192
     * @param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subjectConfiguration The subject configuration
193
     *
194
     * @return object The handler instance
195
     */
196
    protected function subjectFactory(SubjectConfigurationInterface $subjectConfiguration)
197
    {
198
199
        // load the subject class name
200
        $className = $subjectConfiguration->getClassName();
201
202
        // initialize the instances
203
        $processor = null;
204
        $systemLogger = $this->getSystemLogger();
205
        $registryProcessor = $this->getRegistryProcessor();
206
        $coreConfigDataUidGenerator = new CoreConfigDataUidGenerator();
207
208
        // instanciate and set the product processor, if specified
209
        if ($processorFactory = $subjectConfiguration->getProcessorFactory()) {
210
            $processor = $processorFactory::factory(
211
                $this->getImportProcessor()->getConnection(),
212
                $subjectConfiguration
213
            );
214
        }
215
216
        // initialize a new handler with the passed class name
217
        return new $className(
218
            $systemLogger,
219
            $subjectConfiguration,
220
            $registryProcessor,
221
            $coreConfigDataUidGenerator,
222
            $processor
223
        );
224
    }
225
226
    /**
227
     * Queries whether or not, the passed filename is part of a bunch or not.
228
     *
229
     * @param string $prefix   The prefix to query for
230
     * @param string $filename The filename to query for
231
     *
232
     * @return boolean TRUE if the filename is part, else FALSE
233
     */
234 2
    protected function isPartOfBunch($prefix, $filename)
235
    {
236
237
        // initialize the pattern
238 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...
239
240
        // query whether or not, this is the first file to be processed
241 2
        if (sizeof($this->matches) === 0) {
242
            // initialize the pattern to query whether the FIRST file has to be processed or not
243 2
            $pattern = sprintf(
244 2
                '/^.*\/(?<%s>%s)_(?<%s>.*)_(?<%s>\d+)\\.csv$/',
245 2
                BunchKeys::PREFIX,
246 2
                $prefix,
247 2
                BunchKeys::FILENAME,
248
                BunchKeys::COUNTER
249 2
            );
250
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
251 2
        } else {
252
            // initialize the pattern to query whether the NEXT file is part of a bunch or not
253 2
            $pattern = sprintf(
254 2
                '/^.*\/(?<%s>%s)_(?<%s>%s)_(?<%s>\d+)\\.csv$/',
255 2
                BunchKeys::PREFIX,
256 2
                $this->matches[BunchKeys::PREFIX],
257 2
                BunchKeys::FILENAME,
258 2
                $this->matches[BunchKeys::FILENAME],
259
                BunchKeys::COUNTER
260 2
            );
261
        }
262
263
        // initialize the array for the matches
264 2
        $matches = array();
265
266
        // update the matches, if the pattern matches
267 2
        if ($result = preg_match($pattern, $filename, $matches)) {
268 2
            $this->matches = $matches;
269 2
        }
270
271
        // stop processing, if the filename doesn't match
272 2
        return (boolean) $result;
273
    }
274
275
    /**
276
     * Return's an array with the names of the expected OK files for the actual subject.
277
     *
278
     * @return array The array with the expected OK filenames
279
     */
280
    protected function getOkFilenames()
281
    {
282
283
        // load the array with the available bunch keys
284
        $bunchKeys = BunchKeys::getAllKeys();
285
286
        // initialize the array for the available okFilenames
287
        $okFilenames = array();
288
289
        // prepare the OK filenames based on the found CSV file information
290
        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...
291
            // intialize the array for the parts of the names (prefix, filename + counter)
292
            $parts = array();
293
            // load the parts from the matches
294
            for ($z = 0; $z < $i; $z++) {
295
                $parts[] = $this->matches[$bunchKeys[$z]];
296
            }
297
298
            // query whether or not, the OK file exists, if yes append it
299
            if (file_exists($okFilename = sprintf('%s/%s.ok', $this->getSourceDir(), implode('_', $parts)))) {
300
                $okFilenames[] = $okFilename;
301
            }
302
        }
303
304
        // prepare and return the pattern for the OK file
305
        return $okFilenames;
306
    }
307
308
    /**
309
     * Query whether or not, the passed CSV filename is in the OK file. If the filename was found,
310
     * it'll be returned and the method return TRUE.
311
     *
312
     * If the filename is NOT in the OK file, the method return's FALSE and the CSV should NOT be
313
     * imported/moved.
314
     *
315
     * @param string $filename The CSV filename to query for
316
     *
317
     * @return void
318
     * @throws \Exception Is thrown, if the passed filename is NOT in the OK file or it can NOT be removed from it
319
     */
320
    protected function removeFromOkFile($filename)
321
    {
322
323
        try {
324
            // load the expected OK filenames
325
            $okFilenames = $this->getOkFilenames();
326
327
            // iterate over the found OK filenames (should usually be only one, but could be more)
328
            foreach ($okFilenames as $okFilename) {
329
                // if the OK filename matches the CSV filename AND the OK file is empty
330
                if (basename($filename, '.csv') === basename($okFilename, '.ok') && filesize($okFilename) === 0) {
331
                    unlink($okFilename);
332
                    return;
333
                }
334
335
                // else, remove the CSV filename from the OK file
336
                $this->removeLineFromFile(basename($filename), $okFilename);
337
                return;
338
            }
339
340
            // throw an exception if either no OK file has been found,
341
            // or the CSV file is not in one of the OK files
342
            throw new \Exception(
343
                sprintf(
344
                    'Can\'t found filename %s in one of the expected OK files: %s',
345
                    $filename,
346
                    implode(', ', $okFilenames)
347
                )
348
            );
349
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
350
        } catch (\Exception $e) {
351
            // wrap and re-throw the exception
352
            throw new \Exception(
353
                sprintf(
354
                    'Can\'t remove filename %s from OK file: %s',
355
                    $filename,
356
                    $okFilename
357
                ),
358
                null,
359
                $e
360
            );
361
        }
362
    }
363
}
364