Skip to content
Snippets Groups Projects
AddUserGroupAction.php 1.21 KiB
<?php
declare(strict_types=1);

namespace App\Application\Actions\Group;
use App\Domain\Group\GroupNotFoundException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Domain\Group\Group ;

class AddUserGroupAction extends GroupAction
{
    /**
     * {@inheritdoc}
     */
    protected function action(): Response
    {
        $groupId = (int) $this->resolveArg('id');
        $group = $this->groupRepository->find($groupId);

        if (!isset($group)) {
            throw new GroupNotFoundException();
        }
    
        $currentUser = $this->userRepository->find($_SESSION['userId']);
        if ($group->hasUser($_SESSION['userId'])){
            return $this->response
            ->withHeader('Location', '/groups/' . $groupId)
            ->withStatus(302);
        }
        $currentUser->addGroup($group);        

        $this->em->persist($group);
        $this->em->flush();

        $this->logger->info("User has been added in group.");
        $this->flash->addMessage('add_user', 'User has been added in group.');

        return $this->response
            ->withHeader('Location', '/groups/' . $groupId)
            ->withStatus(302);
    }

}