. */ /** @noinspection MultipleReturnStatementsInspection */ declare(strict_types=1); namespace FireflyIII\Factory; use FireflyIII\Models\Category; use FireflyIII\User; use Illuminate\Support\Collection; use Log; /** * Class CategoryFactory */ class CategoryFactory { /** * Constructor. */ public function __construct() { if ('testing' === config('app.env')) { Log::warning(sprintf('%s should not be instantiated in the TEST environment!', \get_class($this))); } } /** @var User */ private $user; /** * @param string $name * * @return Category|null */ public function findByName(string $name): ?Category { $result = null; /** @var Collection $collection */ $collection = $this->user->categories()->get(); /** @var Category $category */ foreach ($collection as $category) { if ($category->name === $name) { $result = $category; break; } } return $result; } /** * @param int|null $categoryId * @param null|string $categoryName * * @return Category|null * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function findOrCreate(?int $categoryId, ?string $categoryName): ?Category { $categoryId = (int)$categoryId; $categoryName = (string)$categoryName; Log::debug(sprintf('Going to find category with ID %d and name "%s"', $categoryId, $categoryName)); if ('' === $categoryName && 0 === $categoryId) { return null; } // first by ID: if ($categoryId > 0) { /** @var Category $category */ $category = $this->user->categories()->find($categoryId); if (null !== $category) { return $category; } } if (\strlen($categoryName) > 0) { $category = $this->findByName($categoryName); if (null !== $category) { return $category; } return Category::create( [ 'user_id' => $this->user->id, 'name' => $categoryName, ] ); } return null; } /** * @param User $user */ public function setUser(User $user): void { $this->user = $user; } }