/**
  * Returns all documents for the topic
  * @param $topic_id
  * @return array
  */
 private function getDocuments($topic_id)
 {
     $document_mapper = new DocumentDBMapper();
     $documents = $document_mapper->getDocumentsByTopicId($topic_id);
     $documents_array = array();
     // Sets profiles, links, fields and target groups for each document
     foreach ($documents as $document) {
         $document->setTargetGroups(DocumentController::getTargetGroups($document));
         $document->setLinks(DocumentController::getLinks($document));
         $document->setFields(DocumentController::getFields($document));
         $document_array = $document->toArray();
         array_push($documents_array, $document_array);
     }
     // Sort document list on sequence
     usort($documents_array, function ($a, $b) {
         return $a['sequence'] - $b['sequence'];
     });
     return $documents_array;
 }
 /**
  * Updates document with related links, target groups and links, by adding new document
  * @return Response
  */
 protected function update()
 {
     $response = null;
     $document_mapper = new DocumentDBMapper();
     $document = Document::fromJSON($this->body);
     // Check that internal id is set
     if ($document->getInternalId() === null) {
         return new ErrorResponse(new InvalidJSONError('Internal id cannot be null.'));
     }
     $original_document = $document_mapper->getById($this->id);
     // If internal id differs from previous version, check check if the new internal id is unique
     if ($document->getInternalId() != $original_document->getInternalId()) {
         if (!$document_mapper->isValidInternalId($document->getInternalId())) {
             return new ErrorResponse(new InvalidJSONError('Internal id is not unique.'));
         }
     }
     // If HIS number differs from previous version, check check if the new HS number is unique
     if ($document->getHisNumber() != $original_document->getHisNumber()) {
         if (!$document_mapper->isValidHisNumber($document->getHisNumber())) {
             return new ErrorResponse(new InvalidJSONError('HIS number is not unique.'));
         }
     }
     // If previous document id  differs from previous version, check check if the new previous document id is unique
     if ($document->getPrevDocumentId() != $original_document->getPrevDocumentId()) {
         if (!$document_mapper->isPreviousDocumentId($document->getPrevDocumentId())) {
             return new ErrorResponse(new InvalidJSONError('Previous document id is not unique.'));
         }
     }
     $document->setId($this->id);
     $result = $document_mapper->update($document);
     if (!$result instanceof DBError) {
         return $this->getById($result);
     } else {
         $response = $result->toJSON();
     }
     return new Response($response);
 }