Skip to content

Commit

Permalink
Improve error in case of multiple admins
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Oct 15, 2020
1 parent 8b56291 commit a6534bc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/Admin/AbstractAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,8 @@ public function attachAdminClass(FieldDescriptionInterface $fieldDescription)
if (null !== $adminCode) {
if (!$pool->hasAdminByAdminCode($adminCode)) {
return;
// NEXT_MAJOR: Uncomment the following exception instead.
// throw new \InvalidArgumentException(sprintf('No admin found for the admin_code "%s"', $adminCode));
}

$admin = $pool->getAdminByAdminCode($adminCode);
Expand All @@ -1487,6 +1489,18 @@ public function attachAdminClass(FieldDescriptionInterface $fieldDescription)

if (!$pool->hasAdminByClass($targetModel)) {
return;
// NEXT_MAJOR: Uncomment the following exception instead.
// throw new \InvalidArgumentException(sprintf(
// 'No admin found for the class "%s", please use the admin_code option instead',
// $targetModel
// ));
}

if (!$pool->hasSingleAdminByClass($targetModel)) {
throw new \InvalidArgumentException(sprintf(
'To many admin found for the class "%s", please use the admin_code option instead',
$targetModel
));
}

$admin = $pool->getAdminByClass($targetModel);
Expand Down
18 changes: 13 additions & 5 deletions src/Admin/Pool.php
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,7 @@ public function getAdminByClass($class)
return null;
}

if (!\is_array($this->adminClasses[$class])) {
throw new \RuntimeException('Invalid format for the Pool::adminClass property');
}

if (\count($this->adminClasses[$class]) > 1) {
if (!$this->hasSingleAdminByClass($class)) {
throw new \RuntimeException(sprintf(
'Unable to find a valid admin for the class: %s, there are too many registered: %s',
$class,
Expand All @@ -249,6 +245,18 @@ public function hasAdminByClass($class)
return isset($this->adminClasses[$class]);
}

/**
* @phpstan-param class-string $class
*/
public function hasSingleAdminByClass(string $class): bool
{
if (!$this->hasAdminByClass($class)) {
return false;
}

return 1 === \count($this->adminClasses[$class]);
}

/**
* Returns an admin class by its Admin code
* ie : sonata.news.admin.post|sonata.news.admin.comment => return the child class of post.
Expand Down

0 comments on commit a6534bc

Please sign in to comment.