File size: 1,696 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
<?php

declare(strict_types=1);

namespace Billing\Application\CommandHandlers;

use Billing\Application\Commands\CancelSubscriptionCommand;
use Billing\Application\Commands\CreateSubscriptionCommand;
use Billing\Domain\Entities\SubscriptionEntity;
use Billing\Domain\Exceptions\NotSubscriptionPlanException;
use Billing\Domain\Exceptions\PlanNotFoundException;
use Billing\Domain\Repositories\PlanRepositoryInterface;
use Shared\Domain\ValueObjects\Id;
use Shared\Infrastructure\CommandBus\Dispatcher;
use Workspace\Domain\Exceptions\WorkspaceNotFoundException;
use Workspace\Domain\Repositories\WorkspaceRepositoryInterface;

class CreateSubscriptionCommandHandler
{
    public function __construct(
        private WorkspaceRepositoryInterface $wrepo,
        private PlanRepositoryInterface $prepo,
        private Dispatcher $dispatcher
    ) {
    }

    /**
     * @throws WorkspaceNotFoundException
     * @throws PlanNotFoundException
     * @throws NotSubscriptionPlanException
     */
    public function handle(CreateSubscriptionCommand $cmd): SubscriptionEntity
    {
        $ws = $cmd->workspace instanceof Id
            ? $this->wrepo->ofId($cmd->workspace) : $cmd->workspace;

        $plan = $cmd->plan instanceof Id
            ? $this->prepo->ofId($cmd->plan) : $cmd->plan;

        $activeSub = $ws->getSubscription();

        $sub = new SubscriptionEntity(
            $ws,
            $plan->getSnapshot(),
            $cmd->trialPeriodDays
        );

        $ws->subscribe($sub);

        if ($activeSub) {
            $cancelCmd = new CancelSubscriptionCommand($activeSub);
            $this->dispatcher->dispatch($cancelCmd);
        }

        return $sub;
    }
}