Code example for JetApp

 avatar
unknown
php
2 years ago
9.6 kB
14
Indexable
<?php

class CamsComRecordedShowProvider implements RecordedShowProviderInterface
{
    public const RECORDED_SHOW_CREDITS_PRICE = 5.0;

    /**
     * @var UserFanclubRepository
     */
    private $fanClubRepository;

    /**
     * @var ElasticRecordedShowRepository
     */
    private $recordedShowRepository;

    /**
     * @var PerformerDictionaryAttributeService
     */
    private $performerDictionaryAttributeService;

    public function __construct(
        UserFanclubRepository $fanClubRepository,
        ElasticRecordedShowRepository $recordedShowRepository,
        PerformerDictionaryAttributeService $performerDictionaryAttributeService
    ) {
        $this->fanClubRepository  = $fanClubRepository;
        $this->recordedShowRepository = $recordedShowRepository;
        $this->performerDictionaryAttributeService = $performerDictionaryAttributeService;
    }

    /**
     * @return RecordedShow
     * @throws \Elastica\Exception\InvalidException
     * @throws \InvalidArgumentException
     * @throws \LogicException
     * @throws \OutOfBoundsException
     * @throws \WC\Application\Exception\DbException
     */
    public function getRecordedShow(
        Uuid $performerId,
        Uuid $userId,
        string $movieName
    ) : RecordedShow
    {
        if (empty($movieName)) {
            throw new \InvalidArgumentException('movieName is required');
        }

        $recordedShowEntity = $this->recordedShowRepository->findByMovieName($movieName);

        if (!$recordedShowEntity) {
            throw new \LogicException('Recorded show not found by movie name');
        }

        $fanclub = $this->fanClubRepository->findActiveByUserIdAndPerformerId($userId, $performerId);
        $isActiveFanclub = !is_null($fanclub) && $fanclub->isActive();

        $m3uPlaylistUrl = sprintf(
            'https://recordedshows.cams.com:1935/playback-mysql/_definst_/%s/playlist.m3u8',
            $movieName
        );
        $pricing = $isActiveFanclub ? RecordedShow::PRICING_FREE : RecordedShow::PRICING_PAID;

        $isPerformerHasFanclub = $this->getPerformerFanclubAvailable($performerId);

        $recordedShow = new RecordedShow(
            $recordedShowEntity,
            self::RECORDED_SHOW_CREDITS_PRICE,
            $pricing,
            $isPerformerHasFanclub,
        );
        $recordedShow->setM3uPlaylistUrl($m3uPlaylistUrl);

        return $recordedShow;
    }

    private function getPerformerFanclubAvailable(Uuid $performerId): bool
    {
        try {
            $dictionaryAttributes = $this->performerDictionaryAttributeService->findAll($performerId);

            return (bool) $dictionaryAttributes->getFanclubAvailable();
        } catch (\Throwable $exception) {
            return false;
        }
    }
}



----------------------


    public function findPricesByPerformerIdAndServiceTypeCollection(
        Uuid $performerId,
        PerformerServiceTypeCollection $serviceTypeCollection
    ) : PerformerPriceCollection {
        try {
            $serviceTypes = [];

            foreach ($serviceTypeCollection as $serviceType) {
                $serviceTypes[] = $serviceType->getValue();
            }

            $uniqueServiceTypes = array_unique($serviceTypes);

            $rows = $this->connection->createCommand(
                sprintf(
                    "SELECT * FROM %s
                        WHERE performerId = :performerId and serviceType IN ('%s')",
                    self::TABLE_NAME,
                    implode("','", $uniqueServiceTypes),
                ),
            )->bindValues([
                ':performerId' => $performerId->toHexadecimal(),
            ])->queryAll();

            return $this->performerPriceMapper->toPriceCollection($rows);
        } catch (\Throwable $e) {
            throw new DbException($e->getMessage(), $e->getCode(), $e);
        }
    }


------------------------------------------

class AddTrackingCodeOnProductActivatedListener
{
    /**
     * @var TrackingCode
     */
    private $trackingCode;

    public function __construct(TrackingCode $trackingCode)
    {
        $this->trackingCode = $trackingCode;
    }

    public function handle(
        ProductActivatedEvent $event,
        string $eventName,
        EventDispatcherInterface $eventDispatcher
    ): void {
        $permissionsSetIds = $event->getActivatedProductsCollection()
            ->reduce(
                function (array $carry, AbstractProductActivationStrategyResult $result) {
                    $carry[] = $result->getActivationRequest()->getPermissionSetId();

                    return $carry;
                }
            );

        $this->trackingCode->prepareCodes([
            'action' => \TrackingCode::ACTION_BUYPRODUCT,
            'userId' => $event->getUserId()->toHexadecimal(),
            'orderId' => $event->getOrderId()->toHexadecimal(),
            'permissionSetIds' => $permissionsSetIds,
        ]);
    }
}



------------------------------------

class UpdateUserGeoDataRequestHandler implements RequestHandlerInterface
{
    /**
     * @var UserGeoDataCommandBus
     */
    private $userGeoDataCommandBus;

    /**
     * @var ResponseBuilder
     */
    private $responseBuilder;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var IpDetector
     */
    private $ipDetector;

    /**
     * @var GeoInfoProvider
     */
    private $geoInfoProvider;

    /**
     * @var AppL10n
     */
    private $appL10n;

    /**
     * @var PlatformDetector
     */
    private $platformDetector;

    public function __construct(
        UserGeoDataCommandBus $userGeoDataCommandBus,
        ResponseBuilder $responseBuilder,
        LoggerInterface $logger,
        IpDetector $ipDetector,
        GeoInfoProvider $geoInfoProvider,
        AppL10n $appL10n,
        PlatformDetector $platformDetector
    ) {
        $this->userGeoDataCommandBus = $userGeoDataCommandBus;
        $this->responseBuilder = $responseBuilder;
        $this->logger = $logger;
        $this->ipDetector = $ipDetector;
        $this->geoInfoProvider = $geoInfoProvider;
        $this->appL10n = $appL10n;
        $this->platformDetector = $platformDetector;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        try {
            /** @var UserIdentity $userIdentity */
            $userIdentity = $request->getAttribute(UserIdentity::class);

            $params = $request->getParsedBody();

            $offset = $params['offset'] ?? null;
            $userTimezone = $params['timezone'] ?? null;

            if (!$offset && !$userTimezone) {
                throw new HttpException('"offset" or "timezone" is required params', HttpStatusCode::BAD_REQUEST);
            }

            $timezone = $userTimezone;

            if ($offset && !$userTimezone) {
                $this->logger->notice(
                    '[UpdateTimeOffset]: Update by [offset] is deprecated, instead it use [timezone] parameter'
                );

                $timezone = $this->getTimezoneFromOffset((int)$offset * 60);
            }

            if (!$timezone) {
                throw new HttpException(
                    sprintf('Can not fetch timezone by time offset %s', $offset * 60),
                    HttpStatusCode::BAD_REQUEST,
                );
            }

            $userId = new Uuid($userIdentity->getId());
            $environment = $this->getEnvironmentByRequest($request);
            $locale = $this->getL10nDataForUser($userIdentity->getId(), $environment)['locale'];
            $timezoneObject = new \DateTimeZone($timezone);

            $command = new SaveUserGeoDataCommand(
                $userId,
                $locale,
                $timezoneObject,
            );

            $this->userGeoDataCommandBus->handle($command);

            $response = $this->responseBuilder->buildSuccessJsonResponse([]);
        } catch (HttpException $e) {
            $response = $this->responseBuilder->buildFailJsonResponse([], [], $e->getMessage(), $e->getCode());
        } catch (\Throwable $e) {
            $this->logger->error('[UpdateTimeOffset] Failed to handle request', ['exception' => $e]);

            $response = $this->responseBuilder->buildFailJsonResponse(
                [],
                [],
                'Internal Server Error',
                HttpStatusCode::INTERNAL_SERVER_ERROR,
            );
        }

        return $response;
    }

    private function getTimezoneFromOffset(int $timeOffset): string
    {
        $geoData = $this->geoInfoProvider->provideGeoInfo($this->ipDetector->detectIp());

        return $this->appL10n->supposeTimeZoneByTimeOffset(
            $timeOffset,
            $geoData->getCountry() ? $geoData->getCountry()->getAlpha3() : null,
        );
    }

    private function getL10nDataForUser(string $userId, string $environment): array
    {
        return $this->appL10n->getForUser(
            $userId,
            $environment,
            ["tryGetFromHeaders" => true]
        );
    }

    private function getEnvironmentByRequest(ServerRequestInterface $request): string
    {
        $serverParams = $request->getServerParams();

        $platformDetectionRequest = new PlatformDetectionRequest(
            (string) $serverParams['SERVER_NAME'],
            isset($serverParams['HTTP_USER_AGENT']) ? (string) $serverParams['HTTP_USER_AGENT'] : '',
        );

        return $this->platformDetector
            ->detectByDetectionRequest($platformDetectionRequest)
            ->getPlatformName()
            ->getValue();
    }
}

Editor is loading...