invoiceninja/app/Services/Migration/CompleteService.php

107 lines
2.2 KiB
PHP
Raw Normal View History

<?php
namespace App\Services\Migration;
use Illuminate\Support\Facades\Storage;
use Unirest\Request;
use Unirest\Request\Body;
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
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()
{
$body = [
2020-11-10 16:20:02 +01:00
'companies' => [],
];
2020-11-10 16:20:02 +01:00
foreach ($this->data as $companyKey => $companyData) {
$body['companies'][] = [
'company_key' => $companyKey,
'migration' => \Unirest\Request\Body::file($companyData['file'], 'application/zip'),
'force' => $companyData['force'],
];
}
try {
$response = Request::post($this->getUrl(), $this->getHeaders(), json_encode($body));
dd($response);
} catch (\Exception $e) {
dd($e->getMessage());
}
if ($response->code == 200) {
$this->isSuccessful = true;
}
if (in_array($response->code, [401, 422, 500])) {
$this->isSuccessful = false;
$this->errors = [
'Oops, something went wrong. Migration can\'t be processed at the moment.',
];
}
return $this;
}
public function isSuccessful()
{
return $this->isSuccessful;
}
public function getErrors()
{
return $this->errors;
}
private function getHeaders()
{
return [
'X-Requested-With' => 'XMLHttpRequest',
'X-Api-Token' => $this->token,
'Content-Type' => 'multipart/form-data',
];
}
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);
}
}