generate serializer part of a resource

@param array  $parameters twig parameters
@param string $dir        base bundle dir
@param string $document   document name

@return void
975471
protected function generateSerializer(array $parameters, $dir, $document)
    {
        // @TODO in Embedded and document just render the differences..
        $this->renderFile(
            'serializer/Document.xml.twig',
            $dir . '/Resources/config/serializer/Document.' . $document . 'Embedded.xml',
            array_merge(
                $parameters,
                [
                    'document' => $document.'Embedded',
                    'noIdField' => true,
                    'realIdField' => true
                ]
            )
        );

        foreach ($parameters['fields'] as $key => $field) {
            if (substr($field['serializerType'], 0, 14) == 'array<Graviton' &&
                strpos($field['serializerType'], '\\Entity') === false &&
                $field['relType'] == 'embed'
            ) {
                $parameters['fields'][$key]['serializerType'] = substr($field['serializerType'], 0, -1).'Embedded>';
            } elseif (substr($field['serializerType'], 0, 8) == 'Graviton' &&
                strpos($field['serializerType'], '\\Entity') === false &&
                $field['relType'] == 'embed'
            ) {
                $parameters['fields'][$key]['serializerType'] = $field['serializerType'].'Embedded';
            }
        }
        $this->renderFile(
            'serializer/Document.xml.twig',
            $dir . '/Resources/config/serializer/Document.' . $document . '.xml',
            array_merge(
                $parameters,
                [
                    'realIdField' => false
                ]
            )
        );
        $this->renderFile(
            'serializer/Document.xml.twig',
            $dir . '/Resources/config/serializer/Document.' . $document . 'Base.xml',
            array_merge(
                $parameters,
                [
                    'document' => $document.'Base',
                    'realIdField' => false
                ]
            )
        );
    }
39186
public function generate($namespace, $bundle, $dir)
    {
        $dir .= '/' . strtr($namespace, '\\', '/');
        if (file_exists($dir)) {
            throw new \RuntimeException(sprintf('Unable to generate the bundle as the target directory "%s" is not empty.', realpath($dir)));
        }

        $basename = substr($bundle, 0, -6);
        $parameters = array(
            'namespace' => $namespace,
            'bundle' => $bundle,
            'bundle_basename' => $basename,
            'extension_alias' => Container::underscore($basename),
        );

        $this->renderFile('/bundle/Bundle.php', $dir . '/' . $bundle . '.php', $parameters);
        $this->renderFile('/bundle/Extension.php', $dir . '/DependencyInjection/' . $basename . 'Extension.php', $parameters);
        $this->renderFile('/bundle/Configuration.php', $dir . '/DependencyInjection/Configuration.php', $parameters);
        $this->renderFile('/bundle/DefaultController.php', $dir . '/Controller/DefaultController.php', $parameters);
        $this->renderFile('/bundle/index.html.twig', $dir . '/Resources/views/Default/index.html.twig', $parameters);

        $this->renderFile('/bundle/services.yml', $dir . '/Resources/config/services.yml', $parameters);
        $this->renderFile('/bundle/routing.yml', $dir . '/Resources/config/routing.yml', $parameters);
    }
34371
private function persistDocument($data, $document, $locale, $articleUuid)
    {
        if (array_key_exists('title', $data)) {
            throw new ParameterNotAllowedException('title', get_class($document));
        }

        $article = $this->getDocumentManager()->find($articleUuid, $locale);

        if (!array_key_exists('template', $data)) {
            $data['template'] = $article->getStructureType();
        }

        $formType = $this->getMetadataFactory()->getMetadataForAlias('article_page')->getFormType();

        $form = $this->createForm(
            $formType,
            $document,
            [
                // disable csrf protection, since we can't produce a token, because the form is cached on the client
                'csrf_protection' => false,
            ]
        );
        $form->submit($data, false);

        $document->setParent($article);

        if (!$form->isValid()) {
            throw new InvalidFormException($form);
        }

        $this->getDocumentManager()->persist(
            $document,
            $locale,
            [
                'user' => $this->getUser()->getId(),
                'clear_missing_content' => false,
                'auto_name' => false,
                'auto_rename' => false,
            ]
        );
    }
1257623
public function mCreateDocument($documents, array $options = [])
    {
        if (!is_array($documents)) {
            throw new InvalidArgumentException('Collection.mCreateDocument: documents parameter format is invalid (should be an array of documents)');
        }

        $documents = array_map(function ($document) {
            return $document instanceof Document ? $document->serialize() : $document;
        }, $documents);

        $data = ['body' => ['documents' => $documents]];

        $response = $this->kuzzle->query(
            $this->buildQueryArgs('document', 'mCreate'),
            $this->kuzzle->addHeaders($data, $this->headers),
            $options
        );

        return $response['result'];
    }
1129273
public function generate(Resource $resource, array $data = array()) : void
    {
        $filepath  = $resource->getSrcFilename();
        $name      = $data['name'];
        $arguments = $data['arguments'];

        $argString = $this->argumentBuilder->buildFrom($arguments);

        $values = array('%name%' => $name, '%arguments%' => $argString);
        if (!$content = $this->templates->render('method', $values)) {
            $content = $this->templates->renderString(
                $this->getTemplate(), $values
            );
        }

        $code = $this->filesystem->getFileContents($filepath);
        $code = preg_replace('/}[ \n]*$/', rtrim($content) ."\n}\n", trim($code));
        $this->filesystem->putFileContents($filepath, $code);

        $this->io->writeln(sprintf(
                "\n<info>Method <value>%s::%s()</value> has been created.</info>",
                $resource->getSrcClassname(), $name
            ), 2);
    }
514130
protected function createImageSource(Document $document)
    {
        $src = $this->getAttribute('src');

        return is_string($src) ? $this->createSource($document) : $src;
    }
870071
private function makeDocumentFromCollection(
        ResourceManager $resourceManager,
        string $resource,
        $result,
        Parameters $parameters,
        ApiRequestHandler $handler
    )
    {
        $document = new Document();
        $serializer = $resourceManager->resolveSerializer($resource);
        if ($handler instanceof ModifiesSerializer) {
            $serializer = $handler->modify($serializer);
        }
        $collection = new Collection($result, $serializer);
        if ($handler instanceof HasElementIncludes) {
            $handler->includes($collection);
        }

        $this->assignAndResolveIncludes($resourceManager, $resource, $collection, $parameters);
        $document->setData($collection);

        if ($handler instanceof HasDocumentMeta) {
            $handler->meta($document);
        }

        if (config('json-api.response.resources.links.self', false)) {
            $document->addLink('self', apiRoute($resource, null, request()->route('version')));
        }

        return $document;
    }
386710
protected function getDocumentPath(array $parameters = []) {
        $dirOut = $this->getDirOutput();
        $dirOut = $dirOut.DIRECTORY_SEPARATOR.$this->getFileNameTranslate($parameters).'.'.$this->getFormat();
        return $dirOut;
    }
202614
public function generate(DocumentManager $dm, object $document)
    {
        $uuid = $this->generateV4();
        return $this->generateV5($uuid, $this->salt ?: php_uname('n'));
    }
1014988
protected function generateServices($parameters, $dir, $document)
    {
        $bundleParts = explode('\\', $parameters['base']);
        $shortName = $bundleParts[0];
        $shortBundle = $this->getBundleBaseName($bundleParts[1]);

        $docName = implode(
            '.',
            array(
                strtolower($shortName),
                strtolower($shortBundle),
                'document',
                strtolower($parameters['document'])
            )
        );

        $this->addParameter(
            $parameters['base'] . 'Document\\' . $parameters['document'],
            $docName . '.class'
        );

        $this->addService(
            $docName,
            null,
            [],
            null,
            [],
            null,
            null,
            '%'. $docName . '.class%'
        );

        $this->addParameter(
            (array) $parameters['json']->getRoles(),
            $docName . '.roles'
        );

        $repoName = implode(
            '.',
            array(
                strtolower($shortName),
                strtolower($shortBundle),
                'repository',
                strtolower($parameters['document'])
            )
        );

        $this->addService(
            $repoName,
            null,
            [],
            null,
            array(
                array(
                    'type' => 'string',
                    'value' => $parameters['bundle'] . ':' . $document
                )
            ),
            'doctrine_mongodb.odm.default_document_manager',
            'getRepository',
            'Doctrine\ODM\MongoDB\DocumentRepository'
        );

        $this->addService(
            $repoName . 'embedded',
            null,
            [],
            null,
            array(
                array(
                    'type' => 'string',
                    'value' => $parameters['bundle'] . ':' . $document . 'Embedded'
                )
            ),
            'doctrine_mongodb.odm.default_document_manager',
            'getRepository',
            'Doctrine\ODM\MongoDB\DocumentRepository'
        );
    }
1157044
public function generate($namespace, $bundle, $dir, $format)
    {
        $dir .= '/' . strtr($namespace, '\\', '/');

        // make sure we have no trailing \ in namespace
        if (substr($namespace, -1) == '\\') {
            $namespace = substr($namespace, 0, -1);
        }

        $basename = $this->getBundleBaseName($bundle);
        $parameters = array(
            'namespace' => $namespace,
            'bundle' => $bundle,
            'format' => $format,
            'bundle_basename' => $basename,
            'extension_alias' => Container::underscore($basename),
        );

        $this->renderFile('bundle/Bundle.php.twig', $dir . '/' . $bundle . '.php', $parameters);
        $this->renderFile(
            'bundle/Extension.php.twig',
            $dir . '/DependencyInjection/' . $basename . 'Extension.php',
            $parameters
        );

        $this->renderFile('bundle/config.xml.twig', $dir . '/Resources/config/config.xml', $parameters);

        if ('xml' === $format || 'annotation' === $format) {
            $this->renderFile('bundle/services.xml.twig', $dir . '/Resources/config/services.xml', $parameters);
        } else {
            $this->renderFile(
                'bundle/services.' . $format . '.twig',
                $dir . '/Resources/config/services.' . $format,
                $parameters
            );
        }

        if ('annotation' != $format) {
            $this->renderFile(
                'bundle/routing.' . $format . '.twig',
                $dir . '/Resources/config/routing.' . $format,
                $parameters
            );
        }
    }
393394
private function manageEditDocumentStoreProperties(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)
  {
    $params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
    $params->loadAccessRights = true;
    $params->loadDocuments = false;
    $category = $dmsLoader->loadCategory($manageCategory, $params);
    
    if (!$category->isEditableForCurrentMember())
    {
      $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];
      $blnShowStart = true;
    }
    else
    {
      $document = $dmsLoader->loadDocument($documentId, $params);
      $documentOriginal = clone $document;
      
      // load existing documents for file name
      $params->loadCategory = true; // need the category of existing documents
      $arrDocuments = $dmsLoader->loadDocuments($document->fileName, $document->fileType, $params);
      $params->loadCategory = false;
      
      $existingDocuments = array();
      foreach ($arrDocuments as $existingDocument)
      {
        if ($existingDocument->id != $documentId)
        {
          $existingDocuments[] = $existingDocument;
        }
      }
      
      $documentVersionMajor = $this->Input->post('documentVersionMajor');
      $documentVersionMinor = $this->Input->post('documentVersionMinor');
      $documentVersionPatch = $this->Input->post('documentVersionPatch');
      
      $document->name = $this->Input->post('documentName');
      $document->description = $this->Input->post('documentDescription');
      $document->keywords = $this->Input->post('documentKeywords');
      $document->versionMajor = $documentVersionMajor;
      $document->versionMinor = $documentVersionMinor;
      $document->versionPatch = $documentVersionPatch;
      $document->lasteditMemberId = $this->Member->id;
      $document->lasteditDate = time();
      if ($category->isPublishableForCurrentMember())
      {
        $document->published = (bool) $this->Input->post('documentPublish');
      }
      
      $versionChanged = false;
      if ($documentVersionMajor != $documentOriginal->versionMajor ||
        $documentVersionMinor != $documentOriginal->versionMinor ||
        $documentVersionPatch != $documentOriginal->versionPatch)
      {
        $versionChanged = true;
      }
      
      if (strlen($document->name) == 0)
      {
        $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_no_name_set'];
        $document->name = $documentOriginal->name;
      }
      if ($versionChanged)
      {
        if (strlen($documentVersionMajor) == 0 || !is_numeric($documentVersionMajor) ||
          strlen($documentVersionMinor) == 0 || !is_numeric($documentVersionMinor) ||
          strlen($documentVersionPatch) == 0 || !is_numeric($documentVersionPatch))
        {
          $document->versionMajor = $documentOriginal->versionMajor;
          $document->versionMinor = $documentOriginal->versionMinor;
          $document->versionPatch = $documentOriginal->versionPatch;
          $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_no_version_set'];
        }
        
        foreach ($existingDocuments as $existingDocument)
        {
          // will be true, if one is true (keep true status, if once set)
          if ($existingDocument->versionMajor == $documentVersionMajor &&
            $existingDocument->versionMinor == $documentVersionMinor &&
            $existingDocument->versionPatch == $documentVersionPatch)
          {
            $document->versionMajor = $documentOriginal->versionMajor;
            $document->versionMinor = $documentOriginal->versionMinor;
            $document->versionPatch = $documentOriginal->versionPatch;
            $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_version_already_used'];
          }
        }
      }
      
      // HOOK: verify the edited document from frontend
      if (isset($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument']))
      {
        foreach ($GLOBALS['TL_HOOKS']['dmsVerifyEditedDocument'] as $callback)
        {
          $this->import($callback[0]);
          $arrMessages = $this->{$callback[0]}->{$callback[1]}($arrMessages, $existingDocuments, $this->Input);
        }
      }
      
      if (count($arrMessages['errors']) > 0)
      {
        $this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_edit");
        $this->Template->setData($this->arrData);
      }
      else
      {
        // HOOK: modify the edited document from frontend
        if (isset($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument']))
        {
          foreach ($GLOBALS['TL_HOOKS']['dmsModifyEditedDocument'] as $callback)
          {
            $this->import($callback[0]);
            $document = $this->{$callback[0]}->{$callback[1]}($document, $this->Input);
          }
        }

        // update document
        $dmsWriter = \DmsWriter::getInstance();
        $document = $dmsWriter->updateDocument($document);
        
        $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_edited'];
        
        // rename the file if the version changed
        if ($versionChanged)
        {
          $filePath = \DmsConfig::getDocumentFilePath($documentOriginal->getFileNameVersioned());
          if (file_exists(TL_ROOT . '/' . $filePath))
          {
            rename($filePath, \DmsConfig::getDocumentFilePath($document->getFileNameVersioned()));
            $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_file_successfully_renamed'];
          }
          else
          {
            $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['edit_file_not_exists'];
          }
        }
        
        $this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_edit_processed");
        $this->Template->setData($this->arrData);
      }
      
      $this->Template->category = $category;
      $this->Template->document = $document;
      $this->Template->existingDocuments = $existingDocuments;
      
      $blnShowStart = false;
    }
  }
595265
public function generate($document, ClassMetadata $class, DocumentManagerInterface $dm, $parent = null)
    {
        if (null === $parent) {
            $parent = $class->parentMapping ? $class->getFieldValue($document, $class->parentMapping) : null;
        }
        $repository = $dm->getRepository($class->name);
        if (!($repository instanceof RepositoryIdInterface)) {
            throw new IdException("ID could not be determined. Make sure the that the Repository '".ClassUtils::getClass($repository)."' implements RepositoryIdInterface");
        }

        $id = $repository->generateId($document, $parent);
        if (!$id) {
            throw new IdException('ID could not be determined. Repository was unable to generate an ID');
        }

        return $id;
    }
1163126
protected function addToDocument($document)
    {
        parent::addToDocument($document);

        $this->getRangeKey()->getPropertyMetadata()->setValue(
            $document,
            $this->getRangeValue()
        );
    }
1303343
public function addDocument($doc, $id = null)
    {
        $action = array(
            self::BULK_ACTION => array(
                '_id' => $id,
                '_index' => $this->index,
                '_type' => $this->type
            )
        );

        $this->body .= json_encode($action) . self::LINE_BREAK;
        $this->body .= $this->serializer->serialize($doc, $this->serializerParams) . self::LINE_BREAK;
    }
51509
public function documentDelete($parameters = array(), $fetch = self::FETCH_OBJECT)
    {
        $queryParam = new QueryParam();
        $queryParam->setRequired('documentIds');
        $qr = [];
        $stack = [];
        $parametersStack = [];
        foreach ($parameters['documentIds'] as $documentId) {
            $qr[] = "documentIds=$documentId";
            $parametersStack[] = $documentId;
            if (strlen(implode("&", $qr)) > 995) {
                $last = array_pop($qr);
                $qr = [$last];
                $lastParam = array_pop($parametersStack);
                $stack[] = $parametersStack;
                $parametersStack = [$lastParam];
            }
        }

        $stack[] = $parametersStack;
        $responses = [];
        $response = null;
        foreach ($stack as $params) {
            $response = parent::documentDelete(['documentIds' => $params], $fetch);
            if (self::FETCH_PROMISE === $fetch) {
                $responses[] = $response;
            }
            if ($response->getStatusCode() != 204) {
                return $response;
            }
        }
        if (self::FETCH_PROMISE === $fetch) {
            return $responses;
        }
        return $response;
    }
829488
protected function generateIndexView(string $dir): void
    {
        $this->renderFile('crud/views/index.html.twig.twig', $dir.'/index.html.twig', [
            'bundle'            => $this->bundle->getName(),
            'entity'            => $this->entity,
            'fields'            => $this->metadata->fieldMappings,
            'actions'           => $this->actions,
            'record_actions'    => $this->getRecordActions(),
            'route_prefix'      => $this->routePrefix,
            'route_name_prefix' => $this->routeNamePrefix,
        ]);
    }