Files
firefly-iii/app/Api/V1/Controllers/Controller.php

243 lines
8.4 KiB
PHP
Raw Normal View History

2018-02-04 13:41:42 +01:00
<?php
2018-05-11 10:08:34 +02:00
2018-02-04 13:41:42 +01:00
/**
* Controller.php
* Copyright (c) 2019 james@firefly-iii.org
2018-02-04 13:41:42 +01:00
*
* This file is part of Firefly III (https://github.com/firefly-iii).
2018-02-04 13:41:42 +01:00
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
2018-02-04 13:41:42 +01:00
*
* This program is distributed in the hope that it will be useful,
2018-02-04 13:41:42 +01:00
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
2018-02-04 13:41:42 +01:00
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
2018-02-04 13:41:42 +01:00
*/
2018-05-11 10:08:34 +02:00
declare(strict_types=1);
2018-02-04 13:41:42 +01:00
namespace FireflyIII\Api\V1\Controllers;
use Carbon\Carbon;
2021-07-04 19:38:17 +02:00
use Carbon\Exceptions\InvalidFormatException;
2025-01-25 04:48:51 +01:00
use FireflyIII\Exceptions\BadHttpHeaderException;
use FireflyIII\Models\Preference;
use FireflyIII\Models\TransactionCurrency;
2024-12-28 07:35:20 +01:00
use FireflyIII\Support\Facades\Amount;
use FireflyIII\Support\Facades\Steam;
use FireflyIII\Support\Http\Api\ValidatesUserGroupTrait;
2025-03-14 19:18:17 +01:00
use FireflyIII\Transformers\AbstractTransformer;
use FireflyIII\User;
2025-01-19 11:34:23 +01:00
use Illuminate\Database\Eloquent\Model;
2018-02-04 13:41:42 +01:00
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
2025-01-19 11:34:23 +01:00
use Illuminate\Pagination\LengthAwarePaginator;
2018-02-04 13:41:42 +01:00
use Illuminate\Routing\Controller as BaseController;
2025-05-29 15:01:06 +02:00
use Illuminate\Support\Facades\Log;
2019-09-04 17:39:39 +02:00
use League\Fractal\Manager;
2025-01-19 11:34:23 +01:00
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection as FractalCollection;
use League\Fractal\Resource\Item;
2019-09-04 17:39:39 +02:00
use League\Fractal\Serializer\JsonApiSerializer;
2023-01-20 22:08:18 +01:00
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\HttpFoundation\ParameterBag;
2018-02-04 13:41:42 +01:00
/**
* Class Controller.
2023-12-22 20:12:38 +01:00
*
2025-01-03 18:16:27 +01:00
* @SuppressWarnings("PHPMD.CouplingBetweenObjects")
2025-01-03 19:07:29 +01:00
* @SuppressWarnings("PHPMD.NumberOfChildren")
2018-02-04 13:41:42 +01:00
*/
2020-07-31 15:12:26 +02:00
abstract class Controller extends BaseController
2018-02-04 13:41:42 +01:00
{
2022-10-30 14:23:00 +01:00
use AuthorizesRequests;
use DispatchesJobs;
use ValidatesRequests;
use ValidatesUserGroupTrait;
2018-02-04 13:41:42 +01:00
protected const string CONTENT_TYPE = 'application/vnd.api+json';
protected const string JSON_CONTENT_TYPE = 'application/json';
protected array $accepts = ['application/json', 'application/vnd.api+json'];
2023-12-20 19:35:52 +01:00
2025-07-31 20:38:57 +02:00
protected bool $convertToPrimary = false;
protected TransactionCurrency $primaryCurrency;
2025-05-04 17:41:26 +02:00
protected ParameterBag $parameters;
2020-07-31 09:24:08 +02:00
2018-02-04 13:41:42 +01:00
/**
* Controller constructor.
*/
public function __construct()
{
// get global parameters
2020-08-22 19:27:16 +02:00
$this->middleware(
function ($request, $next) {
2023-10-05 19:11:17 +02:00
$this->parameters = $this->getParameters();
2020-08-22 19:27:16 +02:00
if (auth()->check()) {
$language = Steam::getLanguage();
2025-07-31 20:38:57 +02:00
$this->convertToPrimary = Amount::convertToPrimary();
$this->primaryCurrency = Amount::getPrimaryCurrency();
2020-08-22 19:27:16 +02:00
app()->setLocale($language);
2025-01-25 04:48:51 +01:00
}
2024-12-26 05:11:32 +01:00
2025-01-25 04:48:51 +01:00
// filter down what this endpoint accepts.
if (!$request->accepts($this->accepts)) {
throw new BadHttpHeaderException(sprintf('Sorry, Accept header "%s" is not something this endpoint can provide.', $request->header('Accept')));
2020-08-22 19:27:16 +02:00
}
2020-10-23 19:11:25 +02:00
2025-01-25 04:48:51 +01:00
2020-08-22 19:27:16 +02:00
return $next($request);
2020-10-23 19:11:25 +02:00
}
);
}
/**
2022-04-12 18:19:30 +02:00
* Method to grab all parameters from the URL.
*/
private function getParameters(): ParameterBag
{
$bag = new ParameterBag();
$page = (int)request()->get('page');
$page = min(max(1, $page), 2 ** 16);
$bag->set('page', $page);
2018-02-13 18:24:06 +01:00
// some date fields:
$dates = ['start', 'end', 'date'];
foreach ($dates as $field) {
2023-02-12 07:23:57 +01:00
$date = null;
2023-12-20 19:35:52 +01:00
2023-01-20 22:08:18 +01:00
try {
$date = request()->query->get($field);
2023-01-21 12:21:06 +01:00
} catch (BadRequestException $e) {
2025-05-29 15:01:06 +02:00
Log::error(sprintf('Request field "%s" contains a non-scalar value. Value set to NULL.', $field));
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
2023-01-20 22:08:18 +01:00
}
$obj = null;
2018-04-02 14:17:11 +02:00
if (null !== $date) {
2018-02-13 18:24:06 +01:00
try {
2025-08-31 19:20:02 +02:00
$obj = Carbon::parse((string)$date, config('app.timezone'));
2025-01-04 08:02:05 +01:00
} catch (InvalidFormatException $e) {
2018-02-13 18:24:06 +01:00
// don't care
2025-08-31 19:20:02 +02:00
Log::warning(sprintf('Ignored invalid date "%s" in API controller parameter check: %s', substr((string)$date, 0, 20), $e->getMessage()));
2018-02-13 18:24:06 +01:00
}
}
if ($obj instanceof Carbon) {
2025-08-31 19:20:02 +02:00
$bag->set($field, $obj);
}
}
// integer fields:
$integers = ['limit'];
foreach ($integers as $integer) {
2023-01-20 22:08:18 +01:00
try {
$value = request()->query->get($integer);
2023-01-21 12:21:06 +01:00
} catch (BadRequestException $e) {
2025-05-29 15:01:06 +02:00
Log::error(sprintf('Request field "%s" contains a non-scalar value. Value set to NULL.', $integer));
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
2023-01-20 22:08:18 +01:00
$value = null;
}
if (null !== $value) {
$value = (int)$value;
2025-09-03 20:34:28 +02:00
$value = min(max(1, $value), 2 ** 16);
2025-01-25 09:17:21 +01:00
$bag->set($integer, $value);
}
2023-12-20 19:35:52 +01:00
if (null === $value
&& 'limit' === $integer // @phpstan-ignore-line
&& auth()->check()) {
2023-10-05 18:52:01 +02:00
// set default for user:
/** @var User $user */
$user = auth()->user();
2023-12-20 19:35:52 +01:00
$pageSize = (int)app('preferences')->getForUser($user, 'listPageSize', 50)->data;
2023-10-05 18:52:01 +02:00
$bag->set($integer, $pageSize);
}
}
2021-05-24 08:06:56 +02:00
// sort fields:
return $bag;
2025-09-03 20:34:28 +02:00
//return $this->getSortParameters($bag);
2018-02-04 13:41:42 +01:00
}
/**
* Method to help build URL's.
*/
final protected function buildParams(): string
{
$return = '?';
$params = [];
foreach ($this->parameters as $key => $value) {
if ('page' === $key) {
continue;
}
if ($value instanceof Carbon) {
$params[$key] = $value->format('Y-m-d');
continue;
}
$params[$key] = $value;
}
return $return.http_build_query($params);
}
final protected function getManager(): Manager
{
// create some objects:
$manager = new Manager();
$baseUrl = request()->getSchemeAndHttpHost().'/api/v1';
$manager->setSerializer(new JsonApiSerializer($baseUrl));
return $manager;
}
2025-01-19 11:34:23 +01:00
final protected function jsonApiList(string $key, LengthAwarePaginator $paginator, AbstractTransformer $transformer): array
{
$manager = new Manager();
$baseUrl = sprintf('%s/api/v1/', request()->getSchemeAndHttpHost());
2025-01-19 11:34:23 +01:00
// TODO add stuff to path?
$manager->setSerializer(new JsonApiSerializer($baseUrl));
$objects = $paginator->getCollection();
2025-01-19 11:34:23 +01:00
// the transformer, at this point, needs to collect information that ALL items in the collection
// require, like meta-data and stuff like that, and save it for later.
// $objects = $transformer->collectMetaData($objects);
2025-01-19 11:34:23 +01:00
$paginator->setCollection($objects);
$resource = new FractalCollection($objects, $transformer, $key);
$resource->setPaginator(new IlluminatePaginatorAdapter($paginator));
return $manager->createData($resource)->toArray();
}
/**
* Returns a JSON API object and returns it.
*
* @param array<int, mixed>|Model $object
*/
final protected function jsonApiObject(string $key, array|Model $object, AbstractTransformer $transformer): array
{
// create some objects:
$manager = new Manager();
$baseUrl = sprintf('%s/api/v1', request()->getSchemeAndHttpHost());
2025-01-19 11:34:23 +01:00
$manager->setSerializer(new JsonApiSerializer($baseUrl));
// $transformer->collectMetaData(new Collection([$object]));
2025-01-19 11:34:23 +01:00
$resource = new Item($object, $transformer, $key);
return $manager->createData($resource)->toArray();
}
2018-02-04 13:41:42 +01:00
}