DbalPasteMapper::validateData()   B
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 15
cts 15
cp 1
rs 8.8977
c 0
b 0
f 0
cc 6
nc 9
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nastoletni\Code\Infrastructure\Dbal;
6
7
use DateTime;
8
use Nastoletni\Code\Application\InvalidDataException;
9
use Nastoletni\Code\Domain\File;
10
use Nastoletni\Code\Domain\Paste;
11
12
class DbalPasteMapper
13
{
14
    /**
15
     * Maps array to Paste entity.
16
     *
17
     * @param array $data Associative array of paste fields.
18
     *
19
     * @return Paste
20
     */
21 6
    public function map(array $data): Paste
22
    {
23 6
        $this->validateData($data);
24
25 1
        $paste = new Paste(
26 1
            Paste\Id::createFromBase10((int) $data[0]['id']),
27 1
            empty($data[0]['title']) ? null : $data[0]['title'],
28 1
            new DateTime($data[0]['created_at'])
29
        );
30
31 1
        foreach ($data as $file) {
32 1
            $file = new File(
33 1
                empty($file['filename']) ? null : $file['filename'],
34 1
                $file['content']
35
            );
36
37 1
            $paste->addFile($file);
38
        }
39
40 1
        return $paste;
41
    }
42
43
    /**
44
     * Checks whether given data is valid.
45
     *
46
     * @param array $data
47
     *
48
     * @throws InvalidDataException when data is invalid.
49
     */
50 6
    private function validateData(array $data): void
51
    {
52 6
        $pasteRequiredFields = ['id', 'title', 'created_at'];
53 6
        $fileRequiredFields = ['filename', 'content'];
54
55 6
        foreach ($pasteRequiredFields as $pasteRequiredField) {
56 6
            if (!array_key_exists($pasteRequiredField, $data[0])) {
57 3
                throw new InvalidDataException(sprintf(
58 3
                    'Given data has to have \'%s\' key.',
59 6
                    $pasteRequiredField
60
                ));
61
            }
62
        }
63
64 3
        foreach ($data as $file) {
65 3
            foreach ($fileRequiredFields as $fileRequiredField) {
66 3
                if (!array_key_exists($fileRequiredField, $file)) {
67 2
                    throw new InvalidDataException(sprintf(
68 2
                        'Given data\'s files have to have \'%s\' key.',
69 3
                        $fileRequiredField
70
                    ));
71
                }
72
            }
73
        }
74 1
    }
75
}
76