Completed
Pull Request — master (#5)
by Beñat
03:29
created

RenameFileHandler::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the BenGorFile package.
5
 *
6
 * (c) Beñat Espiña <[email protected]>
7
 * (c) Gorka Laucirica <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace BenGorFile\File\Application\Command\Rename;
14
15
use BenGorFile\File\Domain\Model\FileException;
16
use BenGorFile\File\Domain\Model\FileId;
17
use BenGorFile\File\Domain\Model\FileName;
18
use BenGorFile\File\Domain\Model\FileRepository;
19
use BenGorFile\File\Domain\Model\Filesystem;
20
21
/**
22
 * Rename file handler class.
23
 *
24
 * @author Beñat Espiña <[email protected]>
25
 */
26
class RenameFileHandler
27
{
28
    /**
29
     * The filesystem.
30
     *
31
     * @var Filesystem
32
     */
33
    private $filesystem;
34
35
    /**
36
     * The file repository.
37
     *
38
     * @var FileRepository
39
     */
40
    private $repository;
41
42
    /**
43
     * Constructor.
44
     *
45
     * @param Filesystem     $filesystem  The filesystem
46
     * @param FileRepository $aRepository The file repository
47
     */
48
    public function __construct(Filesystem $filesystem, FileRepository $aRepository)
49
    {
50
        $this->filesystem = $filesystem;
51
        $this->repository = $aRepository;
52
    }
53
54
    /**
55
     * Handles the given command.
56
     *
57
     * @param RenameFileCommand $aCommand The command
58
     *
59
     * @throws FileException when file does not exist
60
     */
61
    public function __invoke(RenameFileCommand $aCommand)
62
    {
63
        $id = new FileId($aCommand->id());
64
        $name = new FileName($aCommand->name());
65
66
        $file = $this->repository->fileOfId($id);
67
        if (null === $file) {
68
            throw FileException::idDoesNotExist($id);
69
        }
70
        $this->filesystem->rename($file->name(), $name);
71
        $file->rename($name);
72
73
        $this->repository->persist($file);
74
    }
75
}
76