Skip to content

Open-source event management and ticket selling platform — perfect for concerts, conferences, and everything in between 🎟️ If you find this project helpful, please consider giving us a star ⭐️

2.1 KB
Raw Blame
<?php

namespace HiEvents\Services\Domain\Order;

use HiEvents\DomainObjects\OrderDomainObject;
use HiEvents\Exceptions\ResourceNotFoundException;
use HiEvents\Repository\Interfaces\OrderRepositoryInterface;
use HiEvents\Services\Infrastructure\DomainEvents\DomainEventDispatcherService;
use HiEvents\Services\Infrastructure\DomainEvents\Enums\DomainEventType;
use HiEvents\Services\Infrastructure\DomainEvents\Events\OrderEvent;
use Illuminate\Database\DatabaseManager;
use Throwable;

class EditOrderService
{
    public function __construct(
        private readonly OrderRepositoryInterface $orderRepository,
        private readonly DomainEventDispatcherService $domainEventDispatcherService,
        private readonly DatabaseManager $databaseManager,
    ) {}

    /**
     * @throws ResourceNotFoundException
     * @throws Throwable
     */
    public function editOrder(
        int $id,
        int $eventId,
        ?string $firstName,
        ?string $lastName,
        ?string $email,
        ?string $notes
    ): OrderDomainObject {
        return $this->databaseManager->transaction(function () use ($id, $firstName, $lastName, $email, $notes, $eventId) {
            $where = [
                'id' => $id,
                'event_id' => $eventId,
            ];

            if ($this->orderRepository->findFirstWhere($where) === null) {
                throw new ResourceNotFoundException(__('Order not found'));
            }

            $this->orderRepository->updateWhere(
                attributes: [
                    ...array_filter([
                        'first_name' => $firstName,
                        'last_name' => $lastName,
                        'notes' => $notes,
                    ]),
                    'email' => $email,
                ],
                where: $where,
            );

            $this->domainEventDispatcherService->dispatch(
                new OrderEvent(
                    type: DomainEventType::ORDER_UPDATED,
                    orderId: $id,
                ),
            );

            return $this->orderRepository->findFirstWhere($where);
        });
    }
}