Passed
Push — master ( c1e721...8ec156 )
by 世昌
02:05
created

Content   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 43
rs 10
c 0
b 0
f 0
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isTypeOf() 0 12 5
A register() 0 3 1
A send() 0 15 5
1
<?php
2
namespace suda\application\response\provider;
3
4
use SplFileInfo;
5
use ReflectionClass;
6
use JsonSerializable;
7
use suda\application\response\Response;
8
use suda\application\response\provider\type\FileContent;
9
use suda\application\response\provider\type\HtmlContent;
10
use suda\application\response\provider\type\JsonContent;
11
use suda\application\response\provider\type\NullContent;
12
13
/**
14
 * 响应类型处理器
15
 */
16
class Content
17
{
18
    protected static $types = [
19
        JsonContent::class => ['array', JsonSerializable::class],
20
        HtmlContent::class => ['boolean', 'integer','double', 'string'],
21
        NullContent::class => ['NULL'],
22
        FileContent::class => [SplFileInfo::class],
23
    ];
24
25
    public static function register(string $provider, array $types)
26
    {
27
        static::$types[$provider] = $types;
28
    }
29
30
    public static function send($response, $content)
31
    {
32
        foreach (static::$types as $provider => $types) {
33
            foreach ($types as $type) {
34
                if (static::isTypeOf($content, $type)) {
35
                    $provider::send($response, $content, $type);
36
                    return;
37
                }
38
            }
39
        }
40
        if (\method_exists($content, '__toString')) {
41
            HtmlContent::send($response, $content, 'string');
42
            return;
43
        }
44
        throw new \Exception(sprintf('can not encode %s class to response', get_class($content)));
45
    }
46
47
    public static function isTypeOf($data, $type) : bool
48
    {
49
        if (is_object($data) && !\in_array($type, ['boolean', 'integer','double', 'string','array','NULL'])) {
50
            $class = new ReflectionClass($data);
51
            $typeRef = new ReflectionClass($type);
52
            if ($typeRef->isInterface()) {
53
                return $class->implementsInterface($type);
54
            } else {
55
                return $class->isSubclassOf($type) || $class->isInstance($data);
56
            }
57
        } else {
58
            return \gettype($data) === $type;
59
        }
60
    }
61
}
62