Completed
Push — master ( 10b695...881323 )
by Greg
02:10
created

IncompatibleDataException::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 6
nc 1
nop 3
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
    public function __construct(FormatterInterface $formatter, $data, $allowedTypes)
12
    {
13
        $formatterDescription = get_class($formatter);
14
        $dataDescription = static::describeDataType($data);
15
        $allowedTypesDescription = static::describeAllowedTypes($allowedTypes);
16
        $message = "Data provided to $formatterDescription must be $allowedTypesDescription. Instead, $dataDescription was provided.";
17
        parent::__construct($message, 1);
18
    }
19
20
    protected static function describeDataType($data)
21
    {
22
        if ($data instanceof \ReflectionClass) {
23
            return 'an instance of ' . $data->getName();
24
        }
25
        if (is_object($data)) {
26
            return 'an instance of ' . get_class($data);
27
        }
28
        if (is_array($data)) {
29
            return 'an array';
30
        }
31
        if (is_string($data)) {
32
            return 'a string';
33
        }
34
        return '<' . var_export($data) . '>';
35
    }
36
37
    protected static function describeAllowedTypes($allowedTypes)
38
    {
39
        if (is_array($allowedTypes) && !empty($allowedTypes)) {
40
            if (count($allowedTypes > 1)) {
41
                return describeListOfAllowedTypes($allowedTypes);
42
            }
43
            $allowedTypes = $allowedTypes[0];
44
        }
45
        return static::describeDataType($allowedTypes);
46
    }
47
48
    protected static function describeListOfAllowedTypes($allowedTypes) {
49
        $descriptions = [];
50
        foreach ($allowedTypes as $oneAllowedType) {
51
            $descriptions[] = static::describeDataType($oneAllowedType);
52
        }
53
        if (count($descriptions) == 2) {
54
            return "either {$description[0]} or {$description[1]}";
0 ignored issues
show
Bug introduced by
The variable $description does not exist. Did you mean $descriptions?

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...
55
        }
56
        $lastDescription = array_pop($descriptions);
57
        $otherDescriptions = implode(', ', $descriptions);
58
        return "one of $otherDescriptions or $lastDescription";
59
    }
60
}
61