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
16 changes: 15 additions & 1 deletion src/Policy/MapResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
namespace Authorization\Policy;

use Authorization\Policy\Exception\MissingPolicyException;
use Cake\Core\ContainerInterface;
use InvalidArgumentException;

/**
Expand All @@ -32,6 +33,13 @@ class MapResolver implements ResolverInterface
*/
protected array $map = [];

/**
* The DIC instance from the application
*
* @var \Cake\Core\ContainerInterface|null
*/
protected ?ContainerInterface $container;

/**
* Constructor.
*
Expand All @@ -45,9 +53,11 @@ class MapResolver implements ResolverInterface
* ```
*
* @param array $map Resource class name to policy map.
* @param \Cake\Core\ContainerInterface|null $container The DIC instance from the application
*/
public function __construct(array $map = [])
public function __construct(array $map = [], ?ContainerInterface $container = null)
{
$this->container = $container;
foreach ($map as $resourceClass => $policy) {
$this->map($resourceClass, $policy);
}
Expand Down Expand Up @@ -107,6 +117,10 @@ public function getPolicy($resource): mixed
return $policy;
}

if ($this->container && $this->container->has($policy)) {
return $this->container->get($policy);
}

return new $policy();
}
}
25 changes: 25 additions & 0 deletions tests/TestCase/Policy/MapResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@
*/
namespace Authorization\Test\TestCase\Policy;

use Authorization\AuthorizationService;
use Authorization\IdentityDecorator;
use Authorization\Policy\Exception\MissingPolicyException;
use Authorization\Policy\MapResolver;
use Cake\Core\Container;
use Cake\TestSuite\TestCase;
use InvalidArgumentException;
use TestApp\Model\Entity\Article;
use TestApp\Policy\ArticlePolicy;
use TestApp\Service\TestService;

class MapResolverTest extends TestCase
{
Expand Down Expand Up @@ -102,4 +106,25 @@ public function testGetPolicyMissing()

$resolver->getPolicy(new Article());
}

public function testGetPolicyViaDIC()
{
$container = new Container();
$container->add(TestService::class);
$container->add(ArticlePolicy::class)
->addArgument(TestService::class);

$article = new Article();
$resolver = new MapResolver([], $container);
$resolver->map(Article::class, ArticlePolicy::class);

$service = new AuthorizationService($resolver);
$user = new IdentityDecorator($service, [
'role' => 'admin',
]);

$policy = $resolver->getPolicy($article);
$this->assertInstanceOf(ArticlePolicy::class, $policy);
$this->assertTrue($policy->canWithInjectedService($user, $article));
}
}