Completed
Push — 8.x ( 824af6 )
by Tim
09:11
created

CsvExportAdapter::init()   B

Complexity

Conditions 7
Paths 64

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
dl 0
loc 42
c 0
b 0
f 0
ccs 0
cts 25
cp 0
rs 8.3146
cc 7
nc 64
nop 2
crap 56
1
<?php
2
3
/**
4
 * TechDivision\Import\Adapter\CsvExportAdapter
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\Adapter;
22
23
use Goodby\CSV\Export\Protocol\ExporterInterface;
24
use TechDivision\Import\Configuration\Subject\ExportAdapterConfigurationInterface;
25
use TechDivision\Import\Serializers\ConfigurationAwareSerializerFactoryInterface;
26
27
/**
28
 * CSV export adapter implementation.
29
 *
30
 * @author    Tim Wagner <[email protected]>
31
 * @copyright 2016 TechDivision GmbH <[email protected]>
32
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
33
 * @link      https://github.com/techdivision/import
34
 * @link      http://www.techdivision.com
35
 */
36
class CsvExportAdapter implements ExportAdapterInterface, SerializerAwareAdapterInterface
37
{
38
39
    /**
40
     * The trait that provides serializer functionality.
41
     *
42
     * @var \TechDivision\Import\Adapter\SerializerTrait
43
     */
44
    use SerializerTrait;
45
46
    /**
47
     * The exporter instance.
48
     *
49
     * @var \Goodby\CSV\Export\Protocol\ExporterInterface
50
     */
51
    protected $exporter;
52
53
    /**
54
     * The array with the names of the exported files.
55
     *
56
     * @var array
57
     */
58
    protected $exportedFilenames = array();
59
60
    /**
61
     * Initialize the adapter with the configuration.
62
     *
63
     * @param \Goodby\CSV\Export\Protocol\ExporterInterface $exporter The exporter instance
64
     */
65
    public function __construct(ExporterInterface $exporter)
66
    {
67
        $this->exporter = $exporter;
68
    }
69
70
    /**
71
     * Overwrites the default CSV configuration values with the one from the passed configuration.
72
     *
73
     * @param \TechDivision\Import\Configuration\Subject\ExportAdapterConfigurationInterface $exportAdapterConfiguration The configuration to use the values from
74
     * @param \TechDivision\Import\Serializers\ConfigurationAwareSerializerFactoryInterface  $serializerFactory          The serializer factory instance
75
     *
76
     * @return void
77
     */
78
    public function init(
79
        ExportAdapterConfigurationInterface $exportAdapterConfiguration,
80
        ConfigurationAwareSerializerFactoryInterface $serializerFactory
81
    ) {
82
83
        // load the exporter configuration and overwrite the values
84
        /** @var \Goodby\CSV\Export\Standard\ExporterConfig $config */
85
        $config = $this->exporter->getConfig();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Goodby\CSV\Export\Protocol\ExporterInterface as the method getConfig() does only exist in the following implementations of said interface: TechDivision\Import\Adapter\Goodby\Exporter.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
86
87
        // query whether or not a delimiter character has been configured
88
        if ($delimiter = $exportAdapterConfiguration->getDelimiter()) {
89
            $config->setDelimiter($delimiter);
90
        }
91
92
        // query whether or not a custom escape character has been configured
93
        if ($escape = $exportAdapterConfiguration->getEscape()) {
94
            $config->setEscape($escape);
95
        }
96
97
        // query whether or not a custom enclosure character has been configured
98
        if ($enclosure = $exportAdapterConfiguration->getEnclosure()) {
99
            $config->setEnclosure($enclosure);
100
        }
101
102
        // query whether or not a custom source charset has been configured
103
        if ($fromCharset = $exportAdapterConfiguration->getFromCharset()) {
104
            $config->setFromCharset($fromCharset);
105
        }
106
107
        // query whether or not a custom target charset has been configured
108
        if ($toCharset = $exportAdapterConfiguration->getToCharset()) {
109
            $config->setToCharset($toCharset);
110
        }
111
112
        // query whether or not a custom file mode has been configured
113
        if ($fileMode = $exportAdapterConfiguration->getFileMode()) {
114
            $config->setFileMode($fileMode);
115
        }
116
117
        // load the serializer instance from the DI container and set it on the subject instance
118
        $this->setSerializer($serializerFactory->createSerializer($exportAdapterConfiguration));
119
    }
120
121
    /**
122
     * Imports the content of the CSV file with the passed filename.
123
     *
124
     * @param array   $artefacts The artefacts to be exported
125
     * @param string  $targetDir The target dir to export the artefacts to
126
     * @param integer $timestamp The timestamp part of the original import file
127
     * @param string  $counter   The counter part of the origin import file
128
     *
129
     * @return void
130
     */
131
    public function export(array $artefacts, $targetDir, $timestamp, $counter)
132
    {
133
134
        // reset the array with the exported filename
135
        $this->exportedFilenames = array();
136
137
        // iterate over the artefacts and export them
138
        foreach ($artefacts as $artefactType => $artefacts) {
139
            // initialize the bunch and the exporter
140
            $bunch = array();
141
142
            // iterate over the artefact types artefacts
143
            foreach ($artefacts as $entityArtefacts) {
144
                // prepend the bunch header first
145
                if (sizeof($bunch) === 0) {
146
                    $bunch[] = array_keys(reset($entityArtefacts));
147
                }
148
149
                // export the artefacts
150
                foreach ($entityArtefacts as $entityArtefact) {
151
                    array_push($bunch, $entityArtefact);
152
                }
153
            }
154
155
            // prepare the name of the export file
156
            $filename = sprintf(
157
                '%s/%s_%s_%s.csv',
158
                $targetDir,
159
                $artefactType,
160
                $timestamp,
161
                $counter
162
            );
163
164
            // export the artefact (bunch)
165
            $this->exporter->export($filename, $bunch);
166
167
            // add the filename to the array with the exported filenames
168
            $this->exportedFilenames[] = $filename;
169
        }
170
    }
171
172
    /**
173
     * Return's the array with the names of the exported files.
174
     *
175
     * @return array The array with the exported filenames
176
     */
177
    public function getExportedFilenames()
178
    {
179
        return $this->exportedFilenames;
180
    }
181
}
182