Skip to content

[12.x] feat: add PolicedBy attribute and policy caching #55765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
65 changes: 55 additions & 10 deletions src/Illuminate/Auth/Access/Gate.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Contracts\Auth\Access\Gate as GateContract;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Eloquent\Attributes\PolicedBy;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
Expand Down Expand Up @@ -652,41 +653,83 @@ protected function resolveAuthCallback($user, $ability, array $arguments)
/**
* Get a policy instance for a given class.
*
* @param object|string $class
* @param object|class-string<*> $class
* @return mixed
*/
public function getPolicyFor($class)
{
$policy = $this->getPolicyClassFor($class);

return $policy ? $this->resolvePolicy($policy) : null;
}

/**
* Get a policy class for a given class.
*
* @param object|class-string<*> $class
* @return class-string<*>|null
*/
public function getPolicyClassFor($class): ?string
{
if (is_object($class)) {
$class = get_class($class);
$class = $class::class;
}

if (! is_string($class)) {
return;
return null;
}

if (isset($this->policies[$class])) {
return $this->resolvePolicy($this->policies[$class]);
return $this->policies[$class];
}

$policy = $this->getPolicedByAttribute($class);

if ($policy !== null) {
return $policy;
}

foreach ($this->guessPolicyName($class) as $guessedPolicy) {
if (class_exists($guessedPolicy)) {
return $this->resolvePolicy($guessedPolicy);
return $guessedPolicy;
}
}

foreach ($this->policies as $expected => $policy) {
if (is_subclass_of($class, $expected)) {
return $this->resolvePolicy($policy);
return $policy;
}
}

return null;
}

/**
* Get the policy from the class attribute.
*
* @param class-string<*> $class
* @return class-string<*>|null
*/
protected function getPolicedByAttribute(string $class): ?string
{
if (! class_exists($class)) {
return null;
}

$attributes = (new ReflectionClass($class))->getAttributes(PolicedBy::class);

if ($attributes === []) {
return null;
}

return $attributes[0]->newInstance()->class;
}

/**
* Guess the policy name for the given class.
*
* @param string $class
* @return array
* @param class-string<*> $class
* @return array<int, class-string<*>>
*/
protected function guessPolicyName($class)
{
Expand Down Expand Up @@ -726,8 +769,10 @@ public function guessPolicyNamesUsing(callable $callback)
/**
* Build a policy class instance of the given type.
*
* @param object|string $class
* @return mixed
* @template TPolicy
*
* @param class-string<TPolicy> $class
* @return TPolicy
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
Expand Down
18 changes: 18 additions & 0 deletions src/Illuminate/Database/Eloquent/Attributes/PolicedBy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Illuminate\Database\Eloquent\Attributes;

use Attribute;

#[Attribute(Attribute::TARGET_CLASS)]
class PolicedBy
{
/**
* Create a new attribute instance.
*
* @param class-string<*> $class
*/
public function __construct(public string $class)
{
}
}
4 changes: 1 addition & 3 deletions src/Illuminate/Database/Eloquent/ModelInspector.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,7 @@ protected function getRelations($model)
*/
protected function getPolicy($model)
{
$policy = Gate::getPolicyFor($model::class);

return $policy ? $policy::class : null;
return Gate::getPolicyClassFor($model::class);
}

/**
Expand Down
17 changes: 17 additions & 0 deletions src/Illuminate/Foundation/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ public static function configure(?string $basePath = null)
return (new Configuration\ApplicationBuilder(new static($basePath)))
->withKernels()
->withEvents()
->withPolicies()
->withCommands()
->withProviders();
}
Expand Down Expand Up @@ -1354,6 +1355,22 @@ public function getCachedEventsPath()
return $this->normalizeCachePath('APP_EVENTS_CACHE', 'cache/events.php');
}

/**
* Determine if the policies are cached.
*/
public function policiesAreCached(): bool
{
return $this['files']->exists($this->getCachedPoliciesPath());
}

/**
* Get the path to the policies cache file.
*/
public function getCachedPoliciesPath(): string
{
return $this->normalizeCachePath('APP_POLICIES_CACHE', 'cache/policies.php');
}

/**
* Normalize a relative or absolute path to a cache file.
*
Expand Down
88 changes: 88 additions & 0 deletions src/Illuminate/Foundation/Auth/DiscoverPolicies.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
use SplFileInfo;
use Symfony\Component\Finder\Finder;

class DiscoverPolicies
{
/**
* The callback to be used to guess class names.
*
* @var (callable(SplFileInfo, string): class-string)|null
*/
public static $guessClassNamesUsingCallback = null;

/**
* Get all of the classes and policies by searching the given class directory.
*
* @param array<int, string>|string $classPaths
* @return array<class-string, class-string>
*/
public static function within(array|string $classPaths, string $basePath): array
{
if (Arr::wrap($classPaths) === []) {
return [];
}

return static::getClassPolicies(
Finder::create()->files()->in($classPaths), $basePath
);
}

/**
* Get all of the classes and their corresponding policies.
*
* @param iterable<SplFileInfo> $files
* @return array<class-string, class-string>
*/
protected static function getClassPolicies(iterable $files, string $basePath): array
{
$policies = [];

foreach ($files as $file) {
$class = static::classFromFile($file, $basePath);
$policy = Gate::getPolicyClassFor($class);

if ($policy !== null) {
$policies[$class] = $policy;
}
}

return $policies;
}

/**
* Extract the class name from the given file path.
*
* @return class-string<*>
*/
protected static function classFromFile(SplFileInfo $file, string $basePath): string
{
if (static::$guessClassNamesUsingCallback) {
return call_user_func(static::$guessClassNamesUsingCallback, $file, $basePath);
}

$class = trim(Str::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);

return ucfirst(Str::camel(str_replace(
[DIRECTORY_SEPARATOR, ucfirst(basename(app()->path())).'\\'],
['\\', app()->getNamespace()],
ucfirst(Str::replaceLast('.php', '', $class))
)));
}

/**
* Specify a callback to be used to guess class names.
*
* @param callable(SplFileInfo, string): class-string<*> $callback
*/
public static function guessClassNamesUsing(callable $callback): void
{
static::$guessClassNamesUsingCallback = $callback;
}
}
28 changes: 28 additions & 0 deletions src/Illuminate/Foundation/Configuration/ApplicationBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Foundation\Bootstrap\RegisterProviders;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as AppAuthServiceProvider;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as AppEventServiceProvider;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as AppRouteServiceProvider;
use Illuminate\Support\Collection;
Expand Down Expand Up @@ -116,6 +117,33 @@ public function withEvents(iterable|bool $discover = true)
return $this;
}

/**
* Register the core auth service provider for the application.
*
* @param iterable<int, string>|bool $discover
* @return $this
*/
public function withPolicies(iterable|bool $discover = true)
{
if (is_iterable($discover)) {
AppAuthServiceProvider::setClassDiscoveryPaths($discover);
}

if ($discover === false) {
AppAuthServiceProvider::disablePolicyDiscovery();
}

if (! isset($this->pendingProviders[AppAuthServiceProvider::class])) {
$this->app->booting(function () {
$this->app->register(AppAuthServiceProvider::class);
});
}

$this->pendingProviders[AppAuthServiceProvider::class] = true;

return $this;
}

/**
* Register the broadcasting services for the application.
*
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Foundation/Console/OptimizeClearCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public function getOptimizeClearTasks()
'compiled' => 'clear-compiled',
'config' => 'config:clear',
'events' => 'event:clear',
'policies' => 'policy:clear',
'routes' => 'route:clear',
'views' => 'view:clear',
...ServiceProvider::$optimizeClearCommands,
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Foundation/Console/OptimizeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ protected function getOptimizeTasks()
return [
'config' => 'config:cache',
'events' => 'event:cache',
'policies' => 'policy:cache',
'routes' => 'route:cache',
'views' => 'view:cache',
...ServiceProvider::$optimizeCommands,
Expand Down
45 changes: 45 additions & 0 deletions src/Illuminate/Foundation/Console/PolicyCacheCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(
name: 'policy:cache',
description: "Discover and cache the application's policies.",
)]
class PolicyCacheCommand extends Command
{
public function handle(): void
{
$this->callSilent('policy:clear');

file_put_contents(
$this->laravel->getCachedPoliciesPath(),
'<?php return '.var_export($this->getPolicies(), true).';',
);

$this->components->info('Policies cached successfully.');
}

/**
* Get all of the policies configured for the application.
*
* @return array<class-string, class-string>
*/
protected function getPolicies(): array
{
$policies = [];

foreach ($this->laravel->getProviders(AuthServiceProvider::class) as $provider) {
$policies[$provider::class] = [
...$provider->discoveredPolicies(),
...$provider->policies(),
];
}

return $policies;
}
}
27 changes: 27 additions & 0 deletions src/Illuminate/Foundation/Console/PolicyClearCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Illuminate\Foundation\Console;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(
name: 'policy:clear',
description: 'Clear all cached policies.',
)]
class PolicyClearCommand extends Command
{
public function __construct(protected Filesystem $files)
{
parent::__construct();
}

/** @throws \RuntimeException */
public function handle(): void
{
$this->files->delete($this->laravel->getCachedPoliciesPath());

$this->components->info('Cached policies cleared successfully.');
}
}
Loading