Last active
April 19, 2022 00:07
-
-
Save chopstik/d695d089976012137501c4136513450d to your computer and use it in GitHub Desktop.
CakePHP Shell to make use of UpdateCounterCache.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Shell; | |
use Cake\Console\Shell; | |
/** | |
* UpdateCounterCaches shell command. | |
*/ | |
class UpdateCounterCachesShell extends Shell | |
{ | |
/** | |
* Current models with counterCache behaviours attached. Edit prior to use. | |
* @var array $_models | |
*/ | |
var $_models = []; | |
/** | |
* main() method. Update the counterCache on a provided model or all models | |
* | |
* @return bool|int|null Success or error code. | |
*/ | |
public function main() | |
{ | |
$this->out($this->getOptionParser()->help()); | |
$model = $this->args[0]; | |
if (!empty($model)) { | |
$this->loadModel($model); | |
$this->out(__('Updating CounterCache on {0}', $model)); | |
$assoc = !empty($this->args[1]) ?? null; | |
$records = $this->{$model}->updateCounterCache($assoc); | |
$this->out("{$records} records updated"); | |
} else { | |
foreach ($this->_models as $model) { | |
$this->loadModel($model); | |
$this->out(__('Updating CounterCache on {0}', $model)); | |
$records = $this->{$model}->updateCounterCache(); | |
$this->out("{$records} records updated"); | |
} | |
} | |
} | |
/** | |
* Manage the available sub-commands along with their arguments and help | |
* @return \Cake\Console\ConsoleOptionParser | |
*/ | |
public function getOptionParser() | |
{ | |
$parser = parent::getOptionParser(); | |
$parser->addArgument('model', [ | |
'index' => 0, | |
'required' => false, | |
'help' => __('Provide a specific model to update')]) | |
->addArgument('association', [ | |
'index' => 1, | |
'required' => false, | |
'help' => __('Provide a specific association on the model'), | |
])->setDescription(__('Update all CounterCaches on all known Models. Adjust Models here: `\App\Shell\UpdateCounterCachesShell::$_models`')); | |
return $parser; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment