Completed
Push — master ( 16eae1...63d154 )
by Freek
01:00
created

SimpleExcelReader::getPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\SimpleExcel;
4
5
use Box\Spout\Common\Entity\Row;
6
use Box\Spout\Reader\ReaderInterface;
7
use Illuminate\Support\LazyCollection;
8
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
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 getPath(): string
36
    {
37
        return $this->path;
38
    }
39
40
    public function noHeaderRow()
41
    {
42
        $this->processHeader = false;
43
44
        return $this;
45
    }
46
47
    public function useDelimiter(string $delimiter)
48
    {
49
        $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...
50
51
        return $this;
52
    }
53
54
    public function useFieldEnclosure(string $fieldEnclosure)
55
    {
56
        $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...
57
58
        return $this;
59
    }
60
61
    public function getReader(): ReaderInterface
62
    {
63
        return $this->reader;
64
    }
65
66
    public function getRows(): LazyCollection
67
    {
68
        $this->reader->open($this->path);
69
70
        $this->reader->getSheetIterator()->rewind();
71
72
        $sheet = $this->reader->getSheetIterator()->current();
73
74
        $this->rowIterator = $sheet->getRowIterator();
75
76
        $this->rowIterator->rewind();
77
78
        /** @var \Box\Spout\Common\Entity\Row $firstRow */
79
        $firstRow = $this->rowIterator->current();
80
81
        if (is_null($firstRow)) {
82
            $this->noHeaderRow();
83
        }
84
85
        if ($this->processHeader) {
86
            $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...
87
            $this->rowIterator->next();
88
        }
89
90
        return LazyCollection::make(function () {
91
            while ($this->rowIterator->valid()) {
92
                $row = $this->rowIterator->current();
93
94
                yield $this->getValueFromRow($row);
95
96
                $this->rowIterator->next();
97
            }
98
        });
99
    }
100
101
    protected function getValueFromRow(Row $row): array
102
    {
103
        if (! $this->processHeader) {
104
            return $row->toArray();
105
        }
106
107
        $values = array_slice($row->toArray(), 0, count($this->headers));
108
109
        while (count($values) < count($this->headers)) {
110
            $values[] = '';
111
        }
112
113
        return array_combine($this->headers, $values);
114
    }
115
116
    public function close()
117
    {
118
        $this->reader->close();
119
    }
120
121
    public function __destruct()
122
    {
123
        $this->close();
124
    }
125
}
126