CreatePasteService   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
c 0
b 0
f 0
lcom 1
cbo 6
dl 0
loc 63
ccs 20
cts 20
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 30 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nastoletni\Code\Application\Service;
6
7
use Nastoletni\Code\Application\Crypter\PasteCrypter;
8
use Nastoletni\Code\Application\Generator\RandomIdGenerator;
9
use Nastoletni\Code\Domain\File;
10
use Nastoletni\Code\Domain\Paste;
11
use Nastoletni\Code\Domain\PasteRepository;
12
13
class CreatePasteService
14
{
15
    /**
16
     * @var PasteRepository
17
     */
18
    private $pasteRepository;
19
20
    /**
21
     * @var PasteCrypter
22
     */
23
    private $pasteCrypter;
24
25
    /**
26
     * CreatePasteService constructor.
27
     *
28
     * @param PasteRepository $pasteRepository
29
     * @param PasteCrypter    $pasteCrypter
30
     */
31 4
    public function __construct(PasteRepository $pasteRepository, PasteCrypter $pasteCrypter)
32
    {
33 4
        $this->pasteRepository = $pasteRepository;
34 4
        $this->pasteCrypter = $pasteCrypter;
35 4
    }
36
37
    /**
38
     * Creates Paste and File entities populating it with unique id and then
39
     * saves it to repository.
40
     *
41
     * @param array $data
42
     *
43
     * @return CreatePastePayload
44
     */
45 4
    public function handle(array $data): CreatePastePayload
46
    {
47
        // Generate pretty for eye key that will be lately used for encrypting.
48 4
        $key = dechex(random_int(0x10000000, 0xFFFFFFFF));
49
50
        do {
51 4
            $paste = new Paste(
52 4
                RandomIdGenerator::nextId(),
53 4
                $data['title'],
54 4
                new \DateTime()
55
            );
56
57 4
            foreach ($data['content'] as $i => $content) {
58 4
                $name = $data['name'][$i];
59
60 4
                $paste->addFile(new File($name, $content));
61
            }
62
63 4
            $this->pasteCrypter->encrypt($paste, $key);
64
65 4
            $alreadyUsed = false;
66
            try {
67 4
                $this->pasteRepository->save($paste);
68 1
            } catch (Paste\AlreadyExistsException $e) {
69 1
                $alreadyUsed = true;
70
            }
71 4
        } while ($alreadyUsed);
72
73 4
        return new CreatePastePayload($paste, $key);
74
    }
75
}
76