Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 0 additions & 78 deletions phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -6511,96 +6511,18 @@
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/MessageFactory.php',
];
$ignoreErrors[] = [
'message' => '#^Argument of an invalid type mixed supplied for foreach, only iterables are supported\\.$#',
'identifier' => 'foreach.nonIterable',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'deleted\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'email\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'is_admin\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'name\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'next_cursor\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'profile\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'real_name\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Method AppBundle\\\\Slack\\\\UsersChecker\\:\\:checkUsersValidity\\(\\) return type has no value type specified in iterable type array\\.$#',
'identifier' => 'missingType.iterableValue',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Parameter \\#1 \\$cursor of method AppBundle\\\\Slack\\\\UsersClient\\:\\:loadPage\\(\\) expects string, mixed given\\.$#',
'identifier' => 'argument.type',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersChecker.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'error\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersClient.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot access offset \'ok\' on mixed\\.$#',
'identifier' => 'offsetAccess.nonOffsetAccessible',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersClient.php',
];
$ignoreErrors[] = [
'message' => '#^Method AppBundle\\\\Slack\\\\UsersClient\\:\\:loadPage\\(\\) return type has no value type specified in iterable type array\\.$#',
'identifier' => 'missingType.iterableValue',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersClient.php',
];
$ignoreErrors[] = [
'message' => '#^Method AppBundle\\\\Slack\\\\UsersClient\\:\\:loadPage\\(\\) should return array but returns mixed\\.$#',
'identifier' => 'return.type',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersClient.php',
];
$ignoreErrors[] = [
'message' => '#^Parameter \\#2 \\.\\.\\.\\$values of function sprintf expects bool\\|float\\|int\\|string\\|null, mixed given\\.$#',
'identifier' => 'argument.type',
'count' => 1,
'path' => __DIR__ . '/sources/AppBundle/Slack/UsersClient.php',
];
$ignoreErrors[] = [
'message' => '#^Cannot cast mixed to string\\.$#',
'identifier' => 'cast.string',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,14 @@ protected function configure(): void

protected function execute(InputInterface $input, OutputInterface $output): int
{
$results = $this->usersChecker->checkUsersValidity();
try {
$results = $this->usersChecker->checkUsersValidity();
} catch (\RuntimeException $e) {
$this->slackNotifier->sendMessage($this->messageFactory->createMessageForMemberNotificationError($e->getMessage()));
$output->writeln(sprintf('<error>Vérification des membres Slack impossible : %s</error>', $e->getMessage()));

return Command::FAILURE;
}

if (($nbResults = count($results)) > 0) {
$message = $this->messageFactory->createMessageForMemberNotification((string) $nbResults);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace AppBundle\Controller\Admin\SlackMembers;

use AppBundle\Slack\UsersChecker;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use Symfony\Component\Security\Http\Attribute\IsGranted;
Expand All @@ -15,14 +16,26 @@ class CheckMembersAction
public function __construct(
private readonly UsersChecker $usersChecker,
private readonly Environment $twig,
private readonly LoggerInterface $logger,
) {}

public function __invoke(): Response
{
$error = null;

try {
$results = $this->usersChecker->checkUsersValidity();
} catch (\RuntimeException $e) {
$results = [];
$error = $e->getMessage();
$this->logger->error('Vérification des membres Slack impossible', ['exception' => $e]);
}

return new Response($this->twig->render('admin/slackmembers/index.html.twig', [
'title' => 'Slack membres',
'techletters' => [],
'results' => $this->usersChecker->checkUsersValidity(),
'results' => $results,
'error' => $error,
]));
}
}
23 changes: 23 additions & 0 deletions sources/AppBundle/Slack/MessageFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,29 @@ public function createMessageForMemberNotification(string $membersToCheckCount):
return $message;
}

public function createMessageForMemberNotificationError(string $error): Message
{
$attachment = new Attachment();
$attachment
->setTitle('Vérification état slack membres : échec')
->setTitleLink('https://afup.org/admin/slackmembers/check')
->setColor('#FF0000')
->addField(
new Field()->setShort(false)->setTitle('Erreur')->setValue($error),
)
;

$message = new Message();
$message
->setChannel('bureau')
->setIconUrl('https://pbs.twimg.com/profile_images/600291061144145920/Lpf3TDQm_400x400.png')
->setUsername('Slack membres')
->addAttachment($attachment)
;

return $message;
}

public function createMessageForGeneralMeeting(PresenceRepository $presenceRepository, UserRepository $userRepository, UrlGeneratorInterface $urlGenerator): Message
{
$latestDate = $presenceRepository->getLatestAttendanceDate();
Expand Down
5 changes: 3 additions & 2 deletions sources/AppBundle/Slack/UsersChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public function __construct(
/**
* Retourne la liste des utilisateurs devant être supprimé du slack membre
* @throws QueryException
* @throws \RuntimeException si l'API Slack ne peut pas être interrogée
*/
public function checkUsersValidity(): array
{
Expand All @@ -29,7 +30,7 @@ public function checkUsersValidity(): array
do {
//Récupère une page d'utilisateur dans Slack
$page = $this->usersClient->loadPage($cursor);
foreach ($page['members'] as $user) {
foreach ($page['members'] ?? [] as $user) {
// Ne traite pas les utilisateurs sans adresse courriel ou supprimé
if (!isset($user['profile']['email']) || $user['deleted'] === true || $user['is_admin'] === true) {
continue;
Expand Down Expand Up @@ -74,7 +75,7 @@ public function checkUsersValidity(): array
}
}
//Récupère le curseur pour la page suivante
$cursor = $page['response_metadata']['next_cursor'];
$cursor = $page['response_metadata']['next_cursor'] ?? '';
} while ($cursor !== '');
return $result;
}
Expand Down
48 changes: 32 additions & 16 deletions sources/AppBundle/Slack/UsersClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@

namespace AppBundle\Slack;

use RuntimeException;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Contracts\HttpClient\Exception\ExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* Client de l'API Web Slack pour lister les utilisateurs de l'espace de travail "Slack Membres".
*/
final readonly class UsersClient
{
public const string USER_LIST_API = '/users.list';
Expand All @@ -16,28 +20,40 @@ public function __construct(
private string $token,
#[Autowire(env: 'SLACK_API_URL')]
private string $apiBaseUrl,
private HttpClientInterface $httpClient,
) {}

/**
* Retourne une page d'utilisateur Slack
* Retourne une page d'utilisateurs Slack.
*
* @param string $cursor curseur pour obtenir la page suivante des utilisateurs Slack
* @return array
* @throws RuntimeException
*
* @return array{ok: true, members?: list<array<string, mixed>>, response_metadata?: array{next_cursor?: string}}
*
* @throws \RuntimeException
*/
public function loadPage($cursor = '')
public function loadPage(string $cursor = ''): array
{
$return = file_get_contents(sprintf("%s%s?token=%s&limit=100&cursor=%s", $this->apiBaseUrl, self::USER_LIST_API, $this->token, $cursor));
if (false === $return) {
throw new RuntimeException("Erreur lors de l'appel à l'API slack");
}
$decodedContent = json_decode($return, true);
if (false === $decodedContent) {
throw new RuntimeException("Erreur lecture retour API slack");
try {
$response = $this->httpClient->request('GET', $this->apiBaseUrl . self::USER_LIST_API, [
'auth_bearer' => $this->token,
'query' => array_filter(['limit' => 100, 'cursor' => $cursor], static fn(int|string $value): bool => $value !== ''),
'timeout' => 10,
]);

/** @var array{ok?: bool, error?: string, members?: list<array<string, mixed>>, response_metadata?: array{next_cursor?: string}} $content */
$content = $response->toArray();
} catch (ExceptionInterface $e) {
throw new \RuntimeException("Erreur lors de l'appel à l'API Slack : " . $e->getMessage(), previous: $e);
}
if (false === $decodedContent["ok"]) {
throw new RuntimeException(sprintf("Erreur sur le retour de l'appel slack : %s",
$decodedContent['error']));

if (($content['ok'] ?? false) !== true) {
throw new \RuntimeException(sprintf(
"Erreur sur le retour de l'appel slack : %s",
$content['error'] ?? 'réponse inattendue',
));
}
return $decodedContent;

return $content;
}
}
7 changes: 6 additions & 1 deletion templates/admin/slackmembers/index.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@
<p>Page de <a href="https://afup-membres.slack.com/admin" target="_blank">Gestion des membres Slack</a>.</p>
</div>

{% if results %}
{% if error %}
<div class="ui negative message">
<div class="header">Impossible d'interroger l'API Slack</div>
<p>{{ error }}</p>
</div>
{% elseif results %}
<table class="ui table striped compact celled">
<thead>
<tr>
Expand Down
73 changes: 73 additions & 0 deletions tests/unit/AppBundle/Slack/UsersCheckerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);

namespace AppBundle\Tests\Slack;

use AppBundle\Association\Model\Repository\UserRepository;
use AppBundle\Slack\UsersChecker;
use AppBundle\Slack\UsersClient;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpClient\MockHttpClient;
use Symfony\Component\HttpClient\Response\JsonMockResponse;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;

final class UsersCheckerTest extends TestCase
{
public function testCheckUsersValidityFollowsPagination(): void
{
$page1 = new JsonMockResponse([
'ok' => true,
'members' => [self::member('alice')],
'response_metadata' => ['next_cursor' => 'dXNlcjpVMDYx='],
]);
$page2 = new JsonMockResponse([
'ok' => true,
'members' => [self::member('bob')],
'response_metadata' => ['next_cursor' => ''],
]);

$userRepository = $this->createStub(UserRepository::class);
$userRepository->method('loadUserByEmailOrAlternateEmail')->willThrowException(new UserNotFoundException());

$checker = new UsersChecker(
new UsersClient('xoxb-token', 'https://slack.test/api', new MockHttpClient([$page1, $page2])),
$userRepository,
);

$results = $checker->checkUsersValidity();

self::assertSame(['alice', 'bob'], array_column($results, 'slack_username'));
self::assertStringNotContainsString('cursor', $page1->getRequestUrl());
self::assertStringContainsString('cursor=dXNlcjpVMDYx%3D', $page2->getRequestUrl());
}

public function testCheckUsersValidityStopsWithoutResponseMetadata(): void
{
$userRepository = $this->createMock(UserRepository::class);
$userRepository->expects(self::never())->method('loadUserByEmailOrAlternateEmail');

$checker = new UsersChecker(
new UsersClient('xoxb-token', 'https://slack.test/api', new MockHttpClient([
new JsonMockResponse(['ok' => true, 'members' => []]),
])),
$userRepository,
);

self::assertSame([], $checker->checkUsersValidity());
}

/**
* @return array<string, mixed>
*/
private static function member(string $name): array
{
return [
'name' => $name,
'real_name' => ucfirst($name),
'deleted' => false,
'is_admin' => false,
'profile' => ['email' => $name . '@example.com'],
];
}
}
Loading
Loading