First code for YNAB import #145

This commit is contained in:
James Cole
2018-07-29 07:30:06 +02:00
parent a1005d91df
commit 8efbeb14d2
16 changed files with 627 additions and 13 deletions

View File

@@ -0,0 +1,86 @@
<?php
/**
* StageGetAccessHandler.php
* Copyright (c) 2018 thegrumpydictator@gmail.com
*
* This file is part of Firefly III.
*
* Firefly III is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Firefly III is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Firefly III. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
namespace FireflyIII\Support\Import\Routine\Ynab;
use Exception;
use FireflyIII\Exceptions\FireflyException;
use FireflyIII\Models\ImportJob;
use FireflyIII\Repositories\ImportJob\ImportJobRepositoryInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Log;
/**
* Class StageGetAccessHandler
*/
class StageGetAccessHandler
{
/** @var ImportJob */
private $importJob;
/** @var ImportJobRepositoryInterface */
private $repository;
/**
* Send a token request to YNAB. Return with access token (if all goes well).
*
* @throws FireflyException
*/
public function run(): void
{
$config = $this->repository->getConfiguration($this->importJob);
$clientId = app('preferences')->get('ynab_client_id', '')->data;
$clientSecret = app('preferences')->get('ynab_client_secret', '')->data;
$redirectUri = route('import.callback.ynab');
$code = $config['auth_code'];
$uri = sprintf(
'https://app.youneedabudget.com/oauth/token?client_id=%s&client_secret=%s&redirect_uri=%s&grant_type=authorization_code&code=%s', $clientId,
$clientSecret, $redirectUri, $code
);
$client = new Client;
try {
$res = $client->request('POST', $uri);
} catch (GuzzleException|Exception $e) {
Log::error($e->getMessage());
Log::error($e->getTraceAsString());
throw new FireflyException($e->getMessage());
}
$statusCode = $res->getStatusCode();
$content = trim($res->getBody()->getContents());
$json = json_decode($content, true) ?? [];
Log::debug(sprintf('Status code from YNAB is %d', $statusCode));
Log::debug(sprintf('Body of result is %s', $content), $json);
Log::error('Hard exit');
exit;
}
/**
* @param ImportJob $importJob
*/
public function setImportJob(ImportJob $importJob): void
{
$this->importJob = $importJob;
$this->repository = app(ImportJobRepositoryInterface::class);
$this->repository->setUser($importJob->user);
}
}