invoiceninja/app/Services/Migration/CompleteService.php

109 lines
2.3 KiB
PHP
Raw Normal View History

<?php
namespace App\Services\Migration;
use Illuminate\Support\Facades\Storage;
use Unirest\Request;
class CompleteService
{
protected $token;
2020-11-10 16:20:02 +01:00
protected $endpoint = 'https://app.invoiceninja.com';
2020-11-10 16:20:02 +01:00
2020-11-11 18:26:33 +01:00
protected $uri = 'api/v1/migration/start';
2020-11-10 16:20:02 +01:00
protected $errors = [];
2020-11-10 16:20:02 +01:00
protected $isSuccessful;
2020-11-10 16:20:02 +01:00
protected $data;
public function __construct(string $token)
{
$this->token = $token;
}
2020-11-10 16:20:02 +01:00
public function data(array $data)
{
2020-11-10 16:20:02 +01:00
$this->data = $data;
return $this;
}
public function endpoint(string $endpoint)
{
$this->endpoint = $endpoint;
return $this;
}
public function start()
{
2020-11-11 18:26:33 +01:00
$files = [];
2020-11-10 16:20:02 +01:00
foreach ($this->data as $companyKey => $companyData) {
2020-11-23 13:07:32 +11:00
2020-11-11 18:26:33 +01:00
$data[] = [
2020-11-23 13:07:32 +11:00
'company_index' => $companyKey,
'company_key' => $companyData['data']['company']['company_key'],
2020-11-10 16:20:02 +01:00
'force' => $companyData['force'],
];
2020-11-11 18:26:33 +01:00
$files[$companyKey] = $companyData['file'];
2020-11-10 16:20:02 +01:00
}
2020-11-11 18:26:33 +01:00
$body = \Unirest\Request\Body::multipart(['companies' => json_encode($data)], $files);
2020-11-10 16:20:02 +01:00
$response = Request::post($this->getUrl(), $this->getHeaders(), $body);
if (in_array($response->code, [200])) {
$this->isSuccessful = true;
} else {
info($response->raw_body);
$this->isSuccessful = false;
$this->errors = [
'Oops, something went wrong. Migration can\'t be processed at the moment. Please checks the logs.',
];
}
return $this;
}
public function isSuccessful()
{
return $this->isSuccessful;
}
public function getErrors()
{
return $this->errors;
}
private function getHeaders()
{
2020-12-10 15:04:59 +01:00
$headers = [
'X-Requested-With' => 'XMLHttpRequest',
'X-Api-Token' => $this->token,
'Content-Type' => 'multipart/form-data',
];
2020-12-10 15:04:59 +01:00
if (session('MIGRATION_API_SECRET')) {
$headers['X-Api-Secret'] = session('MIGRATION_API_SECRET');
}
return $headers;
}
private function getUrl()
{
2020-11-10 16:20:02 +01:00
return "{$this->endpoint}/{$this->uri}";
}
2020-11-10 16:20:02 +01:00
public function deleteFile(string $path)
{
2020-11-10 16:20:02 +01:00
Storage::delete($path);
}
}