Skip to content

Commit

Permalink
Add options to the StaticClearCommand to clear specific routes and uris.
Browse files Browse the repository at this point in the history
  • Loading branch information
david-d-h committed Oct 27, 2023
1 parent 3c2cf15 commit 46fe950
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 3 deletions.
62 changes: 60 additions & 2 deletions src/Commands/StaticClearCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

use Illuminate\Config\Repository;
use Illuminate\Console\Command;
use Illuminate\Routing\Route;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Route as Router;
use Vormkracht10\LaravelStatic\LaravelStatic;

class StaticClearCommand extends Command
{
public $signature = 'static:clear';
public $signature = 'static:clear {--u|uri=*} {--r|routes=*}';

public $description = 'Clear static cached files';

Expand All @@ -26,8 +29,63 @@ public function __construct(Repository $config, LaravelStatic $static)

public function handle(): void
{
$this->static->clear();
$uris = $this->option('uri');

if (! empty($uris)) {
$paths = $this->preparePaths($uris);

$this->static->clear($paths);
} elseif ($routes = Arr::wrap(
$this->option('routes'),
)) {
$this->purgeWithRoutes($routes);
} else {
$this->static->clear();
}

$this->info('✔ Static cache cleared!');
}

protected function purgeWithRoutes(array $names)
{
$routes = Router::getRoutes();

foreach ($names as $name) {
$route = $routes->getByName($name);

if (is_null($route)) {
$this->components->warn("Route [{$name}] not found");

continue;
}

if (count($route->parameterNames()) !== 0) {
$this->components->warn("Route [{$name}] expects parameters, use the -u option instead");

continue;
}

$this->purgeRoute($route);
}
}

protected function purgeRoute(Route $route)
{
$path = $this->preparePaths(
$route->uri(),
);

$this->static->clear($path);
}

protected function preparePaths($uris): array
{
$uris = Arr::wrap($uris);

foreach ($uris as $uri) {
$paths[] = ltrim($uri, '/') . '?.html';
}

return $paths ?? [];
}
}
6 changes: 5 additions & 1 deletion src/LaravelStatic.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@ public function __construct(Repository $config, Filesystem $files)
$this->files = $files;
}

public function clear(): bool
public function clear(?array $paths = null): bool
{
$disk = $this->disk();

if (! is_null($paths)) {
return $disk->delete($paths);
}

$files = $disk->allFiles();

return $disk->delete($files);
Expand Down

0 comments on commit 46fe950

Please sign in to comment.