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