id = $id; $this->data = $data; $this->storage = Storage::disk('local'); $this->url = env('WEBHOOK_CORE_URL') . '/webhooks'; $this->secret = env('WEBHOOK_CORE_SECRET'); } /** * Execute the job. * * @return void */ public function handle() { try { $this->setupData(); $this->createDocx(); // Convert to original format, either PDF, ODT, etc. $this->sendResponse('success'); } catch (\Exception $exception) { \Illuminate\Support\Facades\Log::info('RecreateDocument@handle: ' . $exception->getMessage()); \Illuminate\Support\Facades\Log::info($exception->getTraceAsString()); $this->sendResponse('fail'); } } protected function setupData() { $text = $this->data['contents']['text']; $textMapper = []; foreach ($this->data['contents']['elements'] as $element) { $textMapper[$element['hash']] = substr( $text, $element['range_start'], $element['range_end'] - $element['range_start'] + 1 ); } $this->data['elements'] = $this->updateText($this->data['elements'], $textMapper); } protected function updateText($elements, $textMapper) { foreach ($elements as $index => $element) { if (array_key_exists('hash', $element)) { $elements[$index]['text'] = $textMapper[$element['hash']]; } if ( array_key_exists('text_object', $element) && array_key_exists('text', $element['text_object']) ) { $elements[$index]['text_object']['text'] = $textMapper[$element['text_object']['hash']]; } if (isset($elements[$index]['elements'])) { $elements[$index]['elements'] = $this->updateText($elements[$index]['elements'], $textMapper); } } return $elements; } protected function createDocx() { $path = 'contracts/' . $this->id . '-document.docx'; $writer = new DocxWriter($this->storage, $path); $writer->execute($this->data); } protected function sendResponse($status) { try { WebhookCall::create() ->url($this->url) ->payload(['data' => [ 'id' => $this->id, 'content' => '', 'file_result_type' => 'document-recreated', 'status' => $status, ]]) ->useSecret($this->secret) ->dispatch(); return true; } catch (\Exception $exception) { Log::error('RecreateDocument@sendDocument: ' . $exception->getMessage()); return false; } } }