Passed
Push — master ( a9f547...49cca7 )
by Raffael
04:18
created

Converter::setOptions()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 0
cts 18
cp 0
rs 8.7624
c 0
b 0
f 0
cc 5
crap 30
eloc 12
nc 5
nop 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A Converter::injectAdapter() 0 18 3
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2018 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon;
13
14
use Balloon\Converter\Adapter\AdapterInterface;
15
use Balloon\Converter\Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Balloon\Exception.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
16
use Balloon\Converter\Result;
17
use Balloon\Filesystem\Node\File;
18
use Psr\Log\LoggerInterface;
19
20
class Converter
21
{
22
    /**
23
     * LoggerInterface.
24
     *
25
     * @var LoggerInterface
26
     */
27
    protected $logger;
28
29
    /**
30
     * Adapter.
31
     *
32
     * @var array
33
     */
34
    protected $adapter = [];
35
36
    /**
37
     * Initialize.
38
     */
39
    public function __construct(LoggerInterface $logger)
40
    {
41
        $this->logger = $logger;
42
    }
43
44
    /**
45
     * Has adapter.
46
     */
47
    public function hasAdapter(string $name): bool
48
    {
49
        return isset($this->adapter[$name]);
50
    }
51
52
    /**
53
     * Inject adapter.
54
     *
55
     *
56
     * @return Converter
57
     */
58
    public function injectAdapter(AdapterInterface $adapter, ?string $name = null): self
59
    {
60
        if (null === $name) {
61
            $name = get_class($adapter);
62
        }
63
64
        $this->logger->debug('inject converter adapter ['.$name.'] of type ['.get_class($adapter).']', [
65
            'category' => get_class($this),
66
        ]);
67
68
        if ($this->hasAdapter($name)) {
69
            throw new Exception('adapter '.$name.' is already registered');
70
        }
71
72
        $this->adapter[$name] = $adapter;
73
74
        return $this;
75
    }
76
77
    /**
78
     * Get adapter.
79
     */
80
    public function getAdapter(string $name): AdapterInterface
81
    {
82
        if (!$this->hasAdapter($name)) {
83
            throw new Exception('adapter '.$name.' is not registered');
84
        }
85
86
        return $this->adapter[$name];
87
    }
88
89
    /**
90
     * Get adapters.
91
     *
92
     *
93
     * @return AdapterInterface[]
94
     */
95
    public function getAdapters(array $adapters = []): array
0 ignored issues
show
Unused Code introduced by
The parameter $adapters is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
96
    {
97
        if (empty($adapter)) {
0 ignored issues
show
Bug introduced by
The variable $adapter does not exist. Did you mean $adapters?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
98
            return $this->adapter;
99
        }
100
        $list = [];
101
        foreach ($adapter as $name) {
102
            if (!$this->hasAdapter($name)) {
103
                throw new Exception('adapter '.$name.' is not registered');
104
            }
105
            $list[$name] = $this->adapter[$name];
106
        }
107
108
        return $list;
109
    }
110
111
    /**
112
     * Get supported formats.
113
     */
114
    public function getSupportedFormats(File $file): array
115
    {
116
        foreach ($this->adapter as $adapter) {
117
            if ($adapter->match($file)) {
118
                return $adapter->getSupportedFormats($file);
119
            }
120
        }
121
122
        return [];
123
    }
124
125
    /**
126
     * Create preview.
127
     */
128
    public function createPreview(File $file): Result
129
    {
130
        $this->logger->debug('create preview from file ['.$file->getId().']', [
131
            'category' => get_class($this),
132
        ]);
133
134
        if (0 === $file->getSize()) {
135
            throw new Exception('can not create preview from empty file');
136
        }
137
138
        foreach ($this->adapter as $name => $adapter) {
139
            try {
140
                if ($adapter->matchPreview($file)) {
141
                    return $adapter->createPreview($file);
142
                }
143
                $this->logger->debug('skip convert adapter ['.$name.'], adapter can not handle file', [
144
                        'category' => get_class($this),
145
                    ]);
146
            } catch (\Exception $e) {
147
                $this->logger->error('failed execute adapter ['.get_class($adapter).']', [
148
                    'category' => get_class($this),
149
                    'exception' => $e,
150
                ]);
151
            }
152
        }
153
154
        throw new Exception('all adapter failed');
155
    }
156
157
    /**
158
     * Convert document.
159
     */
160
    public function convert(File $file, string $format): Result
161
    {
162
        $this->logger->debug('convert file ['.$file->getId().'] to format ['.$format.']', [
163
            'category' => get_class($this),
164
        ]);
165
166
        if (0 === $file->getSize()) {
167
            throw new Exception('can not convert empty file');
168
        }
169
170
        foreach ($this->adapter as $name => $adapter) {
171
            try {
172
                if ($adapter->match($file) && in_array($format, $adapter->getSupportedFormats($file), true)) {
173
                    return $adapter->convert($file, $format);
174
                }
175
                $this->logger->debug('skip convert adapter ['.$name.'], adapter can not handle file', [
176
                        'category' => get_class($this),
177
                    ]);
178
            } catch (\Exception $e) {
179
                $this->logger->error('failed execute adapter ['.get_class($adapter).']', [
180
                    'category' => get_class($this),
181
                    'exception' => $e,
182
                ]);
183
            }
184
        }
185
186
        throw new Exception('all adapter failed');
187
    }
188
}
189