FileStorageProvider::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Mathielen\ImportEngine\Storage\Provider;
4
5
use Mathielen\ImportEngine\Storage\Factory\FormatDiscoverLocalFileStorageFactory;
6
use Mathielen\ImportEngine\Storage\Factory\StorageFactoryInterface;
7
use Mathielen\ImportEngine\Storage\Format\Discovery\MimeTypeDiscoverStrategy;
8
use Mathielen\ImportEngine\ValueObject\StorageSelection;
9
use Mathielen\ImportEngine\Exception\InvalidConfigurationException;
10
11
class FileStorageProvider implements StorageProviderInterface
12
{
13
    /**
14
     * @var StorageFactoryInterface
15
     */
16
    private $storageFactory;
17
18 15
    public function __construct(StorageFactoryInterface $storageFactory = null)
19
    {
20
        //default
21 15
        if (!$storageFactory) {
22 15
            $storageFactory = new FormatDiscoverLocalFileStorageFactory(new MimeTypeDiscoverStrategy());
23
        }
24
25 15
        $this->setStorageFactory($storageFactory);
26 15
    }
27
28 15
    public function setStorageFactory(StorageFactoryInterface $storageFactory)
29
    {
30 15
        $this->storageFactory = $storageFactory;
31 15
    }
32
33
    /**
34
     * (non-PHPdoc).
35
     *
36
     * @see \Mathielen\ImportEngine\Storage\Provider\StorageProviderInterface::select()
37
     */
38 2
    public function select($id = null)
39
    {
40 2
        if ($id instanceof \SplFileInfo) {
41
            $selection = new StorageSelection($id, $id->getRealPath(), $id->getFilename());
42
43
            return $selection;
44 2
        } elseif (is_string($id)) {
45 2
            if (!file_exists($id)) {
46
                throw new \InvalidArgumentException('id is not a valid file path: '.$id);
47
            }
48 2
            $selection = new StorageSelection(new \SplFileInfo($id), realpath($id), $id);
49
50 2
            return $selection;
51
        } elseif ($id instanceof StorageSelection) {
52
            return $id;
53
        }
54
55
        throw new \InvalidArgumentException('Id must be a string, an instance of SplFileInfo or a StorageSelection. Was: '.print_r($id, true));
56
    }
57
58
    /**
59
     * (non-PHPdoc).
60
     *
61
     * @see \Mathielen\ImportEngine\Storage\Provider\StorageProviderInterface::storage()
62
     */
63 2
    public function storage(StorageSelection $selection)
64
    {
65 2
        if (!$this->storageFactory) {
66
            throw new InvalidConfigurationException('Cannot factor storage. StorageFactory is missing. Set factory with setStorageFactory()');
67
        }
68
69 2
        return $this->storageFactory->factor($selection);
70
    }
71
}
72