PayloadGenerator::formatFile()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace DiscordWebhook\Generator;
5
6
use DateTime;
7
use SplFileInfo;
8
use Symfony\Component\Serializer\Encoder\JsonEncoder;
9
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
10
use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader;
11
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
12
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
13
use Symfony\Component\Serializer\Serializer;
14
15
/**
16
 * Class PayloadGenerator
17
 *
18
 * @package DiscordWebhook\Generator
19
 * @author Scrummer <[email protected]>
20
 */
21
class PayloadGenerator
22
{
23
    /**
24
     * @var Serializer
25
     */
26
    private $serializer;
27
28
    public function __construct()
29
    {
30
        $classMetadataFactory = new ClassMetadataFactory(new YamlFileLoader(__DIR__ . '/../../config/serializer/definitions.yml'));
31
        $metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
32
        $defaultContext = [
33
            ObjectNormalizer::CALLBACKS => [
34
                'timestamp' => [$this, 'formatTimestamp'],
35
                'file' => [$this, 'formatFile']
36
            ],
37
            ObjectNormalizer::SKIP_NULL_VALUES => true
38
        ];
39
40
        $normalizer = new ObjectNormalizer(
41
            $classMetadataFactory,
42
            $metadataAwareNameConverter,
43
            null,
44
            null,
45
            null,
46
            null,
47
            $defaultContext
48
        );
49
50
        $this->serializer = new Serializer([$normalizer], [new JsonEncoder()]);
51
    }
52
53
    public function generate(object $object): array
54
    {
55
        $data = [];
56
        $normalizedData = $this->serializer->normalize(
57
            $object,
58
            null,
59
            [
60
                ObjectNormalizer::ALLOW_EXTRA_ATTRIBUTES => false
61
            ]
62
        );
63
64
        if (!array_key_exists('embeds', $normalizedData)) {
65
            foreach ($normalizedData as $field => $content) {
66
                $tmpData = [
67
                    'name' => $field,
68
                    'contents' => $content
69
                ];
70
71
                if ($field === 'file' && $field !== null) {
72
                    $tmpData = $content;
73
                }
74
75
                $data['multipart'][] = $tmpData;
76
            }
77
        } else { // only send it as json when there are embeds
78
            $data['form_params']['payload_json'] = $this->serializer->encode($normalizedData, JsonEncoder::FORMAT);
79
        }
80
81
        return $data;
82
    }
83
84
    public function formatTimestamp($dateTime): ?string
85
    {
86
        return $dateTime instanceof DateTime ? $dateTime->format(DateTime::ATOM) : null;
87
    }
88
89
    public function formatFile($file): ?array
90
    {
91
        if ($file instanceof SplFileInfo) {
92
            return [
93
                'name' => 'file',
94
                'contents' => $file->openFile()->fread($file->getSize()),
95
                'filename' => $file->getFilename()
96
            ];
97
        }
98
99
        return null;
100
    }
101
}
102