Completed
Push — master ( 33462b...3b23c0 )
by Freek
56s
created

SimpleExcelReader::useFieldEnclosure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\SimpleExcel;
4
5
use Box\Spout\Common\Entity\Row;
6
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
7
use Box\Spout\Reader\ReaderInterface;
8
use Illuminate\Support\LazyCollection;
9
10
class SimpleExcelReader
11
{
12
    /**  @var string */
13
    private $path;
14
15
    /** @var \Box\Spout\Reader\ReaderInterface */
16
    private $reader;
17
18
    /** @var \Box\Spout\Reader\IteratorInterface */
19
    private $rowIterator;
20
21
    private $processHeader = true;
22
23
    public static function create(string $file)
24
    {
25
        return new static($file);
26
    }
27
28
    public function __construct(string $path)
29
    {
30
        $this->path = $path;
31
32
        $this->reader = ReaderEntityFactory::createReaderFromFile($this->path);
33
    }
34
35
    public function noTitleRow()
36
    {
37
        $this->processHeader = false;
38
39
        return $this;
40
    }
41
42
    public function useDelimiter(string $delimiter)
43
    {
44
        $this->reader->setFieldDelimiter($delimiter);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Box\Spout\Reader\ReaderInterface as the method setFieldDelimiter() does only exist in the following implementations of said interface: Box\Spout\Reader\CSV\Reader.

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...
45
46
        return $this;
47
    }
48
49
    public function useFieldEnclosure(string $fieldEnclosure)
50
    {
51
        $this->reader->setFieldEnclosure($fieldEnclosure);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Box\Spout\Reader\ReaderInterface as the method setFieldEnclosure() does only exist in the following implementations of said interface: Box\Spout\Reader\CSV\Reader.

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...
52
53
        return $this;
54
    }
55
56
    public function getReader(): ReaderInterface
57
    {
58
        return $this->getReader();
59
    }
60
61
    public function getRows(): LazyCollection
62
    {
63
        $this->reader->open($this->path);
64
65
        $sheet = $this->reader->getSheetIterator()->current();
66
67
        $this->rowIterator = $sheet->getRowIterator();
68
69
        $this->rowIterator->rewind();
70
71
        /** @var \Box\Spout\Common\Entity\Row $firstRow */
72
        $firstRow = $this->rowIterator->current();
73
74
        if (is_null($firstRow)) {
75
            $this->noTitleRow();
76
        }
77
78
        if ($this->processHeader) {
79
            $this->headers = $firstRow->toArray();
0 ignored issues
show
Bug introduced by
The property headers does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
80
            $this->rowIterator->next();
81
        }
82
83
        return LazyCollection::make(function () {
84
            while ($this->rowIterator->valid()) {
85
                $row = $this->rowIterator->current();
86
87
                yield $this->getValueFromRow($row);
88
89
                $this->rowIterator->next();
90
            }
91
        });
92
    }
93
94
    protected function getValueFromRow(Row $row): array
95
    {
96
        if (!$this->processHeader) {
97
            return $row->toArray();
98
        }
99
100
        $values = array_slice($row->toArray(), 0, count($this->headers));
101
102
        while (count($values) < count($this->headers)) {
103
            $values[] = '';
104
        }
105
106
        return array_combine($this->headers, $values);
107
    }
108
109
    public function __destruct()
110
    {
111
        $this->reader->close();
112
    }
113
}
114