Completed
Push — master ( 565628...6dc795 )
by Greg
03:21
created

IncompatibleDataException::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 7
cts 7
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 3
crap 1
1
<?php
2
namespace Consolidation\OutputFormatters\Exception;
3
4
use Consolidation\OutputFormatters\FormatterInterface;
5
6
/**
7
 * Represents an incompatibility between the output data and selected formatter.
8
 */
9
class IncompatibleDataException extends \Exception
10
{
11 3
    public function __construct(FormatterInterface $formatter, $data, $allowedTypes)
12
    {
13 3
        $formatterDescription = get_class($formatter);
14 3
        $dataDescription = static::describeDataType($data);
15 3
        $allowedTypesDescription = static::describeAllowedTypes($allowedTypes);
16 3
        $message = "Data provided to $formatterDescription must be $allowedTypesDescription. Instead, $dataDescription was provided.";
17 3
        parent::__construct($message, 1);
18 3
    }
19
20 3
    protected static function describeDataType($data)
21
    {
22 3
        if ($data instanceof \ReflectionClass) {
23 3
            return 'an instance of ' . $data->getName();
24
        }
25 3
        if (is_object($data)) {
26
            return 'an instance of ' . get_class($data);
27
        }
28 3
        if (is_array($data)) {
29 3
            return 'an array';
30
        }
31 1
        if (is_string($data)) {
32 1
            return 'a string';
33
        }
34
        return '<' . var_export($data) . '>';
35
    }
36
37 3
    protected static function describeAllowedTypes($allowedTypes)
38
    {
39 3
        if (is_array($allowedTypes) && !empty($allowedTypes)) {
40 3
            if (count($allowedTypes > 1)) {
41 3
                return static::describeListOfAllowedTypes($allowedTypes);
42
            }
43
            $allowedTypes = $allowedTypes[0];
44
        }
45
        return static::describeDataType($allowedTypes);
46
    }
47
48 3
    protected static function describeListOfAllowedTypes($allowedTypes)
49
    {
50 3
        $descriptions = [];
51 3
        foreach ($allowedTypes as $oneAllowedType) {
52 3
            $descriptions[] = static::describeDataType($oneAllowedType);
53 3
        }
54 3
        if (count($descriptions) == 2) {
55 2
            return "either {$descriptions[0]} or {$descriptions[1]}";
56
        }
57 1
        $lastDescription = array_pop($descriptions);
58 1
        $otherDescriptions = implode(', ', $descriptions);
59 1
        return "one of $otherDescriptions or $lastDescription";
60
    }
61
}
62