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

98 lines
2.5 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
}
/**
* @param string $triggerType
* @param string $triggerValue
*
2016-02-17 14:14:32 -06:00
* @param bool $stopProcessing
*
* @return AbstractTrigger
* @throws FireflyException
*/
public static function makeTriggerFromStrings(string $triggerType, string $triggerValue, bool $stopProcessing)
{
/** @var AbstractTrigger $class */
$class = self::getTriggerClass($triggerType);
$obj = $class::makeFromStrings($triggerValue, $stopProcessing);
return $obj;
}
/**
* Returns a map with triggertypes, mapped to the class representing that type
*/
protected static function getTriggerTypes()
{
if (!self::$triggerTypes) {
self::$triggerTypes = Domain::getRuleTriggers();
}
return self::$triggerTypes;
}
/**
* 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
*/
private static function getTriggerClass(string $triggerType): string
2016-02-17 08:29:26 -06:00
{
$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;
}
}