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

CsvImportAdapter::init()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

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

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...
96
97
        // query whether or not a delimiter character has been configured
98
        if ($delimiter = $importAdapterConfiguration->getDelimiter()) {
99
            $config->setDelimiter($delimiter);
100
        }
101
102
        // query whether or not a custom escape character has been configured
103
        if ($escape = $importAdapterConfiguration->getEscape()) {
104
            $config->setEscape($escape);
105
        }
106
107
        // query whether or not a custom enclosure character has been configured
108
        if ($enclosure = $importAdapterConfiguration->getEnclosure()) {
109
            $config->setEnclosure($enclosure);
110
        }
111
112
        // query whether or not a custom source charset has been configured
113
        if ($fromCharset = $importAdapterConfiguration->getFromCharset()) {
114
            $config->setFromCharset($fromCharset);
115
        }
116
117
        // query whether or not a custom target charset has been configured
118
        if ($toCharset = $importAdapterConfiguration->getToCharset()) {
119
            $config->setToCharset($toCharset);
120
        }
121
122
        // load the serializer instance from the DI container and set it on the subject instance
123
        $this->setSerializer($serializerFactory->createSerializer($importAdapterConfiguration));
124
    }
125
126
    /**
127
     * Imports the content of the CSV file with the passed filename.
128
     *
129
     * @param callable $callback The callback that processes the row
130
     * @param string   $filename The filename to process
131
     *
132
     * @return void
133
     */
134
    public function import(callable $callback, $filename)
135
    {
136
137
        // reset and initialize the interpreter
138
        $this->interpreter->reset();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Goodby\CSV\Import\Protocol\InterpreterInterface as the method reset() does only exist in the following implementations of said interface: TechDivision\Import\Adapter\Goodby\Interpreter.

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...
139
        $this->interpreter->addObserver($callback);
140
141
        // parse the CSV file to be imported
142
        $this->lexer->parse($filename, $this->interpreter);
143
    }
144
}
145