<commit_before><?php

namespace CultuurNet\UDB3\Event\ReadModel\Permission;

use Broadway\Domain\DomainMessage;
use Broadway\EventHandling\EventListenerInterface;
use CultuurNet\UDB3\Cdb\EventItemFactory;
use CultuurNet\UDB3\Event\Events\EventCreatedFromCdbXml;
use CultuurNet\UDB3\Event\Events\EventImportedFromUDB2;
use CultuurNet\UDB3\EventHandling\DelegateEventHandlingToSpecificMethodTrait;
use CultuurNet\UDB3\UiTID\UsersInterface;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use ValueObjects\Exception\InvalidNativeArgumentException;
use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

class Projector implements EventListenerInterface, LoggerAwareInterface
{
    use DelegateEventHandlingToSpecificMethodTrait;
    use LoggerAwareTrait;

    /**
     * @var UsersInterface
     */
    private $users;

    /**
     * @var PermissionRepositoryInterface
     */
    private $permissionRepository;

    public function __construct(
        UsersInterface $users,
        PermissionRepositoryInterface $permissionRepository
    ) {
        $this->users = $users;
        $this->permissionRepository = $permissionRepository;
        $this->logger = new NullLogger();
    }

    protected function applyEventImportedFromUDB2(
        EventImportedFromUDB2 $eventImportedFromUDB2
    ) {
        $cdbEvent = EventItemFactory::createEventFromCdbXml(
            $eventImportedFromUDB2->getCdbXmlNamespaceUri(),
            $eventImportedFromUDB2->getCdbXml()
        );

        $createdByIdentifier = $cdbEvent->getCreatedBy();

        if ($createdByIdentifier) {
            $ownerId = $this->getUserIdByCreatedByIdentifier($createdByIdentifier);

            if (!$ownerId) {
                return;
            }

            $this->permissionRepository->markEventEditableByUser(
                new String($eventImportedFromUDB2->getEventId()),
                $ownerId
            );
        }
    }

    protected function applyEventCreatedFromCdbXml(
        EventCreatedFromCdbXml $eventCreatedFromCdbXml,
        DomainMessage $domainMessage
    ) {
        $cdbEvent = EventItemFactory::createEventFromCdbXml(
            $eventCreatedFromCdbXml->getCdbXmlNamespaceUri(),
            $eventCreatedFromCdbXml->getEventXmlString()->toEventXmlString()
        );

        $createdByIdentifier = $cdbEvent->getCreatedBy();

        // By default the owner is the user who was authenticated when creating
        // the event.
        $metadata = $domainMessage->getMetadata()->serialize();
        $ownerId = new String($metadata['user_id']);

        // If createdby is supplied, consider the user identified by createdby
        // as the owner.
        if ($createdByIdentifier) {
            $ownerId = $this->getUserIdByCreatedByIdentifier($createdByIdentifier);
        }

        if (!$ownerId) {
            return;
        }

        $this->permissionRepository->markEventEditableByUser(
            $eventCreatedFromCdbXml->getEventId(),
            $ownerId
        );
    }

    /**
     * @param $createdByIdentifier
     * @return String
     */
    private function getUserIdByCreatedByIdentifier($createdByIdentifier)
    {
        try {
            $email = new EmailAddress($createdByIdentifier);
            $userId = $this->users->byEmail($email);
        } catch (InvalidNativeArgumentException $e) {
            $nick = new String($createdByIdentifier);
            $userId = $this->users->byNick($nick);
        }

        if (!$userId) {
            $this->logger->warning(
                'Unable to find user with identifier ' . $createdByIdentifier
            );
        }

        return $userId;
    }
}<commit_msg>III-447: Use CreatedByToUserIdResolverInterface in projector instead of UsersInterface<commit_after><?php

namespace CultuurNet\UDB3\Event\ReadModel\Permission;

use Broadway\Domain\DomainMessage;
use Broadway\EventHandling\EventListenerInterface;
use CultuurNet\UDB3\Cdb\CreatedByToUserIdResolverInterface;
use CultuurNet\UDB3\Cdb\EventItemFactory;
use CultuurNet\UDB3\Event\Events\EventCreatedFromCdbXml;
use CultuurNet\UDB3\Event\Events\EventImportedFromUDB2;
use CultuurNet\UDB3\EventHandling\DelegateEventHandlingToSpecificMethodTrait;
use ValueObjects\Exception\InvalidNativeArgumentException;
use ValueObjects\String\String;
use ValueObjects\Web\EmailAddress;

class Projector implements EventListenerInterface
{
    use DelegateEventHandlingToSpecificMethodTrait;

    /**
     * @var CreatedByToUserIdResolverInterface
     */
    private $userIdResolver;

    /**
     * @var PermissionRepositoryInterface
     */
    private $permissionRepository;

    public function __construct(
        PermissionRepositoryInterface $permissionRepository,
        CreatedByToUserIdResolverInterface $createdByToUserIdResolver
    ) {
        $this->userIdResolver = $createdByToUserIdResolver;
        $this->permissionRepository = $permissionRepository;
    }

    protected function applyEventImportedFromUDB2(
        EventImportedFromUDB2 $eventImportedFromUDB2
    ) {
        $cdbEvent = EventItemFactory::createEventFromCdbXml(
            $eventImportedFromUDB2->getCdbXmlNamespaceUri(),
            $eventImportedFromUDB2->getCdbXml()
        );

        $createdByIdentifier = $cdbEvent->getCreatedBy();

        if ($createdByIdentifier) {
            $ownerId = $this->userIdResolver->resolveCreatedByToUserId(
                new String($createdByIdentifier)
            );

            if (!$ownerId) {
                return;
            }

            $this->permissionRepository->markEventEditableByUser(
                new String($eventImportedFromUDB2->getEventId()),
                $ownerId
            );
        }
    }

    protected function applyEventCreatedFromCdbXml(
        EventCreatedFromCdbXml $eventCreatedFromCdbXml,
        DomainMessage $domainMessage
    ) {
        $cdbEvent = EventItemFactory::createEventFromCdbXml(
            $eventCreatedFromCdbXml->getCdbXmlNamespaceUri(),
            $eventCreatedFromCdbXml->getEventXmlString()->toEventXmlString()
        );

        $createdByIdentifier = $cdbEvent->getCreatedBy();

        // By default the owner is the user who was authenticated when creating
        // the event.
        $metadata = $domainMessage->getMetadata()->serialize();
        $ownerId = new String($metadata['user_id']);

        // If createdby is supplied, consider the user identified by createdby
        // as the owner.
        if ($createdByIdentifier) {
            $ownerId = $this->userIdResolver->resolveCreatedByToUserId(
                new String($createdByIdentifier)
            );
        }

        if (!$ownerId) {
            return;
        }

        $this->permissionRepository->markEventEditableByUser(
            $eventCreatedFromCdbXml->getEventId(),
            $ownerId
        );
    }
}
{'fraction_non_alphanumeric': 0.09108049311094997, 'fraction_numerical': 0.004205946337926033, 'mean_word_length': 2.780701754385965, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 50, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3621540', 'n_tokens_mistral': 1896, 'n_tokens_neox': 1845, 'n_words': 306}