Passed
Push — master ( e7bef7...3228c5 )
by Vladimir
03:06
created

HtmlField::build()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 39
c 0
b 0
f 0
rs 8.8977
cc 6
nc 1
nop 2
1
<?php
2
namespace GraphQL\Examples\Blog\Type\Field;
3
4
use GraphQL\Examples\Blog\Type\Enum\ContentFormatEnum;
5
use GraphQL\Examples\Blog\Types;
6
7
class HtmlField
8
{
9
    public static function build($name, $objectKey = null)
10
    {
11
        $objectKey = $objectKey ?: $name;
12
13
        // Demonstrates how to organize re-usable fields
14
        // Usual example: when the same field with same args shows up in different types
15
        // (for example when it is a part of some interface)
16
        return [
17
            'name' => $name,
18
            'type' => Types::string(),
19
            'args' => [
20
                'format' => [
21
                    'type' => Types::contentFormatEnum(),
22
                    'defaultValue' => ContentFormatEnum::FORMAT_HTML
23
                ],
24
                'maxLength' => Types::int()
25
            ],
26
            'resolve' => function($object, $args) use ($objectKey) {
27
                $html = $object->{$objectKey};
28
                $text = strip_tags($html);
29
30
                if (!empty($args['maxLength'])) {
31
                    $safeText = mb_substr($text, 0, $args['maxLength']);
32
                } else {
33
                    $safeText = $text;
34
                }
35
36
                switch ($args['format']) {
37
                    case ContentFormatEnum::FORMAT_HTML:
38
                        if ($safeText !== $text) {
39
                            // Text was truncated, so just show what's safe:
40
                            return nl2br($safeText);
41
                        } else {
42
                            return $html;
43
                        }
44
45
                    case ContentFormatEnum::FORMAT_TEXT:
46
                    default:
47
                        return $safeText;
48
                }
49
            }
50
        ];
51
    }
52
}
53