71 lines
1.8 KiB
PHP

<?php declare(strict_types=1);
namespace App\Services\Registry\V2;
use App\Dto\Service\Registry\V2\AuthorizationService\Scope;
use App\Models\Repository;
use App\Models\User;
use App\Repositories\RepositoryRepository;
use App\Repositories\UserRepository;
final readonly class AccessCommand
{
public function __construct(
private RepositoryRepository $repositoryRepository,
private UserRepository $userRepository,
) { }
public function execute(?Scope $scope, ?User $user): array
{
if (\is_null($scope)) {
return [];
}
$userScope = $this->userRepository->getUserByUsername($scope->getUsername());
if (!$userScope) {
return [];
}
$repository = $this->repositoryRepository->getRepositoryByName($userScope, $scope->getRepositoryName());
if (!$repository) {
return [];
}
return [
[
'type' => 'repository',
'name' => $scope->getUsername() . '/' . $scope->getRepositoryName(),
'actions' => $this->actions($userScope, $repository, $scope, $user),
]
];
}
private function actions(User $userScope, Repository $repository, Scope $scope, ?User $user): array
{
$actions = [];
if ($repository->is_public) {
$actions[] = 'pull';
}
if (\is_null($user)) {
return $actions;
}
if ($userScope->id !== $user->id) {
return $actions;
}
foreach ($scope->getActions() as $action) {
if ($action === 'pull' && $repository->is_public) {
continue;
}
if ($user->can($action, $repository)) {
$actions[] = $action;
}
}
return $actions;
}
}