. */ declare(strict_types=1); namespace FireflyIII\Services\Internal\Update; use FireflyIII\Models\Category; use FireflyIII\Models\RuleAction; use FireflyIII\Models\RuleTrigger; use Log; /** * Class CategoryUpdateService * * @codeCoverageIgnore */ class CategoryUpdateService { private $user; /** * Constructor. */ public function __construct() { if ('testing' === config('app.env')) { Log::warning(sprintf('%s should not be instantiated in the TEST environment!', get_class($this))); } if(auth()->check()) { $this->user = auth()->user(); } } /** * @param Category $category * @param array $data * * @return Category */ public function update(Category $category, array $data): Category { $oldName = $category->name; $category->name = $data['name']; $category->save(); // update triggers and actions $this->updateRuleTriggers($oldName, $data['name']); $this->updateRuleActions($oldName, $data['name']); return $category; } /** * @param string $oldName * @param string $newName */ private function updateRuleActions(string $oldName, string $newName): void { $types = ['set_category',]; $actions = RuleAction::leftJoin('rules', 'rules.id', '=', 'rule_actions.rule_id') ->where('rules.user_id', $this->user->id) ->whereIn('rule_actions.action_type', $types) ->where('rule_actions.action_value', $oldName) ->get(['rule_actions.*']); Log::debug(sprintf('Found %d actions to update.', $actions->count())); /** @var RuleAction $action */ foreach ($actions as $action) { $action->action_value = $newName; $action->save(); Log::debug(sprintf('Updated action %d: %s', $action->id, $action->action_value)); } } /** * @param string $oldName * @param string $newName */ private function updateRuleTriggers(string $oldName, string $newName): void { $types = ['category_is',]; $triggers = RuleTrigger::leftJoin('rules', 'rules.id', '=', 'rule_triggers.rule_id') ->where('rules.user_id', $this->user->id) ->whereIn('rule_triggers.trigger_type', $types) ->where('rule_triggers.trigger_value', $oldName) ->get(['rule_triggers.*']); Log::debug(sprintf('Found %d triggers to update.', $triggers->count())); /** @var RuleTrigger $trigger */ foreach ($triggers as $trigger) { $trigger->trigger_value = $newName; $trigger->save(); Log::debug(sprintf('Updated trigger %d: %s', $trigger->id, $trigger->trigger_value)); } } /** * @param mixed $user */ public function setUser($user): void { $this->user = $user; } }