apply more cs rules for php-cs

This commit is contained in:
2023-10-17 13:27:03 +02:00
parent 0b0cbed9db
commit bc2041cbdd
1485 changed files with 8169 additions and 9620 deletions

View File

@@ -19,8 +19,6 @@ declare(strict_types=1);
namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use LogicException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
@@ -33,18 +31,18 @@ class EventsOnUserSubscriptionCreator
public function __construct(private readonly LoggerInterface $logger, private readonly MachineHttpClient $machineHttpClient, private readonly MapCalendarToUser $mapCalendarToUser, private readonly UrlGeneratorInterface $urlGenerator) {}
/**
* @return array{secret: string, id: string, expiration: int}
*
* @throws ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*
* @return array<secret: string, id: string, expiration: int>
*/
public function createSubscriptionForUser(User $user, DateTimeImmutable $expiration): array
public function createSubscriptionForUser(User $user, \DateTimeImmutable $expiration): array
{
if (null === $userId = $this->mapCalendarToUser->getUserId($user)) {
throw new LogicException('no user id');
throw new \LogicException('no user id');
}
$subscription = [
@@ -56,7 +54,7 @@ class EventsOnUserSubscriptionCreator
),
'resource' => "/users/{$userId}/calendar/events",
'clientState' => $secret = base64_encode(openssl_random_pseudo_bytes(92, $cstrong)),
'expirationDateTime' => $expiration->format(DateTimeImmutable::ATOM),
'expirationDateTime' => $expiration->format(\DateTimeImmutable::ATOM),
];
try {
@@ -79,26 +77,26 @@ class EventsOnUserSubscriptionCreator
}
/**
* @return array{secret: string, id: string, expiration: int}
*
* @throws ClientExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*
* @return array<secret: string, id: string, expiration: int>
*/
public function renewSubscriptionForUser(User $user, DateTimeImmutable $expiration): array
public function renewSubscriptionForUser(User $user, \DateTimeImmutable $expiration): array
{
if (null === $userId = $this->mapCalendarToUser->getUserId($user)) {
throw new LogicException('no user id');
throw new \LogicException('no user id');
}
if (null === $subscriptionId = $this->mapCalendarToUser->getActiveSubscriptionId($user)) {
throw new LogicException('no user id');
throw new \LogicException('no user id');
}
$subscription = [
'expirationDateTime' => $expiration->format(DateTimeImmutable::ATOM),
'expirationDateTime' => $expiration->format(\DateTimeImmutable::ATOM),
];
try {

View File

@@ -13,7 +13,6 @@ namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;
use Chill\CalendarBundle\Exception\UserAbsenceSyncException;
use Chill\MainBundle\Entity\User;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
@@ -43,25 +42,24 @@ final readonly class MSUserAbsenceReader implements MSUserAbsenceReaderInterface
try {
$automaticRepliesSettings = $this->machineHttpClient
->request('GET', 'users/' . $id . '/mailboxSettings/automaticRepliesSetting')
->request('GET', 'users/'.$id.'/mailboxSettings/automaticRepliesSetting')
->toArray(true);
} catch (ClientExceptionInterface|DecodingExceptionInterface|RedirectionExceptionInterface|TransportExceptionInterface $e) {
throw new UserAbsenceSyncException("Error receiving response for mailboxSettings", 0, $e);
throw new UserAbsenceSyncException('Error receiving response for mailboxSettings', 0, $e);
} catch (ServerExceptionInterface $e) {
throw new UserAbsenceSyncException("Server error receiving response for mailboxSettings", 0, $e);
throw new UserAbsenceSyncException('Server error receiving response for mailboxSettings', 0, $e);
}
if (!array_key_exists("status", $automaticRepliesSettings)) {
throw new \LogicException("no key \"status\" on automatic replies settings: " . json_encode($automaticRepliesSettings, JSON_THROW_ON_ERROR));
if (!array_key_exists('status', $automaticRepliesSettings)) {
throw new \LogicException('no key "status" on automatic replies settings: '.json_encode($automaticRepliesSettings, JSON_THROW_ON_ERROR));
}
return match ($automaticRepliesSettings['status']) {
'disabled' => false,
'alwaysEnabled' => true,
'scheduled' =>
RemoteEventConverter::convertStringDateWithoutTimezone($automaticRepliesSettings['scheduledStartDateTime']['dateTime']) < $this->clock->now()
'scheduled' => RemoteEventConverter::convertStringDateWithoutTimezone($automaticRepliesSettings['scheduledStartDateTime']['dateTime']) < $this->clock->now()
&& RemoteEventConverter::convertStringDateWithoutTimezone($automaticRepliesSettings['scheduledEndDateTime']['dateTime']) > $this->clock->now(),
default => throw new UserAbsenceSyncException("this status is not documented by Microsoft")
default => throw new UserAbsenceSyncException('this status is not documented by Microsoft')
};
}
}

View File

@@ -36,13 +36,13 @@ readonly class MSUserAbsenceSync
return;
}
$this->logger->info("will change user absence", ['userId' => $user->getId()]);
$this->logger->info('will change user absence', ['userId' => $user->getId()]);
if ($absence) {
$this->logger->debug("make user absent", ['userId' => $user->getId()]);
$this->logger->debug('make user absent', ['userId' => $user->getId()]);
$user->setAbsenceStart($this->clock->now());
} else {
$this->logger->debug("make user present", ['userId' => $user->getId()]);
$this->logger->debug('make user present', ['userId' => $user->getId()]);
$user->setAbsenceStart(null);
}
}

View File

@@ -19,7 +19,6 @@ declare(strict_types=1);
namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use LogicException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
@@ -30,17 +29,14 @@ class MachineHttpClient implements HttpClientInterface
private readonly HttpClientInterface $decoratedClient;
/**
* @param HttpClientInterface $decoratedClient
*/
public function __construct(private readonly MachineTokenStorage $machineTokenStorage, ?HttpClientInterface $decoratedClient = null)
public function __construct(private readonly MachineTokenStorage $machineTokenStorage, HttpClientInterface $decoratedClient = null)
{
$this->decoratedClient = $decoratedClient ?? \Symfony\Component\HttpClient\HttpClient::create();
}
/**
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
* @throws LogicException if method is not supported
* @throws \LogicException if method is not supported
*/
public function request(string $method, string $url, array $options = []): ResponseInterface
{
@@ -66,13 +62,13 @@ class MachineHttpClient implements HttpClientInterface
break;
default:
throw new LogicException("Method not supported: {$method}");
throw new \LogicException("Method not supported: {$method}");
}
return $this->decoratedClient->request($method, $url, $options);
}
public function stream($responses, ?float $timeout = null): ResponseStreamInterface
public function stream($responses, float $timeout = null): ResponseStreamInterface
{
return $this->decoratedClient->stream($responses, $timeout);
}

View File

@@ -19,12 +19,9 @@ declare(strict_types=1);
namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use LogicException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use function array_key_exists;
/**
* Write metadata to user, which allow to find his default calendar.
@@ -43,12 +40,12 @@ class MapCalendarToUser
public function getActiveSubscriptionId(User $user): string
{
if (!array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
throw new LogicException('do not contains msgraph metadata');
if (!\array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
throw new \LogicException('do not contains msgraph metadata');
}
if (!array_key_exists(self::ID_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY])) {
throw new LogicException('do not contains metadata for subscription id');
if (!\array_key_exists(self::ID_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY])) {
throw new \LogicException('do not contains metadata for subscription id');
}
return $user->getAttributes()[self::METADATA_KEY][self::ID_SUBSCRIPTION_EVENT];
@@ -83,12 +80,12 @@ class MapCalendarToUser
public function getSubscriptionSecret(User $user): string
{
if (!array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
throw new LogicException('do not contains msgraph metadata');
if (!\array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
throw new \LogicException('do not contains msgraph metadata');
}
if (!array_key_exists(self::SECRET_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY])) {
throw new LogicException('do not contains secret in msgraph');
if (!\array_key_exists(self::SECRET_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY])) {
throw new \LogicException('do not contains secret in msgraph');
}
return $user->getAttributes()[self::METADATA_KEY][self::SECRET_SUBSCRIPTION_EVENT];
@@ -114,25 +111,25 @@ class MapCalendarToUser
public function hasActiveSubscription(User $user): bool
{
if (!array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
if (!\array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
return false;
}
if (!array_key_exists(self::EXPIRATION_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY])) {
if (!\array_key_exists(self::EXPIRATION_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY])) {
return false;
}
return $user->getAttributes()[self::METADATA_KEY][self::EXPIRATION_SUBSCRIPTION_EVENT]
>= (new DateTimeImmutable('now'))->getTimestamp();
>= (new \DateTimeImmutable('now'))->getTimestamp();
}
public function hasSubscriptionSecret(User $user): bool
{
if (!array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
if (!\array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
return false;
}
return array_key_exists(self::SECRET_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY]);
return \array_key_exists(self::SECRET_SUBSCRIPTION_EVENT, $user->getAttributes()[self::METADATA_KEY]);
}
public function hasUserId(User $user): bool
@@ -141,11 +138,11 @@ class MapCalendarToUser
return false;
}
if (!array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
if (!\array_key_exists(self::METADATA_KEY, $user->getAttributes())) {
return false;
}
return array_key_exists('id', $user->getAttributes()[self::METADATA_KEY]);
return \array_key_exists('id', $user->getAttributes()[self::METADATA_KEY]);
}
public function writeMetadata(User $user): User
@@ -179,8 +176,8 @@ class MapCalendarToUser
public function writeSubscriptionMetadata(
User $user,
int $expiration,
?string $id = null,
?string $secret = null
string $id = null,
string $secret = null
): void {
$user->setAttributeByDomain(self::METADATA_KEY, self::EXPIRATION_SUBSCRIPTION_EVENT, $expiration);

View File

@@ -19,7 +19,6 @@ declare(strict_types=1);
namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;
use League\OAuth2\Client\Tool\BearerAuthorizationTrait;
use LogicException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
@@ -30,10 +29,7 @@ class OnBehalfOfUserHttpClient
private readonly HttpClientInterface $decoratedClient;
/**
* @param HttpClientInterface $decoratedClient
*/
public function __construct(private readonly OnBehalfOfUserTokenStorage $tokenStorage, ?HttpClientInterface $decoratedClient = null)
public function __construct(private readonly OnBehalfOfUserTokenStorage $tokenStorage, HttpClientInterface $decoratedClient = null)
{
$this->decoratedClient = $decoratedClient ?? \Symfony\Component\HttpClient\HttpClient::create();
}
@@ -61,13 +57,13 @@ class OnBehalfOfUserHttpClient
break;
default:
throw new LogicException("Method not supported: {$method}");
throw new \LogicException("Method not supported: {$method}");
}
return $this->decoratedClient->request($method, $url, $options);
}
public function stream($responses, ?float $timeout = null): ResponseStreamInterface
public function stream($responses, float $timeout = null): ResponseStreamInterface
{
return $this->decoratedClient->stream($responses, $timeout);
}

View File

@@ -18,7 +18,6 @@ declare(strict_types=1);
namespace Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph;
use LogicException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use TheNetworg\OAuth2\Client\Provider\Azure;
use TheNetworg\OAuth2\Client\Token\AccessToken;
@@ -38,7 +37,7 @@ class OnBehalfOfUserTokenStorage
$token = $this->session->get(self::MS_GRAPH_ACCESS_TOKEN, null);
if (null === $token) {
throw new LogicException('unexisting token');
throw new \LogicException('unexisting token');
}
if ($token->hasExpired()) {

View File

@@ -24,11 +24,7 @@ use Chill\CalendarBundle\Entity\Invite;
use Chill\CalendarBundle\RemoteCalendar\Model\RemoteEvent;
use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Templating\Entity\PersonRenderInterface;
use DateTimeImmutable;
use DateTimeZone;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
@@ -52,9 +48,9 @@ class RemoteEventConverter
private const REMOTE_DATETIME_WITHOUT_TZ_FORMAT = 'Y-m-d\TH:i:s.u?';
private readonly DateTimeZone $defaultDateTimeZone;
private readonly \DateTimeZone $defaultDateTimeZone;
private readonly DateTimeZone $remoteDateTimeZone;
private readonly \DateTimeZone $remoteDateTimeZone;
public function __construct(
private readonly \Twig\Environment $engine,
@@ -63,7 +59,7 @@ class RemoteEventConverter
private readonly PersonRenderInterface $personRender,
private readonly TranslatorInterface $translator
) {
$this->defaultDateTimeZone = (new DateTimeImmutable())->getTimezone();
$this->defaultDateTimeZone = (new \DateTimeImmutable())->getTimezone();
$this->remoteDateTimeZone = self::getRemoteTimeZone();
}
@@ -103,7 +99,7 @@ class RemoteEventConverter
{
$result = array_merge(
[
'subject' => '[Chill] ' .
'subject' => '[Chill] '.
implode(
', ',
$calendar->getPersons()->map(fn (Person $p) => $this->personRender->renderString($p, []))->toArray()
@@ -119,7 +115,7 @@ class RemoteEventConverter
'timeZone' => 'UTC',
],
'allowNewTimeProposals' => false,
'transactionId' => 'calendar_' . $calendar->getId(),
'transactionId' => 'calendar_'.$calendar->getId(),
'body' => [
'contentType' => 'text',
'content' => $this->engine->render(
@@ -152,45 +148,45 @@ class RemoteEventConverter
public function convertAvailabilityToRemoteEvent(array $event): RemoteEvent
{
$startDate =
DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['start']['dateTime'], $this->remoteDateTimeZone)
\DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['start']['dateTime'], $this->remoteDateTimeZone)
->setTimezone($this->defaultDateTimeZone);
$endDate =
DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['end']['dateTime'], $this->remoteDateTimeZone)
\DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['end']['dateTime'], $this->remoteDateTimeZone)
->setTimezone($this->defaultDateTimeZone);
return new RemoteEvent(
uniqid('generated_'),
$this->translator->trans('remote_ms_graph.freebusy_statuses.' . $event['status']),
$this->translator->trans('remote_ms_graph.freebusy_statuses.'.$event['status']),
'',
$startDate,
$endDate
);
}
public static function convertStringDateWithoutTimezone(string $date): DateTimeImmutable
public static function convertStringDateWithoutTimezone(string $date): \DateTimeImmutable
{
$d = DateTimeImmutable::createFromFormat(
$d = \DateTimeImmutable::createFromFormat(
self::REMOTE_DATETIME_WITHOUT_TZ_FORMAT,
$date,
self::getRemoteTimeZone()
);
if (false === $d) {
throw new RuntimeException("could not convert string date to datetime: {$date}");
throw new \RuntimeException("could not convert string date to datetime: {$date}");
}
return $d->setTimezone((new DateTimeImmutable())->getTimezone());
return $d->setTimezone((new \DateTimeImmutable())->getTimezone());
}
public static function convertStringDateWithTimezone(string $date): DateTimeImmutable
public static function convertStringDateWithTimezone(string $date): \DateTimeImmutable
{
$d = DateTimeImmutable::createFromFormat(self::REMOTE_DATETIMEZONE_FORMAT, $date);
$d = \DateTimeImmutable::createFromFormat(self::REMOTE_DATETIMEZONE_FORMAT, $date);
if (false === $d) {
throw new RuntimeException("could not convert string date to datetime: {$date}");
throw new \RuntimeException("could not convert string date to datetime: {$date}");
}
$d->setTimezone((new DateTimeImmutable())->getTimezone());
$d->setTimezone((new \DateTimeImmutable())->getTimezone());
return $d;
}
@@ -198,10 +194,10 @@ class RemoteEventConverter
public function convertToRemote(array $event): RemoteEvent
{
$startDate =
DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['start']['dateTime'], $this->remoteDateTimeZone)
\DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['start']['dateTime'], $this->remoteDateTimeZone)
->setTimezone($this->defaultDateTimeZone);
$endDate =
DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['end']['dateTime'], $this->remoteDateTimeZone)
\DateTimeImmutable::createFromFormat(self::REMOTE_DATE_FORMAT, $event['end']['dateTime'], $this->remoteDateTimeZone)
->setTimezone($this->defaultDateTimeZone);
return new RemoteEvent(
@@ -214,26 +210,22 @@ class RemoteEventConverter
);
}
public function getLastModifiedDate(array $event): DateTimeImmutable
public function getLastModifiedDate(array $event): \DateTimeImmutable
{
$date = DateTimeImmutable::createFromFormat(self::REMOTE_DATETIMEZONE_FORMAT, $event['lastModifiedDateTime']);
$date = \DateTimeImmutable::createFromFormat(self::REMOTE_DATETIMEZONE_FORMAT, $event['lastModifiedDateTime']);
if (false === $date) {
$date = DateTimeImmutable::createFromFormat(self::REMOTE_DATETIMEZONE_FORMAT_ALT, $event['lastModifiedDateTime']);
$date = \DateTimeImmutable::createFromFormat(self::REMOTE_DATETIMEZONE_FORMAT_ALT, $event['lastModifiedDateTime']);
}
if (false === $date) {
$this->logger->error(self::class . ' Could not convert lastModifiedDate', [
$this->logger->error(self::class.' Could not convert lastModifiedDate', [
'actual' => $event['lastModifiedDateTime'],
'format' => self::REMOTE_DATETIMEZONE_FORMAT,
'format_alt' => self::REMOTE_DATETIMEZONE_FORMAT_ALT,
]);
throw new RuntimeException(sprintf(
'could not convert lastModifiedDate: %s, expected format: %s',
$event['lastModifiedDateTime'],
self::REMOTE_DATETIMEZONE_FORMAT . ' and ' . self::REMOTE_DATETIMEZONE_FORMAT_ALT
));
throw new \RuntimeException(sprintf('could not convert lastModifiedDate: %s, expected format: %s', $event['lastModifiedDateTime'], self::REMOTE_DATETIMEZONE_FORMAT.' and '.self::REMOTE_DATETIMEZONE_FORMAT_ALT));
}
return $date;
@@ -247,9 +239,9 @@ class RemoteEventConverter
return 'Y-m-d\TH:i:s';
}
public static function getRemoteTimeZone(): DateTimeZone
public static function getRemoteTimeZone(): \DateTimeZone
{
return new DateTimeZone('UTC');
return new \DateTimeZone('UTC');
}
private function buildInviteToAttendee(Invite $invite): array

View File

@@ -24,7 +24,6 @@ use Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph\RemoteEventConverter;
use Chill\MainBundle\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
@@ -45,7 +44,7 @@ class CalendarRangeSyncer
}
$calendarRange->preventEnqueueChanges = true;
$this->logger->info(self::class . ' remove a calendar range because deleted on remote calendar');
$this->logger->info(self::class.' remove a calendar range because deleted on remote calendar');
$this->em->remove($calendarRange);
break;
@@ -57,7 +56,7 @@ class CalendarRangeSyncer
$notification['resource']
)->toArray();
} catch (ClientExceptionInterface $clientException) {
$this->logger->warning(self::class . ' could not retrieve event from ms graph. Already deleted ?', [
$this->logger->warning(self::class.' could not retrieve event from ms graph. Already deleted ?', [
'calendarRangeId' => $calendarRange->getId(),
'remoteEventId' => $notification['resource'],
]);
@@ -68,7 +67,7 @@ class CalendarRangeSyncer
$lastModified = RemoteEventConverter::convertStringDateWithTimezone($new['lastModifiedDateTime']);
if ($calendarRange->getRemoteAttributes()['lastModifiedDateTime'] === $lastModified->getTimestamp()) {
$this->logger->info(self::class . ' change key is equals. Source is probably a local update', [
$this->logger->info(self::class.' change key is equals. Source is probably a local update', [
'calendarRangeId' => $calendarRange->getId(),
'remoteEventId' => $notification['resource'],
]);
@@ -90,7 +89,7 @@ class CalendarRangeSyncer
break;
default:
throw new RuntimeException('This changeType is not suppored: ' . $notification['changeType']);
throw new \RuntimeException('This changeType is not suppored: '.$notification['changeType']);
}
}
}

View File

@@ -23,12 +23,9 @@ use Chill\CalendarBundle\Entity\Invite;
use Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph\RemoteEventConverter;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Repository\UserRepositoryInterface;
use LogicException;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use function in_array;
class CalendarSyncer
{
@@ -39,7 +36,7 @@ class CalendarSyncer
match ($notification['changeType']) {
'deleted' => $this->handleDeleteCalendar($calendar, $notification, $user),
'updated' => $this->handleUpdateCalendar($calendar, $notification, $user),
default => throw new RuntimeException('this change type is not supported: ' . $notification['changeType']),
default => throw new \RuntimeException('this change type is not supported: '.$notification['changeType']),
};
}
@@ -59,7 +56,7 @@ class CalendarSyncer
$notification['resource']
)->toArray();
} catch (ClientExceptionInterface $clientException) {
$this->logger->warning(self::class . ' could not retrieve event from ms graph. Already deleted ?', [
$this->logger->warning(self::class.' could not retrieve event from ms graph. Already deleted ?', [
'calendarId' => $calendar->getId(),
'remoteEventId' => $notification['resource'],
]);
@@ -76,7 +73,7 @@ class CalendarSyncer
);
if ($calendar->getRemoteAttributes()['lastModifiedDateTime'] === $lastModified->getTimestamp()) {
$this->logger->info(self::class . ' change key is equals. Source is probably a local update', [
$this->logger->info(self::class.' change key is equals. Source is probably a local update', [
'calendarRangeId' => $calendar->getId(),
'remoteEventId' => $notification['resource'],
]);
@@ -135,12 +132,12 @@ class CalendarSyncer
'tentativelyAccepted' => $invite->setStatus(Invite::TENTATIVELY_ACCEPTED),
'accepted' => $invite->setStatus(Invite::ACCEPTED),
'declined' => $invite->setStatus(Invite::DECLINED),
default => throw new LogicException('should not happens, not implemented: ' . $status),
default => throw new \LogicException('should not happens, not implemented: '.$status),
};
}
foreach ($calendar->getUsers() as $user) {
if (!in_array(strtolower($user->getEmailCanonical()), $emails, true)) {
if (!\in_array(strtolower($user->getEmailCanonical()), $emails, true)) {
$calendar->removeUser($user);
}
}

View File

@@ -28,8 +28,6 @@ use Chill\CalendarBundle\RemoteCalendar\Connector\MSGraph\RemoteEventConverter;
use Chill\CalendarBundle\Repository\CalendarRangeRepository;
use Chill\CalendarBundle\Repository\CalendarRepository;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use Exception;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
@@ -38,8 +36,6 @@ use Symfony\Component\Security\Core\Security;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use function array_key_exists;
use function count;
class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
{
@@ -47,7 +43,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
public function __construct(private readonly CalendarRepository $calendarRepository, private readonly CalendarRangeRepository $calendarRangeRepository, private readonly HttpClientInterface $machineHttpClient, private readonly MapCalendarToUser $mapCalendarToUser, private readonly LoggerInterface $logger, private readonly OnBehalfOfUserTokenStorage $tokenStorage, private readonly OnBehalfOfUserHttpClient $userHttpClient, private readonly RemoteEventConverter $remoteEventConverter, private readonly TranslatorInterface $translator, private readonly UrlGeneratorInterface $urlGenerator, private readonly Security $security) {}
public function countEventsForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate): int
public function countEventsForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate): int
{
$userId = $this->mapCalendarToUser->getUserId($user);
@@ -58,7 +54,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$data = $this->userHttpClient->request(
'GET',
'users/' . $userId . '/calendarView',
'users/'.$userId.'/calendarView',
[
'query' => [
'startDateTime' => $startDate->setTimezone(RemoteEventConverter::getRemoteTimeZone())->format(RemoteEventConverter::getRemoteDateTimeSimpleFormat()),
@@ -70,7 +66,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
)->toArray();
} catch (ClientExceptionInterface $e) {
if (403 === $e->getResponse()->getStatusCode()) {
return count($this->getScheduleTimesForUser($user, $startDate, $endDate));
return \count($this->getScheduleTimesForUser($user, $startDate, $endDate));
}
$this->logger->error('Could not get list of event on MSGraph', [
@@ -107,6 +103,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$this->logger->debug('mark user ready for msgraph calendar as he does not have any mapping', [
'userId' => $user->getId(),
]);
return true;
}
@@ -114,14 +111,14 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
}
/**
* @return array|\Chill\CalendarBundle\RemoteCalendar\Model\RemoteEvent[]
*
* @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
* @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
*
* @return array|\Chill\CalendarBundle\RemoteCalendar\Model\RemoteEvent[]
*/
public function listEventsForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate, ?int $offset = 0, ?int $limit = 50): array
public function listEventsForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate, ?int $offset = 0, ?int $limit = 50): array
{
$userId = $this->mapCalendarToUser->getUserId($user);
@@ -132,7 +129,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$bareEvents = $this->userHttpClient->request(
'GET',
'users/' . $userId . '/calendarView',
'users/'.$userId.'/calendarView',
[
'query' => [
'startDateTime' => $startDate->setTimezone(RemoteEventConverter::getRemoteTimeZone())->format(RemoteEventConverter::getRemoteDateTimeSimpleFormat()),
@@ -172,7 +169,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
}
}
public function removeCalendar(string $remoteId, array $remoteAttributes, User $user, ?CalendarRange $associatedCalendarRange = null): void
public function removeCalendar(string $remoteId, array $remoteAttributes, User $user, CalendarRange $associatedCalendarRange = null): void
{
if ('' === $remoteId) {
return;
@@ -222,7 +219,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$calendar->getRemoteId(),
$this->translator->trans('remote_ms_graph.cancel_event_because_main_user_is_%label%', ['%label%' => $calendar->getMainUser()]),
$previousMainUser,
'calendar_' . $calendar->getRemoteId()
'calendar_'.$calendar->getRemoteId()
);
$this->createCalendarOnRemote($calendar);
} else {
@@ -300,7 +297,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
break;
default:
throw new Exception('not supported');
throw new \Exception('not supported');
}
try {
@@ -313,7 +310,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$this->logger->warning('could not update calendar range to remote', [
'exception' => $e->getTraceAsString(),
'content' => $e->getResponse()->getContent(),
'calendarRangeId' => 'invite_' . $invite->getId(),
'calendarRangeId' => 'invite_'.$invite->getId(),
]);
throw $e;
@@ -355,7 +352,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
'id' => $id,
'lastModifiedDateTime' => $lastModified,
'changeKey' => $changeKey
] = $this->createOnRemote($eventData, $calendar->getMainUser(), 'calendar_' . $calendar->getId());
] = $this->createOnRemote($eventData, $calendar->getMainUser(), 'calendar_'.$calendar->getId());
if (null === $id) {
return;
@@ -390,7 +387,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$event = $this->machineHttpClient->request(
'POST',
'users/' . $userId . '/calendar/events',
'users/'.$userId.'/calendar/events',
[
'json' => $eventData,
]
@@ -434,7 +431,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
] = $this->createOnRemote(
$eventData,
$calendarRange->getUser(),
'calendar_range_' . $calendarRange->getId()
'calendar_range_'.$calendarRange->getId()
);
$calendarRange->setRemoteId($id)
@@ -457,7 +454,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$userId = $this->mapCalendarToUser->getUserId($user);
if ('' === $iCalUid = ($event['iCalUId'] ?? '')) {
throw new Exception('no iCalUid for this event');
throw new \Exception('no iCalUid for this event');
}
try {
@@ -475,8 +472,8 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
throw $clientException;
}
if (1 !== count($events['value'])) {
throw new Exception('multiple events found with same iCalUid');
if (1 !== \count($events['value'])) {
throw new \Exception('multiple events found with same iCalUid');
}
return $events['value'][0]['id'];
@@ -487,19 +484,13 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$userId = $this->mapCalendarToUser->getUserId($user);
if (null === $userId) {
throw new Exception(
sprintf(
'no remote calendar for this user: %s, remoteid: %s',
$user->getId(),
$remoteId
)
);
throw new \Exception(sprintf('no remote calendar for this user: %s, remoteid: %s', $user->getId(), $remoteId));
}
try {
return $this->machineHttpClient->request(
'GET',
'users/' . $userId . '/calendar/events/' . $remoteId
'users/'.$userId.'/calendar/events/'.$remoteId
)->toArray();
} catch (ClientExceptionInterface $e) {
$this->logger->warning('Could not get event from calendar', [
@@ -510,11 +501,11 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
}
}
private function getScheduleTimesForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate): array
private function getScheduleTimesForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate): array
{
$userId = $this->mapCalendarToUser->getUserId($user);
if (array_key_exists($userId, $this->cacheScheduleTimeForUser)) {
if (\array_key_exists($userId, $this->cacheScheduleTimeForUser)) {
return $this->cacheScheduleTimeForUser[$userId];
}
@@ -529,17 +520,17 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$body = [
'schedules' => [$user->getEmailCanonical()],
'startTime' => [
'dateTime' => ($startDate->setTimezone(RemoteEventConverter::getRemoteTimeZone())->format(RemoteEventConverter::getRemoteDateTimeSimpleFormat())),
'dateTime' => $startDate->setTimezone(RemoteEventConverter::getRemoteTimeZone())->format(RemoteEventConverter::getRemoteDateTimeSimpleFormat()),
'timeZone' => 'UTC',
],
'endTime' => [
'dateTime' => ($endDate->setTimezone(RemoteEventConverter::getRemoteTimeZone())->format(RemoteEventConverter::getRemoteDateTimeSimpleFormat())),
'dateTime' => $endDate->setTimezone(RemoteEventConverter::getRemoteTimeZone())->format(RemoteEventConverter::getRemoteDateTimeSimpleFormat()),
'timeZone' => 'UTC',
],
];
try {
$response = $this->userHttpClient->request('POST', 'users/' . $userId . '/calendar/getSchedule', [
$response = $this->userHttpClient->request('POST', 'users/'.$userId.'/calendar/getSchedule', [
'json' => $body,
])->toArray();
} catch (ClientExceptionInterface $e) {
@@ -564,7 +555,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$eventDatas = [];
$eventDatas[] = $this->remoteEventConverter->calendarToEvent($calendar);
if (0 < count($newInvites)) {
if (0 < \count($newInvites)) {
// it seems that invitaiton are always send, even if attendee changes are mixed with other datas
// $eventDatas[] = $this->remoteEventConverter->calendarToEventAttendeesOnly($calendar);
}
@@ -578,7 +569,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
$calendar->getRemoteId(),
$eventData,
$calendar->getMainUser(),
'calendar_' . $calendar->getId()
'calendar_'.$calendar->getId()
);
$calendar->addRemoteAttributes([
@@ -609,7 +600,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$event = $this->machineHttpClient->request(
'PATCH',
'users/' . $userId . '/calendar/events/' . $remoteId,
'users/'.$userId.'/calendar/events/'.$remoteId,
[
'json' => $eventData,
]
@@ -637,7 +628,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$this->machineHttpClient->request(
'DELETE',
'users/' . $userId . '/calendar/events/' . $remoteId
'users/'.$userId.'/calendar/events/'.$remoteId
);
} catch (ClientExceptionInterface) {
$this->logger->warning('could not remove event from calendar', [
@@ -664,7 +655,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$event = $this->machineHttpClient->request(
'GET',
'users/' . $userId . '/calendar/events/' . $calendarRange->getRemoteId()
'users/'.$userId.'/calendar/events/'.$calendarRange->getRemoteId()
)->toArray();
} catch (ClientExceptionInterface $e) {
$this->logger->warning('Could not get event from calendar', [
@@ -691,7 +682,7 @@ class MSGraphRemoteCalendarConnector implements RemoteCalendarConnectorInterface
try {
$event = $this->machineHttpClient->request(
'PATCH',
'users/' . $userId . '/calendar/events/' . $calendarRange->getRemoteId(),
'users/'.$userId.'/calendar/events/'.$calendarRange->getRemoteId(),
[
'json' => $eventData,
]

View File

@@ -22,20 +22,18 @@ use Chill\CalendarBundle\Entity\Calendar;
use Chill\CalendarBundle\Entity\CalendarRange;
use Chill\CalendarBundle\Entity\Invite;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use LogicException;
use Symfony\Component\HttpFoundation\Response;
class NullRemoteCalendarConnector implements RemoteCalendarConnectorInterface
{
public function countEventsForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate): int
public function countEventsForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate): int
{
return 0;
}
public function getMakeReadyResponse(string $returnPath): Response
{
throw new LogicException('As this connector is always ready, this method should not be called');
throw new \LogicException('As this connector is always ready, this method should not be called');
}
public function isReady(): bool
@@ -43,12 +41,12 @@ class NullRemoteCalendarConnector implements RemoteCalendarConnectorInterface
return true;
}
public function listEventsForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate, ?int $offset = 0, ?int $limit = 50): array
public function listEventsForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate, ?int $offset = 0, ?int $limit = 50): array
{
return [];
}
public function removeCalendar(string $remoteId, array $remoteAttributes, User $user, ?CalendarRange $associatedCalendarRange = null): void {}
public function removeCalendar(string $remoteId, array $remoteAttributes, User $user, CalendarRange $associatedCalendarRange = null): void {}
public function removeCalendarRange(string $remoteId, array $remoteAttributes, User $user): void {}

View File

@@ -23,12 +23,11 @@ use Chill\CalendarBundle\Entity\CalendarRange;
use Chill\CalendarBundle\Entity\Invite;
use Chill\CalendarBundle\RemoteCalendar\Model\RemoteEvent;
use Chill\MainBundle\Entity\User;
use DateTimeImmutable;
use Symfony\Component\HttpFoundation\Response;
interface RemoteCalendarConnectorInterface
{
public function countEventsForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate): int;
public function countEventsForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate): int;
/**
* Return a response, more probably a RedirectResponse, where the user
@@ -46,9 +45,9 @@ interface RemoteCalendarConnectorInterface
/**
* @return array|RemoteEvent[]
*/
public function listEventsForUser(User $user, DateTimeImmutable $startDate, DateTimeImmutable $endDate, ?int $offset = 0, ?int $limit = 50): array;
public function listEventsForUser(User $user, \DateTimeImmutable $startDate, \DateTimeImmutable $endDate, ?int $offset = 0, ?int $limit = 50): array;
public function removeCalendar(string $remoteId, array $remoteAttributes, User $user, ?CalendarRange $associatedCalendarRange = null): void;
public function removeCalendar(string $remoteId, array $remoteAttributes, User $user, CalendarRange $associatedCalendarRange = null): void;
public function removeCalendarRange(string $remoteId, array $remoteAttributes, User $user): void;