Completed
Pull Request — master (#25)
by Greg
02:58
created

AbstractDataFormatException   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 14
lcom 0
cbo 0
dl 0
loc 51
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B describeDataType() 0 16 7
A describeAllowedTypes() 0 10 4
A describeListOfAllowedTypes() 0 13 3
1
<?php
2
namespace Consolidation\OutputFormatters\Exception;
3
4
use Consolidation\OutputFormatters\FormatterInterface;
5
6
/**
7
 * Contains some helper functions used by exceptions in this project.
8
 */
9
abstract class AbstractDataFormatException extends \Exception
10
{
11
    /**
12
     * Return a description of the data type represented by the provided parameter.
13
     *
14
     * @param \ReflectionClass $data The data type to describe. Note that
15
     *   \ArrayObject is used as a proxy to mean an array primitive (or an ArrayObject).
16
     * @return string
17
     */
18
    protected static function describeDataType($data)
19
    {
20
        if (is_array($data) || ($data instanceof \ReflectionClass)) {
21
            if (is_array($data) || ($data->getName() == 'ArrayObject')) {
22
                return 'an array';
23
            }
24
            return 'an instance of ' . $data->getName();
25
        }
26
        if (is_string($data)) {
27
            return 'a string';
28
        }
29
        if (is_object($data)) {
30
            return 'an instance of ' . get_class($data);
31
        }
32
        throw new \Exception("Undescribable data error: " . var_export($data, true));
33
    }
34
35
    protected static function describeAllowedTypes($allowedTypes)
36
    {
37
        if (is_array($allowedTypes) && !empty($allowedTypes)) {
38
            if (count($allowedTypes) > 1) {
39
                return static::describeListOfAllowedTypes($allowedTypes);
40
            }
41
            $allowedTypes = $allowedTypes[0];
42
        }
43
        return static::describeDataType($allowedTypes);
44
    }
45
46
    protected static function describeListOfAllowedTypes($allowedTypes)
47
    {
48
        $descriptions = [];
49
        foreach ($allowedTypes as $oneAllowedType) {
50
            $descriptions[] = static::describeDataType($oneAllowedType);
51
        }
52
        if (count($descriptions) == 2) {
53
            return "either {$descriptions[0]} or {$descriptions[1]}";
54
        }
55
        $lastDescription = array_pop($descriptions);
56
        $otherDescriptions = implode(', ', $descriptions);
57
        return "one of $otherDescriptions or $lastDescription";
58
    }
59
}
60