Passed
Push — master ( 75052b...8ecf83 )
by Dmitri
01:50
created

BookService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Application\Service;
6
7
use App\Application\Command\CreateBook;
8
use App\Application\Dto\Assembler;
9
use App\Application\Dto\BookDto;
10
use App\Application\Exception\BookNotFound;
11
use App\Domain\Model\AuthorId;
12
use App\Domain\Model\Book;
13
use App\Domain\Model\BookId;
14
use App\Domain\Model\BookRepository;
15
use App\Domain\Model\IdGenerator;
16
use Damax\Common\Pagerfanta\CallableDecoratorAdapter;
17
use Pagerfanta\Pagerfanta;
18
19
final class BookService
20
{
21
    private $books;
22
    private $idGenerator;
23
    private $assembler;
24
25
    public function __construct(BookRepository $books, IdGenerator $idGenerator, Assembler $assembler)
26
    {
27
        $this->books = $books;
28
        $this->idGenerator = $idGenerator;
29
        $this->assembler = $assembler;
30
    }
31
32
    public function create(CreateBook $command): BookDto
33
    {
34
        $info = $command->book();
35
        $book = new Book($this->idGenerator->bookId(), AuthorId::fromString($info['author_id']), $info['title']);
36
37
        $this->books->add($book);
38
39
        return $this->assembler->toBookDto($book);
40
    }
41
42
    /**
43
     * @throws BookNotFound
44
     */
45
    public function fetch(string $id): BookDto
46
    {
47
        $bookId = BookId::fromString($id);
48
49
        if (null === $book = $this->books->byId($bookId)) {
50
            throw BookNotFound::byId($bookId);
51
        }
52
53
        return $this->assembler->toBookDto($book);
54
    }
55
56
    public function fetchRange(string $authorId = null): Pagerfanta
57
    {
58
        $adapter = $this->books
59
            ->paginate($authorId ? AuthorId::fromString($authorId) : null)
60
            ->getAdapter()
61
        ;
62
63
        return new Pagerfanta(new CallableDecoratorAdapter($adapter, [$this->assembler, 'toBookDto']));
64
    }
65
}
66