BlobGenerator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 16
dl 0
loc 43
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __invoke() 0 21 5
1
<?php
2
namespace DBFaker\Generators;
3
4
use DBFaker\Exceptions\FileTooLargeException;
5
use DBFaker\Exceptions\NoTestFilesFoundException;
6
use Doctrine\DBAL\Schema\Column;
7
8
class BlobGenerator implements FakeDataGeneratorInterface
9
{
10
11
    /**
12
     * @var string
13
     */
14
    private $globExpression;
15
    /**
16
     * @var Column
17
     */
18
    private $column;
19
20
    public function __construct(string $globExpression, Column $column)
21
    {
22
        $this->globExpression = $globExpression;
23
        $this->column = $column;
24
    }
25
26
    /**
27
     * @return bool|resource
28
     * @throws NoTestFilesFoundException
29
     */
30
    public function __invoke()
31
    {
32
        $files = glob($this->globExpression, GLOB_MARK);
33
        $files = array_filter($files, function ($fileName) {
34
            return strrpos($fileName, DIRECTORY_SEPARATOR) !== \strlen($fileName) - 1;
35
        });
36
        foreach ($files as $file) {
37
            // Note: length = 0 for Blob types (unlimited) but not for Binary types (limited in length)
38
            if ($this->column->getLength() !== 0 && \filesize($file) > $this->column->getLength()) {
39
                throw FileTooLargeException::create($file, $this->column);
40
            }
41
        }
42
        if (\count($files) === 0) {
43
            throw new NoTestFilesFoundException("No files found for glob expression '".$this->globExpression."'");
44
        }
45
        $files = array_values($files);
46
        $chosenFile = $files[random_int(0, \count($files) - 1)];
47
48
        // TODO: throw exception if column not large enough
49
50
        return fopen($chosenFile, 'rb');
51
    }
52
}
53