File size: 1,500 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

declare(strict_types=1);

namespace Affiliate\Application\CommandHandlers;

use Affiliate\Application\Commands\ListPayoutsCommand;
use Affiliate\Domain\Entities\PayoutEntity;
use Affiliate\Domain\Exceptions\PayoutNotFoundException;
use Affiliate\Domain\Repositories\PayoutRepositoryInterface;
use Shared\Domain\ValueObjects\CursorDirection;
use Traversable;

class ListPayoutsCommandHandler
{
    public function __construct(
        private PayoutRepositoryInterface $repo
    ) {}

    /**
     * @return Traversable<PayoutEntity>
     * @throws PayoutNotFoundException
     */
    public function handle(ListPayoutsCommand $cmd): Traversable
    {
        $cursor = $cmd->cursor
            ? $this->repo->ofId($cmd->cursor)
            : null;

        $payouts = $this->repo;

        if ($cmd->sortDirection) {
            $payouts = $payouts->sort($cmd->sortDirection, $cmd->sortParameter);
        }

        if ($cmd->status) {
            $payouts = $payouts->filterByStatus($cmd->status);
        }

        if ($cmd->user) {
            $payouts = $payouts->filterByUser($cmd->user);
        }

        if ($cmd->maxResults) {
            $payouts = $payouts->setMaxResults($cmd->maxResults);
        }

        if ($cursor) {
            if ($cmd->cursorDirection == CursorDirection::ENDING_BEFORE) {
                return $payouts = $payouts->endingBefore($cursor);
            }

            return $payouts->startingAfter($cursor);
        }

        return $payouts;
    }
}