Completed
Pull Request — master (#21)
by Greg
03:15
created

FormatterManager::addSimplifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 1
cts 1
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
namespace Consolidation\OutputFormatters;
3
4
use Symfony\Component\Console\Output\OutputInterface;
5
use Consolidation\OutputFormatters\Exception\UnknownFormatException;
6
use Consolidation\OutputFormatters\Formatters\RenderDataInterface;
7
use Consolidation\OutputFormatters\Exception\IncompatibleDataException;
8
use Consolidation\OutputFormatters\Transformations\DomToArraySimplifier;
9
use Consolidation\OutputFormatters\StructuredData\RestructureInterface;
10
11
/**
12
 * Manage a collection of formatters; return one on request.
13
 */
14
class FormatterManager
15
{
16 28
    protected $formatters = [];
17
    protected $arraySimplifiers = [];
18 28
19 28
    public function __construct()
20 28
    {
21 28
        $this->formatters = [
22 28
            'string' => '\Consolidation\OutputFormatters\Formatters\StringFormatter',
23 28
            'yaml' => '\Consolidation\OutputFormatters\Formatters\YamlFormatter',
24 28
            'xml' => '\Consolidation\OutputFormatters\Formatters\XmlFormatter',
25 28
            'json' => '\Consolidation\OutputFormatters\Formatters\JsonFormatter',
26 28
            'print-r' => '\Consolidation\OutputFormatters\Formatters\PrintRFormatter',
27 28
            'php' => '\Consolidation\OutputFormatters\Formatters\SerializeFormatter',
28
            'var_export' => '\Consolidation\OutputFormatters\Formatters\VarExportFormatter',
29
            'list' => '\Consolidation\OutputFormatters\Formatters\ListFormatter',
30
            'csv' => '\Consolidation\OutputFormatters\Formatters\CsvFormatter',
31 28
            'table' => '\Consolidation\OutputFormatters\Formatters\TableFormatter',
32 28
            'sections' => '\Consolidation\OutputFormatters\Formatters\SectionsFormatter',
33
        ];
34
35
        $this->arraySimplifiers = [
36
            new DomToArraySimplifier(),
37
        ];
38
39
        // Make the empty format an alias for the 'string' formatter.
40
        $this->add('', $this->formatters['string']);
41
    }
42
43 28
    /**
44
     * Add a formatter
45 28
     *
46 27
     * @param string $key the identifier of the formatter to add
47 24
     * @param string $formatterClassname the class name of the formatter to add
48 24
     * @return FormatterManager
49
     */
50 27
    public function add($key, $formatterClassname)
51
    {
52
        $this->formatters[$key] = $formatterClassname;
53
        return $this;
54 27
    }
55 27
56 4
    /**
57
     * Add a simplifier
58
     *
59
     * @param SimplifyToArrayInterface $simplifier the array simplifier to add
60 27
     * @return FormatterManager
61
     */
62
    public function addSimplifier(SimplifyToArrayInterface $simplifier)
63 27
    {
64
        $this->arraySimplifiers[] = $simplifier;
65
        return $this;
66
    }
67 24
68
    /**
69 24
     * Return the identifiers for all valid data types that have been registered.
70
     *
71
     * @param mixed $dataType \ReflectionObject or other description of the produced data type
72
     * @return array
73
     */
74
    public function validFormats($dataType)
75
    {
76
        $validFormats = [];
77
        foreach ($this->formatters as $formatId => $formatterName) {
78
            $formatter = $this->getFormatter($formatId);
79 28
            if ($this->isValidFormat($formatter, $dataType)) {
80
                $validFormats[] = $formatId;
81 28
            }
82 1
        }
83
        sort($validFormats);
84
        return $validFormats;
85 27
    }
86 27
87 9
    public function isValidFormat(FormatterInterface $formatter, $dataType)
88 9
    {
89 27
        if (is_array($dataType)) {
90
            $dataType = new \ReflectionClass('\ArrayObject');
91
        }
92 28
        if (!$dataType instanceof \ReflectionClass) {
93
            $dataType = new \ReflectionClass($dataType);
94 28
        }
95
        // If the formatter does not implement ValidationInterface, then
96
        // it is presumed that the formatter only accepts arrays.
97
        if (!$formatter instanceof ValidationInterface) {
98
            return $dataType->isSubclassOf('ArrayObject') || ($dataType->getName() == 'ArrayObject');
99
        }
100
        $supportedTypes = $formatter->validDataTypes();
101
        foreach ($supportedTypes as $supportedType) {
102
            if (($dataType->getName() == $supportedType->getName()) || $dataType->isSubclassOf($supportedType->getName())) {
103
                return true;
104
            }
105
        }
106
        return false;
107 24
    }
108
109 24
    /**
110 14
     * Format and write output
111
     *
112 14
     * @param OutputInterface $output Output stream to write to
113
     * @param string $format Data format to output in
114
     * @param mixed $structuredOutput Data to output
115
     * @param FormatterOptions $options Formatting options
116
     */
117
    public function write(OutputInterface $output, $format, $structuredOutput, FormatterOptions $options)
118
    {
119
        $formatter = $this->getFormatter((string)$format);
120
        $structuredOutput = $this->validateAndRestructure($formatter, $structuredOutput, $options);
121
        $formatter->write($output, $structuredOutput, $options);
122 27
    }
123
124
    protected function validateAndRestructure(FormatterInterface $formatter, $structuredOutput, FormatterOptions $options)
125
    {
126 27
        // Give the formatter a chance to do something with the
127 16
        // raw data before it is restructured.
128
        $overrideRestructure = $this->overrideRestructure($formatter, $structuredOutput, $options);
129
        if ($overrideRestructure) {
130
            return $overrideRestructure;
131
        }
132 15
133 4
        // Restructure the output data (e.g. select fields to display, etc.).
134
        $restructuredOutput = $this->restructureData($structuredOutput, $options);
135
136 11
        // Make sure that the provided data is in the correct format for the selected formatter.
137
        $restructuredOutput = $this->validateData($formatter, $restructuredOutput, $options);
138
139
        // Give the original data a chance to re-render the structured
140
        // output after it has been restructured and validated.
141
        $restructuredOutput = $this->renderData($formatter, $structuredOutput, $restructuredOutput, $options);
142
143
        return $restructuredOutput;
144
    }
145
146
    /**
147 27
     * Fetch the requested formatter.
148
     *
149 27
     * @param string $format Identifier for requested formatter
150 7
     * @return FormatterInterface
151
     */
152 20
    public function getFormatter($format)
153
    {
154
        if (!$this->hasFormatter($format)) {
155
            throw new UnknownFormatException($format);
156
        }
157
        $formatter = new $this->formatters[$format];
158
        return $formatter;
159
    }
160
161
    /**
162
     * Test to see if the stipulated format exists
163
     */
164
    public function hasFormatter($format)
165
    {
166
        return array_key_exists($format, $this->formatters);
167
    }
168 27
169
    /**
170 27
     * Render the data as necessary (e.g. to select or reorder fields).
171 5
     *
172
     * @param FormatterInterface $formatter
173 26
     * @param mixed $originalData
174
     * @param mixed $restructuredData
175
     * @param FormatterOptions $options Formatting options
176
     * @return mixed
177
     */
178
    public function renderData(FormatterInterface $formatter, $originalData, $restructuredData, FormatterOptions $options)
179
    {
180
        if ($formatter instanceof RenderDataInterface) {
181
            return $formatter->renderData($originalData, $restructuredData, $options);
182
        }
183
        return $restructuredData;
184
    }
185
186
    /**
187
     * Determine if the provided data is compatible with the formatter being used.
188
     *
189
     * @param FormatterInterface $formatter Formatter being used
190
     * @param mixed $structuredOutput Data to validate
191
     * @return mixed
192
     */
193
    public function validateData(FormatterInterface $formatter, $structuredOutput, FormatterOptions $options)
194
    {
195
        // If the formatter implements ValidationInterface, then let it
196
        // test the data and throw or return an error
197
        if ($formatter instanceof ValidationInterface) {
198
            return $formatter->validate($structuredOutput);
199
        }
200
        // If the formatter does not implement ValidationInterface, then
201
        // it will never be passed an ArrayObject; we will always give
202
        // it a simple array.
203
        $structuredOutput = $this->simplifyToArray($structuredOutput, $options);
204
        // If we could not simplify to an array, then throw an exception.
205
        // We will never give a formatter anything other than an array
206
        // unless it validates that it can accept the data type.
207
        if (!is_array($structuredOutput)) {
208
            throw new IncompatibleDataException(
209
                $formatter,
210
                $structuredOutput,
211
                []
212
            );
213
        }
214
        return $structuredOutput;
215
    }
216
217
    protected function simplifyToArray($structuredOutput, FormatterOptions $options)
218
    {
219
        // Check to see if any of the simplifiers can convert the given data
220
        // set to an array.
221
        foreach ($this->arraySimplifiers as $simplifier) {
222
            $structuredOutput = $simplifier->simplifyToArray($structuredOutput, $options);
223
        }
224
        // Convert \ArrayObjects to a simple array.
225
        if ($structuredOutput instanceof \ArrayObject) {
226
            return $structuredOutput->getArrayCopy();
227
        }
228
        return $structuredOutput;
229
    }
230
231
    /**
232
     * Restructure the data as necessary (e.g. to select or reorder fields).
233
     *
234
     * @param mixed $structuredOutput
235
     * @param FormatterOptions $options
236
     * @return mixed
237
     */
238
    public function restructureData($structuredOutput, FormatterOptions $options)
239
    {
240
        if ($structuredOutput instanceof RestructureInterface) {
241
            return $structuredOutput->restructure($options);
242
        }
243
        return $structuredOutput;
244
    }
245
246
    /**
247
     * Allow the formatter access to the raw structured data prior
248
     * to restructuring.  For example, the 'list' formatter may wish
249
     * to display the row keys when provided table output.  If this
250
     * function returns a result that does not evaluate to 'false',
251
     * then that result will be used as-is, and restructuring and
252
     * validation will not occur.
253
     *
254
     * @param mixed $structuredOutput
255
     * @param FormatterOptions $options
256
     * @return mixed
257
     */
258
    public function overrideRestructure(FormatterInterface $formatter, $structuredOutput, FormatterOptions $options)
259
    {
260
        if ($formatter instanceof OverrideRestructureInterface) {
261
            return $formatter->overrideRestructure($structuredOutput, $options);
262
        }
263
    }
264
}
265