Completed
Pull Request — master (#89)
by Tim
02:51
created

MissingOptionValuesPlugin   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 184
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
lcom 1
cbo 8
dl 0
loc 184
ccs 0
cts 90
cp 0
rs 10
c 1
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
C process() 0 114 12
A getSystemName() 0 4 1
A getTargetDir() 0 14 2
1
<?php
2
3
/**
4
 * TechDivision\Import\Plugins\MissingOptionValuesPlugin
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\ColumnKeys;
24
use TechDivision\Import\Utils\RegistryKeys;
25
use TechDivision\Import\Utils\SwiftMailerKeys;
26
use TechDivision\Import\ApplicationInterface;
27
use TechDivision\Import\Subjects\ExportableTrait;
28
use TechDivision\Import\Adapter\ExportAdapterInterface;
29
30
/**
31
 * Plugin that exports the missing option values to a CSV file.
32
 *
33
 * @author    Tim Wagner <[email protected]>
34
 * @copyright 2016 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
37
 * @link      http://www.techdivision.com
38
 */
39
class MissingOptionValuesPlugin extends AbstractPlugin
40
{
41
42
    /**
43
     * The artefact type.
44
     *
45
     * @var string
46
     */
47
    const ARTEFACT_TYPE = 'missing-option-values';
48
49
    /**
50
     * The trait providing the export functionality.
51
     *
52
     * @var \TechDivision\Import\Subjects\ExportableTrait
53
     */
54
    use ExportableTrait;
55
56
    /**
57
     * Initializes the plugin with the application instance.
58
     *
59
     * @param \TechDivision\Import\ApplicationInterface           $application   The application instance
60
     * @param \TechDivision\Import\Adapter\ExportAdapterInterface $exportAdapter The export adapter instance
61
     */
62
    public function __construct(ApplicationInterface $application, ExportAdapterInterface $exportAdapter)
63
    {
64
65
        // pass the application to the parent constructor
66
        parent::__construct($application);
67
68
        // set the export adapter
69
        $this->exportAdapter = $exportAdapter;
70
    }
71
72
    /**
73
     * Process the plugin functionality.
74
     *
75
     * @return void
76
     * @throws \Exception Is thrown, if the plugin can not be processed
77
     */
78
    public function process()
79
    {
80
81
        // query whether or not, the debug mode has been enabled
82
        if (!$this->getConfiguration()->isDebugMode()) {
83
            $this->getSystemLogger()->info('Debug mode is not enabled, missing option values will not be exported');
84
            return;
85
        }
86
87
        // clear the filecache
88
        clearstatcache();
89
90
        // load the actual status
91
        $status = $this->getRegistryProcessor()->getAttribute($this->getSerial());
92
93
        // query whether or not the configured source directory is available
94
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
95
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
96
        }
97
98
        // load the array with the missing option values from the status
99
        $missingOptions = $status[RegistryKeys::MISSING_OPTION_VALUES];
100
101
        // if missing option values are found, return immediately
102
        if (sizeof($missingOptions) === 0) {
103
            $this->getSystemLogger()->info('Found no missing option values');
104
            return;
105
        }
106
107
        // initialize the array with the artefacts
108
        $artefacts = array();
109
110
        // prepare the artefacts
111
        foreach ($missingOptions as $attributeCode => $options) {
112
            foreach ($options as $value => $data) {
113
                list($counter, $skus) = $data;
114
                $artefacts[] = $this->newArtefact(
115
                    array(
116
                        ColumnKeys::STORE_VIEW_CODE   => null,
117
                        ColumnKeys::ATTRIBUTE_CODE    => $attributeCode,
118
                        ColumnKeys::ADMIN_STORE_VALUE => $value,
119
                        ColumnKeys::VALUE             => $value,
120
                        ColumnKeys::COUNTER           => $counter,
121
                        ColumnKeys::UNIQUE_IDENTIFIER => implode(',', array_keys($skus)),
122
                        ColumnKeys::SORT_ORDER        => null
123
                    )
124
                );
125
            }
126
        }
127
128
        // initialize a dummy last entity ID
129
        $this->setLastEntityId(0);
130
131
        // add the artefacts (missing option values) and export them as CSV file
132
        $this->addArtefacts($artefactType = MissingOptionValuesPlugin::ARTEFACT_TYPE, $artefacts);
133
        $this->export($timestamp = date('Ymd-His'), $counter = '01');
134
135
        // query whether or not a swift mailer has been registered
136
        if ($swiftMailer = $this->getSwiftMailer()) {
137
            // the swift mailer configuration
138
            $swiftMailerConfiguration = $this->getPluginConfiguration()->getSwiftMailer();
0 ignored issues
show
Bug introduced by
The method getSwiftMailer() does not seem to exist on object<TechDivision\Impo...ConfigurationInterface>.

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...
139
140
            // create the message with the CSV with the missing option values
141
            $message = $swiftMailer->createMessage()
142
                                   ->setSubject(sprintf('[%s] %s', $this->getSystemName(), $swiftMailerConfiguration->getParam(SwiftMailerKeys::SUBJECT)))
143
                                   ->setFrom($swiftMailerConfiguration->getParam(SwiftMailerKeys::FROM))
144
                                   ->setTo($to = $swiftMailerConfiguration->getParam(SwiftMailerKeys::TO))
145
                                   ->setBody('The attached CSV file(s) contains the missing attribute option values');
146
147
            // attach the CSV files with the missing option values
148
            foreach ($this->getExportAdapter()->getExportedFilenames() as $filename) {
149
                $message->attach(\Swift_Attachment::fromPath($filename));
150
            }
151
152
            // initialize the array with the failed recipients
153
            $failedRecipients = array();
154
            $recipientsAccepted = 0;
0 ignored issues
show
Unused Code introduced by
$recipientsAccepted 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...
155
156
            // send the mail
157
            $recipientsAccepted = $swiftMailer->send($message, $failedRecipients);
158
159
            // query whether or not all recipients have been accepted
160
            if (sizeof($failedRecipients) > 0) {
161
                $this->getSystemLogger()->error(sprintf('Can\'t send mail to %s', implode(', ', $failedRecipients)));
162
            }
163
164
            // if at least one recipient has been accepted
165
            if ($recipientsAccepted > 0) {
166
                // cast 'to' into an array if not already
167
                is_array($to) ? : $to = (array) $to;
168
                // remove the NOT accepted recipients
169
                $acceptedRecipients = array_diff($to, $failedRecipients);
170
171
                // log a message with the successfull receivers
172
                $this->getSystemLogger()->info(
173
                    sprintf(
174
                        'Mail successfully sent to %d recipient(s) (%s)',
175
                        $recipientsAccepted,
176
                        implode(', ', $acceptedRecipients)
177
                    )
178
                );
179
            }
180
        }
181
182
        // and and log a message that the missing option values has been exported
183
        foreach ($this->getSystemLoggers() as $systemLogger) {
184
            $systemLogger->error(
185
                sprintf(
186
                    'Exported missing option values to file %s!',
187
                    $filename
0 ignored issues
show
Bug introduced by
The variable $filename seems to be defined by a foreach iteration on line 148. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
188
                )
189
            );
190
        }
191
    }
192
193
    /**
194
     * Return's the systemm name to be used.
195
     *
196
     * @return string The system name to be used
197
     */
198
    protected function getSystemName()
199
    {
200
        return $this->getConfiguration()->getSystemName();
201
    }
202
203
    /**
204
     * Return's the target directory the CSV files has to be exported to.
205
     *
206
     * @return string The name of the target directory
207
     */
208
    protected function getTargetDir()
209
    {
210
211
        // load the actual status
212
        $status = $this->getRegistryProcessor()->getAttribute($this->getSerial());
213
214
        // query whether or not the configured source directory is available
215
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
216
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
217
        }
218
219
        // return the source directory where we want to export to
220
        return $sourceDir;
221
    }
222
}
223