<?php

/**
 * Lifestyle Webconsulting GmbH
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is private by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 */

namespace Sso\WebserviceBundle\Security\Authorisation;

use Sso\WebserviceBundle\Entity\Webservice\Type\User;
use Sso\WebserviceBundle\Event\Factory as EventFactory;
use Sso\WebserviceBundle\Event\UserAuthorizationEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 * Class UserAuthorization
 *
 * @copyright  2019 Lifestyle Webconsulting GmbH
 * @link       https://www.life-style.de
 * @package Sso\WebserviceBundle\Security\Authorisation
 */
class UserAuthorization implements UserAuthorizationInterface
{
    /**
     * @var EventDispatcherInterface
     */
    private $eventDispatcher;

    /**
     * @var EventFactory
     */
    private $eventFactory;

    /**
     * UserAuthorization constructor.
     * @param EventDispatcherInterface $eventDispatcher
     * @param EventFactory $eventFactory
     */
    public function __construct(EventDispatcherInterface $eventDispatcher, EventFactory $eventFactory)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->eventFactory = $eventFactory;
    }

    /**
     * @param User $user
     * @return bool
     */
    public function canUpdate(User $user): bool
    {
        return $this->isAuthorized($user, UserAuthorizationEvent::PRE_UPDATE);
    }

    /**
     * @param User $user
     * @return bool
     */
    public function canShow(User $user): bool
    {
        return $this->isAuthorized($user, UserAuthorizationEvent::PRE_SHOW);
    }

    /**
     * @param User $user
     * @return bool
     */
    public function canDelete(User $user): bool
    {
        return $this->isAuthorized($user, UserAuthorizationEvent::PRE_DELETE);
    }

    /**
     * @param User $user
     * @param string $eventName
     * @return bool
     */
    private function isAuthorized(User $user, string $eventName): bool
    {
        $event = $this->eventFactory->userAuthorizationEvent($user);
        $this->eventDispatcher->dispatch($eventName, $event);
        return $event->isAuthorized();
    }
}
