master

laravel/framework

Last updated at: 29/12/2023 09:20

PruneStaleTagsCommand.php

TLDR

The provided file, PruneStaleTagsCommand.php, is a part of the Illuminate/Cache package in the Demo Projects project. It contains a command that prunes stale cache tags from the cache, specifically for Redis-based caching.

Methods

There are no methods defined in this file.

Classes

PruneStaleTagsCommand

The PruneStaleTagsCommand class extends the Command class from the Symfony Console component and is responsible for handling the cache:prune-stale-tags console command. It prunes stale cache tags from the cache, but only for Redis-based caching.

  • Properties

    • $name: The name of the console command (cache:prune-stale-tags).
    • $description: The description of the console command ("Prune stale cache tags from the cache (Redis only)").
  • Public Methods

    • handle(CacheManager $cache): Executes the console command. It retrieves the cache store based on the provided store name argument and checks if the store is an instance of RedisStore. If not, it displays an error message and exits. If the store is an instance of RedisStore, it calls the flushStaleTags() method on the cache store to prune stale cache tags. Finally, it displays a success message.
  • Protected Methods

    • getArguments(): Retrieves the console command arguments. It returns an array that includes an optional argument store which represents the name of the store to prune tags from.
<?php

namespace Illuminate\Cache\Console;

use Illuminate\Cache\CacheManager;
use Illuminate\Cache\RedisStore;
use Illuminate\Console\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;

#[AsCommand(name: 'cache:prune-stale-tags')]
class PruneStaleTagsCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'cache:prune-stale-tags';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Prune stale cache tags from the cache (Redis only)';

    /**
     * Execute the console command.
     *
     * @param  \Illuminate\Cache\CacheManager  $cache
     * @return void
     */
    public function handle(CacheManager $cache)
    {
        $cache = $cache->store($this->argument('store'));

        if (! $cache->getStore() instanceof RedisStore) {
            $this->components->error('Pruning cache tags is only necessary when using Redis.');

            return 1;
        }

        $cache->flushStaleTags();

        $this->components->info('Stale cache tags pruned successfully.');
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['store', InputArgument::OPTIONAL, 'The name of the store you would like to prune tags from'],
        ];
    }
}