Completed
Push — 12.x ( 057fdd...85f11c )
by Tim
06:14
created

MissingOptionValuesPlugin::isDebugMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 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
     * Queries whether or not debug mode is enabled or not, default is TRUE.
74
     *
75
     * @return boolean TRUE if debug mode is enabled, else FALSE
76
     */
77
    public function isDebugMode()
78
    {
79
        return $this->getConfiguration()->isDebugMode();
80
    }
81
82
    /**
83
     * Process the plugin functionality.
84
     *
85
     * @return void
86
     * @throws \Exception Is thrown, if the plugin can not be processed
87
     */
88
    public function process()
89
    {
90
91
        // query whether or not, the debug mode has been enabled
92
        if (!$this->getConfiguration()->isDebugMode()) {
93
            $this->getSystemLogger()->info('Debug mode is not enabled, missing option values will not be exported');
94
            return;
95
        }
96
97
        // clear the filecache
98
        clearstatcache();
99
100
        // load the actual status
101
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
102
103
        // query whether or not the configured source directory is available
104
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
105
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
106
        }
107
108
        // load the array with the missing option values from the status
109
        $missingOptions = $status[RegistryKeys::MISSING_OPTION_VALUES];
110
111
        // if missing option values are found, return immediately
112
        if (sizeof($missingOptions) === 0) {
113
            $this->getSystemLogger()->info('Found no missing option values');
114
            return;
115
        }
116
117
        // initialize the array with the artefacts
118
        $artefacts = array();
119
120
        // prepare the artefacts
121
        foreach ($missingOptions as $attributeCode => $options) {
122
            foreach ($options as $value => $data) {
123
                list($counter, $skus) = $data;
124
                $artefacts[] = $this->newArtefact(
125
                    array(
126
                        ColumnKeys::STORE_VIEW_CODE   => null,
127
                        ColumnKeys::ATTRIBUTE_CODE    => $attributeCode,
128
                        ColumnKeys::ADMIN_STORE_VALUE => $value,
129
                        ColumnKeys::VALUE             => $value,
130
                        ColumnKeys::COUNTER           => $counter,
131
                        ColumnKeys::UNIQUE_IDENTIFIER => implode(',', array_keys($skus)),
132
                        ColumnKeys::SORT_ORDER        => null
133
                    )
134
                );
135
            }
136
        }
137
138
        // initialize a dummy last entity ID
139
        $this->setLastEntityId(0);
140
141
        // add the artefacts (missing option values) and export them as CSV file
142
        $this->addArtefacts(MissingOptionValuesPlugin::ARTEFACT_TYPE, $artefacts);
143
        $this->export(date('Ymd-His'), $counter = '01');
144
145
        // query whether or not a swift mailer has been registered
146
        if ($swiftMailer = $this->getSwiftMailer()) {
147
            // the swift mailer configuration
148
            $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...
149
150
            // create the message with the CSV with the missing option values
151
            $message = $swiftMailer->createMessage()
152
                                   ->setSubject(sprintf('[%s] %s', $this->getSystemName(), $swiftMailerConfiguration->getParam(SwiftMailerKeys::SUBJECT)))
153
                                   ->setFrom($swiftMailerConfiguration->getParam(SwiftMailerKeys::FROM))
154
                                   ->setTo($to = $swiftMailerConfiguration->getParam(SwiftMailerKeys::TO))
155
                                   ->setBody('The attached CSV file(s) contains the missing attribute option values');
156
157
            // load the exported filenames
158
            $exportedFilenames = $this->getExportAdapter()->getExportedFilenames();
159
160
            // attach the CSV files with the missing option values
161
            foreach ($exportedFilenames as $filename) {
162
                $message->attach(\Swift_Attachment::fromPath($filename));
163
            }
164
165
            // initialize the array with the failed recipients
166
            $failedRecipients = array();
167
            $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...
168
169
            // send the mail
170
            $recipientsAccepted = $swiftMailer->send($message, $failedRecipients);
171
172
            // query whether or not all recipients have been accepted
173
            if (sizeof($failedRecipients) > 0) {
174
                $this->getSystemLogger()->error(sprintf('Can\'t send mail to %s', implode(', ', $failedRecipients)));
175
            }
176
177
            // if at least one recipient has been accepted
178
            if ($recipientsAccepted > 0) {
179
                // cast 'to' into an array if not already
180
                is_array($to) ? : $to = (array) $to;
181
                // remove the NOT accepted recipients
182
                $acceptedRecipients = array_diff($to, $failedRecipients);
183
184
                // log a message with the successfull receivers
185
                $this->getSystemLogger()->info(
186
                    sprintf(
187
                        'Mail successfully sent to %d recipient(s) (%s)',
188
                        $recipientsAccepted,
189
                        implode(', ', $acceptedRecipients)
190
                    )
191
                );
192
            }
193
        }
194
195
        // load the system loggers
196
        $systemLoggers = $this->getSystemLoggers();
197
198
        // and and log a message that the missing option values has been exported
199
        foreach ($systemLoggers as $systemLogger) {
200
            $systemLogger->error(
201
                sprintf(
202
                    'Exported missing option values to file %s!',
203
                    $filename
0 ignored issues
show
Bug introduced by
The variable $filename seems to be defined by a foreach iteration on line 161. 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...
204
                )
205
            );
206
        }
207
    }
208
209
    /**
210
     * Return's the systemm name to be used.
211
     *
212
     * @return string The system name to be used
213
     */
214
    protected function getSystemName()
215
    {
216
        return $this->getConfiguration()->getSystemName();
217
    }
218
219
    /**
220
     * Return's the target directory the CSV files has to be exported to.
221
     *
222
     * @return string The name of the target directory
223
     */
224 View Code Duplication
    protected function getTargetDir()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
225
    {
226
227
        // load the actual status
228
        $status = $this->getRegistryProcessor()->getAttribute(RegistryKeys::STATUS);
229
230
        // query whether or not the configured source directory is available
231
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
232
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
233
        }
234
235
        // return the source directory where we want to export to
236
        return $sourceDir;
237
    }
238
}
239