firefly-iii/app/Rules/Triggers/TriggerFactory.php

80 lines
2.0 KiB
PHP
Raw Normal View History

<?php
declare(strict_types = 1);
/**
* TriggerFactory.php
* Copyright (C) 2016 Robert Horlings
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace FireflyIII\Rules\Triggers;
2016-02-17 08:52:46 -06:00
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\RuleTrigger;
use FireflyIII\Support\Domain;
/**
* Interface TriggerInterface
*
* @package FireflyIII\Rules\Triggers
*/
class TriggerFactory
{
protected static $triggerTypes = null;
2016-02-17 08:29:26 -06:00
2016-02-17 08:38:21 -06:00
/**
* Returns the trigger for the given type and journal
*
* @param RuleTrigger $trigger
2016-02-17 08:38:21 -06:00
*
2016-02-17 13:19:44 -06:00
* @return AbstractTrigger
2016-02-17 08:38:21 -06:00
*/
2016-02-17 13:19:44 -06:00
public static function getTrigger(RuleTrigger $trigger)
2016-02-17 08:38:21 -06:00
{
$triggerType = $trigger->trigger_type;
2016-02-17 13:19:44 -06:00
/** @var AbstractTrigger $class */
$class = self::getTriggerClass($triggerType);
$obj = $class::makeFromTriggerValue($trigger->trigger_value);
return $obj;
2016-02-17 08:38:21 -06:00
}
/**
* Returns the class name to be used for triggers with the given name
2016-02-17 08:29:26 -06:00
*
* @param string $triggerType
2016-02-17 08:29:26 -06:00
*
* @return TriggerInterface|string
* @throws FireflyException
*/
2016-02-17 08:29:26 -06:00
public static function getTriggerClass(string $triggerType): string
{
$triggerTypes = self::getTriggerTypes();
2016-02-17 08:29:26 -06:00
if (!array_key_exists($triggerType, $triggerTypes)) {
2016-02-17 08:52:46 -06:00
throw new FireflyException('No such trigger exists ("' . e($triggerType) . '").');
}
2016-02-17 08:29:26 -06:00
$class = $triggerTypes[$triggerType];
if (!class_exists($class)) {
2016-02-17 08:52:46 -06:00
throw new FireflyException('Could not instantiate class for rule trigger type "' . e($triggerType) . '" (' . e($class) . ').');
}
2016-02-17 08:29:26 -06:00
return $class;
}
2016-02-17 08:29:26 -06:00
/**
* Returns a map with triggertypes, mapped to the class representing that type
*/
2016-02-17 08:29:26 -06:00
protected static function getTriggerTypes()
{
if (!self::$triggerTypes) {
self::$triggerTypes = Domain::getRuleTriggers();
}
2016-02-17 08:29:26 -06:00
return self::$triggerTypes;
}
}