| 1 | <?php |
||
| 13 | |||
| 14 | class ImportController extends AbstractController |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * @var SaverInterface |
||
| 18 | */ |
||
| 19 | private $saver; |
||
| 20 | |||
| 21 | /** @var string */ |
||
| 22 | private $token; |
||
| 23 | |||
| 24 | public function __construct(App $app, SaverInterface $saver, $token) |
||
| 25 | { |
||
| 26 | parent::__construct($app); |
||
| 27 | $this->saver = $saver; |
||
| 28 | $this->token = $token; |
||
| 29 | } |
||
| 30 | |||
| 31 | public function import(Request $request, Response $response) |
||
| 32 | { |
||
| 33 | try { |
||
| 34 | $id = $this->runImport($request); |
||
| 35 | $result = ['ok' => true, 'id' => $id, 'size' => $request->getContentLength()]; |
||
| 36 | } catch (InvalidArgumentException $e) { |
||
| 37 | $result = ['error' => true, 'message' => $e->getMessage()]; |
||
| 38 | $response->setStatus(401); |
||
| 39 | } catch (Exception $e) { |
||
| 40 | $result = ['error' => true, 'message' => $e->getMessage()]; |
||
| 41 | $response->setStatus(500); |
||
| 42 | } |
||
| 43 | |||
| 44 | $response['Content-Type'] = 'application/json'; |
||
| 45 | $response->body(json_encode($result)); |
||
| 46 | } |
||
| 47 | |||
| 48 | private function runImport(Request $request): string |
||
| 49 | { |
||
| 50 | if ($this->token) { |
||
| 51 | if ($this->token !== $request->get('token')) { |
||
| 52 | throw new InvalidArgumentException('Token validation failed'); |
||
| 53 | } |
||
| 54 | } |
||
| 55 | |||
| 56 | $data = json_decode($request->getBody(), true); |
||
| 57 | |||
| 58 | return $this->saver->save($data); |
||
| 59 | } |
||
| 60 | } |
||
| 61 |