deserialize() final public method

final public deserialize ( $data, $type, $format )
Ejemplo n.º 1
0
 public function deserialize($data, $type, $format, array $context = array())
 {
     if (!$type) {
         $temp = $this->serializer->decode($data, $format, $context);
         $type = isset($this->map[$temp['type']]) ? $this->map[$temp['type']] : 'Bangpound\\oEmbed\\Response\\Response';
     }
     return $this->serializer->deserialize($data, $type, $format, $context);
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln("CONECTANDO A WEBSERVICE VIA SOAP");
     try {
         $normalizer = new GetSetMethodNormalizer();
         $encoder = new JsonEncoder();
         $serializer = new Serializer(array($normalizer), array($encoder));
         //retrieve WSDL
         $this->client = new \nusoap_client("http://crm.cam-la.com/service/v4/soap.php?wsdl", 'true');
         $this->executeLogin($input, $output);
         //Obtengo todos los archivos que hay en la carpeta:
         $path = $this->getApplication()->getKernel()->getContainer()->get('kernel')->getRootDir() . '/Resources/data/';
         $files = scandir($path);
         foreach ($files as $file) {
             if (is_readable($path . $file) == false) {
                 continue;
             }
             if (is_file($path . $file) == false) {
                 continue;
             }
             $output->writeln("EJECUTANDO DATA " . $file);
             $content = file_get_contents($path . $file);
             $data = json_decode(json_encode($content), true);
             $obj = $serializer->deserialize($data, 'BcTic\\Bundle\\AtencionCrmCamBundle\\Entity\\CustomerCase', 'json');
             $this->uploadToDataBase($obj, $input, $output);
             //Ahora debo eliminar el archivo, pues con otro comando los obtengo y los voy actualizando para consulta cada 5 minutos.
             unlink($path . $file);
         }
     } catch (Exception $e) {
         $output->writeln("ERROR: " . $e->getMessage());
     }
     $output->writeln("EJECUCION FINALIZADA. Good Bye!");
 }
Ejemplo n.º 3
0
 /**
  * @param $json
  * @return Connection
  */
 private function mapJsonToConnection($json)
 {
     /* @var ConnectionDto $dto */
     $dto = $this->serializer->deserialize($json, ConnectionDto::CLASS_NAME, 'json');
     $connection = $this->assembler->assemble($dto);
     return $connection;
 }
Ejemplo n.º 4
0
 /**
  * Deserializes a Json into readable datas
  * @param string $string
  *
  * @return RZ\Roadiz\Core\Entities\Group
  */
 public function deserialize($string)
 {
     if ($string == "") {
         throw new \Exception('File is empty.');
     }
     $encoder = new JsonEncoder();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter(['name']);
     $normalizer = new GetSetMethodNormalizer(null, $nameConverter);
     $serializer = new Serializer([$normalizer], [$encoder]);
     $group = $serializer->deserialize($string, 'RZ\\Roadiz\\Core\\Entities\\Group', 'json');
     /*
      * Importing Roles.
      *
      * We need to extract roles from group and to re-encode them
      * to pass to RoleJsonSerializer.
      */
     $tempArray = json_decode($string, true);
     $data = [];
     if (!empty($tempArray['roles'])) {
         foreach ($tempArray['roles'] as $roleAssoc) {
             $role = $this->roleSerializer->deserialize(json_encode($roleAssoc));
             $role = $this->em->getRepository('RZ\\Roadiz\\Core\\Entities\\Role')->findOneByName($role->getName());
             $group->addRole($role);
         }
         $data[] = $group;
     }
     return $data;
 }
 /**
  * Deserializes a json file into a readable array of datas.
  *
  * @param string $jsonString
  *
  * @return RZ\Roadiz\Core\Entities\NodeTypeField
  */
 public static function deserialize($jsonString)
 {
     $encoder = new JsonEncoder();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter(['name', 'label', 'description', 'visible', 'type', 'indexed', 'virtual', 'default_values']);
     $normalizer = new GetSetMethodNormalizer(null, $nameConverter);
     $serializer = new Serializer([$normalizer], [$encoder]);
     return $serializer->deserialize($jsonString, 'RZ\\Roadiz\\Core\\Entities\\NodeTypeField', 'json');
 }
Ejemplo n.º 6
0
 private function deserialize($json, $entityName)
 {
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $object = $serializer->deserialize($json, $entityName, 'json');
     return $object;
 }
 /**
  * Sends the passed Request and returns the response or a hydrated object.
  *
  * @param RequestInterface $request The Request to send.
  * @param string $entityClass Optional entity class to hydrate.
  * @return mixed The response or a hydrated object.
  */
 protected function send(RequestInterface $request, $entityClass = null)
 {
     $response = $this->client->send($request);
     $retVal = $response->getBody();
     if ($entityClass !== null) {
         $retVal = $this->serializer->deserialize($retVal, $entityClass, 'json');
     }
     return $retVal;
 }
 public function getAction()
 {
     $normalizer = new ObjectNormalizer(new ClassMetadataFactory(new YamlFileLoader(CONFIG_PATH . 'test_entity.yml')), new CamelCaseToSnakeCaseNameConverter());
     $serializer = new Serializer([$normalizer], [new JsonEncoder(), new XmlEncoder()]);
     $test = new TestEntity();
     $test->setMessage('Test');
     $test = $serializer->deserialize('<test><id>1</id></test>', 'DG\\SymfonyCert\\Entity\\TestEntity', 'xml', ['object_to_populate' => $test]);
     return new Response($serializer->serialize($test, 'xml', ['groups' => ['group2']]), 200, ['Content-Type' => 'text/xml']);
 }
 /**
  * @override \ComponentRegistry\PackageRepository\PackageRepository
  */
 public function synchronise($task)
 {
     $client = new Client();
     // TODO: this is really shit
     $data = $client->get(static::PLUGIN_LIST_URL)->getBody()->getContents();
     // TODO: this is even shitter
     $data = preg_replace(['/^{"timestamp":[0-9]+,"plugins":/', '/}$/'], '', $data);
     $serialiser = new Serializer([new ArrayDenormalizer(), new GetSetMethodNormalizer(), new ObjectNormalizer()], [new JsonEncoder()]);
     $components = $serialiser->deserialize($data, 'ComponentRegistry\\Entity\\Component[]', 'json');
 }
Ejemplo n.º 10
0
 /**
  * Deserializes a json file into a readable array of datas.
  *
  * @param string $jsonString
  *
  * @return RZ\Roadiz\Core\Entities\Role
  */
 public function deserialize($jsonString)
 {
     if ($jsonString == "") {
         throw new \Exception('File is empty.');
     }
     $encoder = new JsonEncoder();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter(['name']);
     $normalizer = new GetSetMethodNormalizer(null, $nameConverter);
     $serializer = new Serializer([$normalizer], [$encoder]);
     return $serializer->deserialize($jsonString, 'RZ\\Roadiz\\Core\\Entities\\Role', 'json');
 }
Ejemplo n.º 11
0
 /**
  * @param HttpRequest $httpRequest
  * @param Serializer  $serializer
  * @param array       $context
  *
  * @return Request
  */
 public static function factory(HttpRequest $httpRequest, Serializer $serializer, array $context = [])
 {
     $attributes = $httpRequest->attributes;
     $content = $httpRequest->getContent();
     $method = $attributes->get('method');
     $params = $serializer->deserialize($content, ParamsDenormalizer::TYPE, 'rest', $context);
     $id = $attributes->get('id');
     $request = new static();
     $request->setMethod($method);
     $request->setParams($params);
     $request->setId($id);
 }
Ejemplo n.º 12
0
 /**
  * @param $response
  * @return Host
  */
 private function mapJsonToHost($json)
 {
     /** @var Host $host */
     $host = $this->serializer->deserialize($json, Host::CLASS_NAME, 'json');
     if (empty($host->endpoints)) {
         $host->endpoints = array();
         return $host;
     }
     $endpointDtos = array();
     foreach ($host->endpoints as $endpoint) {
         $endpointDto = new Endpoint();
         foreach ($endpoint as $key => $value) {
             $endpointDto->{$key} = $value;
         }
         $endpointDtos[] = $endpointDto;
     }
     $host->endpoints = $endpointDtos;
     return $host;
 }
 /**
  * @param $json
  * @return array
  */
 private function mapJsonToConnectionDescriptors($json)
 {
     $decoded_connections = json_decode($json, true);
     if (!$decoded_connections) {
         $this->logger->error('Mapping received invalid JSON', array('json' => $json));
         throw new \RuntimeException('Mapping received invalid JSON');
     }
     if (!is_array($decoded_connections['connections'])) {
         $this->logger->error('JSON does not contain connection', array('json' => $json));
         throw new RuntimeException('Connections is not an array!');
     }
     $connections = array();
     foreach ($decoded_connections['connections'] as $decoded_connection) {
         /* @var ConnectionDto $dto */
         $dto = $this->serializer->deserialize(json_encode($decoded_connection), ConnectionDescriptorDto::CLASS_NAME, 'json');
         $connections[] = $this->assembler->assemble($dto);
     }
     return $connections;
 }
Ejemplo n.º 14
0
 /**
  * Deserializes a Json into readable datas.
  *
  * @param string $string
  *
  * @return RZ\Roadiz\Core\Entities\NodeType
  */
 public static function deserialize($string)
 {
     $encoder = new JsonEncoder();
     $nameConverter = new CamelCaseToSnakeCaseNameConverter(['name', 'displayName', 'display_name', 'description', 'visible', 'newsletterType', 'hidingNodes']);
     $normalizer = new GetSetMethodNormalizer(null, $nameConverter);
     $serializer = new Serializer([$normalizer], [$encoder]);
     $nodeType = $serializer->deserialize($string, 'RZ\\Roadiz\\Core\\Entities\\NodeType', 'json');
     /*
      * Importing Fields.
      *
      * We need to extract fields from node-type and to re-encode them
      * to pass to NodeTypeFieldJsonSerializer.
      */
     $tempArray = json_decode($string, true);
     foreach ($tempArray['fields'] as $fieldAssoc) {
         $ntField = NodeTypeFieldJsonSerializer::deserialize(json_encode($fieldAssoc));
         $nodeType->addField($ntField);
     }
     return $nodeType;
 }
Ejemplo n.º 15
0
 public function __construct($ezpage, $container, $blockMapper)
 {
     $this->xml = $ezpage['data_text'];
     $this->blockMapper = $blockMapper;
     $this->container = $container;
     $serializer = new Serializer([new ObjectNormalizer()], [new XmlEncoder()]);
     try {
         $page = new PageValue();
         if ($this->xml) {
             $page = $serializer->deserialize($this->xml, 'EzSystems\\EzFlowMigrationToolkit\\HelperObject\\PageValue', 'xml');
         }
     } catch (InvalidArgumentException $e) {
         // Not valid or empty page
         $page = new PageValue();
     }
     $this->layout = $page->zone_layout;
     if (is_array($page->zone)) {
         foreach ($page->zone as $legacyZone) {
             $zone = new Zone($legacyZone, $blockMapper);
             $this->zones[] = $zone;
         }
     }
 }
Ejemplo n.º 16
0
 /**
  * Executes the current command.
  *
  * This method is not abstract because you can use this class
  * as a concrete class. In this case, instead of defining the
  * execute() method, you set the code to execute by passing
  * a Closure to the setCode() method.
  *
  * @param InputInterface  $input  An InputInterface instance
  * @param OutputInterface $output An OutputInterface instance
  *
  * @return null|int     null or 0 if everything went fine, or an error code
  *
  * @throws \LogicException When this abstract method is not implemented
  * @see    setCode()
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $filename = $input->getOption('file');
     if (empty($filename)) {
         throw new \RuntimeException("File wurde nicht angegeben!");
     }
     // TODO: file_exists readable etc.
     $serializer = new Serializer(array(new GetSetMethodNormalizer()), array(new JsonEncoder()));
     $helptexts = json_decode(file_get_contents($filename));
     $em = $this->getContainer()->get('doctrine')->getManager();
     foreach ($helptexts as $helptext) {
         $newHelptext = $serializer->deserialize($helptext, 'WhereGroup\\MetadorBundle\\Entity\\Helptext', 'json');
         $existingHelptext = $this->getContainer()->get('doctrine')->getRepository('WhereGroupMetadorBundle:Helptext')->findById($newHelptext->getId());
         if ($existingHelptext) {
             $existingHelptext[0]->setText($newHelptext->getText());
             $em->persist($existingHelptext[0]);
         } else {
             $em->persist($newHelptext);
         }
     }
     $em->flush();
     $output->writeln('Import done.');
     return 0;
 }
Ejemplo n.º 17
0
 public function enregistrerlignesdevisAction()
 {
     $sortie = array("erreur" => true, "action" => "new", "type" => "devis", "typezone" => "onglet", "message" => "Le Lignes du Devis n'ont pas été enregistrées");
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new GetSetMethodNormalizer());
     //        $normalizers->setIgnoredAttributes(array('id'));
     $serializer = new Serializer($normalizers, $encoders);
     $request = $this->getRequest();
     $iddevis = $request->get("iddevis");
     $lignesdevis = $request->get("lignesdevis");
     $em = $this->getDoctrine()->getManager();
     $devis = $em->getRepository('AcmeProsalesBundle:Devis')->find($iddevis);
     if ($lignesdevis) {
         foreach (json_decode($lignesdevis) as $lignedevis) {
             $Lignedevis = new Lignesdevis();
             $Lignedevis = $serializer->deserialize(json_encode($lignedevis), 'Acme\\prosalesBundle\\Entity\\Lignesdevis', 'json');
             $Lignedevis->setDevis($devis);
             $em->persist($Lignedevis);
             $em->flush();
         }
         $sortie["erreur"] = false;
         $sortie["message"] = "Les Lignes du Devis ont été enregistrées avec succès";
         $sortie["idorg"] = $devis->getOrganisation()->getId();
         $sortie["iddevis"] = $iddevis;
         $sortie["idonglet"] = "new_devis_" . $devis->getOrganisation()->getId();
         $sortie["resultat"] = $devis->getArrayDevis();
     }
     $response = new JsonResponse();
     $response->setData($sortie);
     return $response;
 }
Ejemplo n.º 18
0
 /**
  * Initiate a new content type as a draft
  *
  * @param Request $request
  *        	@Route("/content-type/add", name="contenttype.add"))
  */
 public function addAction(Request $request)
 {
     /** @var EntityManager $em */
     $em = $this->getDoctrine()->getManager();
     /** @var EnvironmentRepository $environmetRepository */
     $environmetRepository = $em->getRepository('AppBundle:Environment');
     $environments = $environmetRepository->findBy(['managed' => true]);
     $contentTypeAdded = new ContentType();
     $form = $this->createFormBuilder($contentTypeAdded)->add('name', IconTextType::class, ['icon' => 'fa fa-gear', 'label' => "Machine name", 'required' => true])->add('singularName', TextType::class, [])->add('pluralName', TextType::class, [])->add('import', FileType::class, ['label' => 'Import From JSON', 'mapped' => false, 'required' => false])->add('environment', ChoiceType::class, ['label' => 'Default environment', 'choices' => $environments, 'choice_label' => function ($environment, $key, $index) {
         return $environment->getName();
     }])->add('save', SubmitType::class, ['label' => 'Create', 'attr' => ['class' => 'btn btn-primary pull-right']])->getForm();
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         /** @var ContentType $contentType */
         $contentTypeAdded = $form->getData();
         $contentTypeRepository = $em->getRepository('AppBundle:ContentType');
         $contentTypes = $contentTypeRepository->findBy(['name' => $contentTypeAdded->getName(), 'deleted' => false]);
         if (count($contentTypes) != 0) {
             $form->get('name')->addError(new FormError('Another content type named ' . $contentTypeAdded->getName() . ' already exists'));
         }
         if (!$this->isValidName($contentTypeAdded->getName())) {
             $form->get('name')->addError(new FormError('The content type name is malformed (format: [a-z][a-z0-9_-]*)'));
         }
         if ($form->isValid()) {
             $normData = $form->get("import")->getNormData();
             if ($normData) {
                 $name = $contentTypeAdded->getName();
                 $pluralName = $contentTypeAdded->getPluralName();
                 $environment = $contentTypeAdded->getEnvironment();
                 /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
                 $file = $request->files->get('form')['import'];
                 $fileContent = file_get_contents($file->getRealPath());
                 $encoders = array(new JsonEncoder());
                 $normalizers = array(new JsonNormalizer());
                 $serializer = new Serializer($normalizers, $encoders);
                 $contentType = $serializer->deserialize($fileContent, "AppBundle\\Entity\\ContentType", 'json');
                 $contentType->setName($name);
                 $contentType->setPluralName($pluralName);
                 $contentType->setEnvironment($environment);
                 $contentType->setActive(false);
                 $contentType->setDirty(true);
                 $contentType->getFieldType()->updateAncestorReferences($contentType, NULL);
                 $contentType->setOrderKey($contentTypeRepository->maxOrderKey() + 1);
                 $em->persist($contentType);
             } else {
                 $contentType = $contentTypeAdded;
                 $contentType->setAskForOuuid(false);
                 $contentType->setViewRole('ROLE_AUTHOR');
                 $contentType->setEditRole('ROLE_AUTHOR');
                 $contentType->setCreateRole('ROLE_AUTHOR');
                 $contentType->setOrderKey($contentTypeRepository->maxOrderKey() + 1);
                 $em->persist($contentType);
             }
             $em->flush();
             $this->addFlash('notice', 'A new content type ' . $contentTypeAdded->getName() . ' has been created');
             return $this->redirectToRoute('contenttype.edit', ['id' => $contentType->getId()]);
         } else {
             $this->addFlash('error', 'Invalid form.');
         }
     }
     return $this->render('contenttype/add.html.twig', ['form' => $form->createView()]);
 }
Ejemplo n.º 19
0
    /**
     * @Route("/search/{query}", defaults={"query"=null}, name="elasticsearch.search"))
     */
    public function searchAction($query, Request $request)
    {
        try {
            $search = new Search();
            //Save the form (uses POST method)
            if ($request->getMethod() == "POST") {
                // 				$request->query->get('search_form')['name'] = $request->request->get('form')['name'];
                $request->request->set('search_form', $request->query->get('search_form'));
                $form = $this->createForm(SearchFormType::class, $search);
                $form->handleRequest($request);
                /** @var Search $search */
                $search = $form->getData();
                $search->setName($request->request->get('form')['name']);
                $search->setUser($this->getUser()->getUsername());
                /** @var SearchFilter $filter */
                foreach ($search->getFilters() as $filter) {
                    $filter->setSearch($search);
                }
                $em = $this->getDoctrine()->getManager();
                $em->persist($search);
                $em->flush();
                return $this->redirectToRoute('elasticsearch.search', ['searchId' => $search->getId()]);
            }
            if (null != $request->query->get('page')) {
                $page = $request->query->get('page');
            } else {
                $page = 1;
            }
            //Use search from a saved form
            $searchId = $request->query->get('searchId');
            if (null != $searchId) {
                $em = $this->getDoctrine()->getManager();
                $repository = $em->getRepository('AppBundle:Form\\Search');
                $search = $repository->find($request->query->get('searchId'));
                if (!$search) {
                    $this->createNotFoundException('Preset search not found');
                }
            }
            $form = $this->createForm(SearchFormType::class, $search, ['method' => 'GET', 'savedSearch' => $searchId]);
            $form->handleRequest($request);
            $openSearchForm = $form->get('search')->isClicked();
            //Form treatement after the "Save" button has been pressed (= ask for a name to save the search preset)
            if ($form->isValid() && $request->query->get('search_form') && array_key_exists('save', $request->query->get('search_form'))) {
                $form = $this->createFormBuilder($search)->add('name', \Symfony\Component\Form\Extension\Core\Type\TextType::class)->add('save_search', SubmitEmsType::class, ['label' => 'Save', 'attr' => ['class' => 'btn btn-primary pull-right'], 'icon' => 'fa fa-save'])->getForm();
                return $this->render('elasticsearch/save-search.html.twig', ['form' => $form->createView()]);
            } else {
                if ($form->isValid() && $request->query->get('search_form') && array_key_exists('delete', $request->query->get('search_form'))) {
                    $this->addFlash('notice', 'Search has been deleted');
                }
            }
            //Next we want 1. see the results, or 2. export the results
            //So the common step is to fetch the results based on the search presets
            /** @var Search $search */
            if ($request->query->get('form') && array_key_exists('massExport', $request->query->get('form'))) {
                //In case of export we saved the search object in json form, time to recuperate it
                $jsonSearch = $request->query->get('form')['search-data'];
                $encoders = array(new JsonEncoder());
                $normalizers = array(new ObjectNormalizer());
                $serializer = new Serializer($normalizers, $encoders);
                $searchArray = json_decode($jsonSearch, true);
                $filtersArray = $searchArray['filters'];
                $searchArray['filters'] = null;
                $search = $serializer->deserialize(json_encode($searchArray), Search::class, 'json');
                foreach ($filtersArray as $rawFilter) {
                    $jsonFilter = json_encode($rawFilter);
                    $filter = $serializer->deserialize($jsonFilter, SearchFilter::class, 'json');
                    $search->addFilter($filter);
                }
            } else {
                $search = $form->getData();
            }
            $body = $this->getSearchService()->generateSearchBody($search);
            //
            /** @var EntityManager $em */
            $em = $this->getDoctrine()->getManager();
            /** @var ContentTypeRepository $contentTypeRepository */
            $contentTypeRepository = $em->getRepository('AppBundle:ContentType');
            $types = $contentTypeRepository->findAllAsAssociativeArray();
            /** @var EnvironmentRepository $environmentRepository */
            $environmentRepository = $em->getRepository('AppBundle:Environment');
            $environments = $environmentRepository->findAllAsAssociativeArray('alias');
            /** @var \Elasticsearch\Client $client */
            $client = $this->get('app.elasticsearch');
            $assocAliases = $client->indices()->getAliases();
            $mapAlias = [];
            $mapIndex = [];
            foreach ($assocAliases as $index => $aliasNames) {
                foreach ($aliasNames['aliases'] as $alias => $options) {
                    if (isset($environments[$alias])) {
                        $mapAlias[$environments[$alias]['alias']] = $environments[$alias];
                        $mapIndex[$index] = $environments[$alias];
                        break;
                    }
                }
            }
            $selectedEnvironments = [];
            if (!empty($search->getEnvironments())) {
                foreach ($search->getEnvironments() as $envName) {
                    $temp = $this->getEnvironmentService()->getAliasByName($envName);
                    if ($temp) {
                        $selectedEnvironments[] = $temp->getAlias();
                    }
                }
            }
            //1. Define the parameters for a regular search request
            $params = ['version' => true, 'index' => empty($selectedEnvironments) ? array_keys($environments) : $selectedEnvironments, 'type' => empty($search->getContentTypes()) ? array_keys($types) : array_values($search->getContentTypes()), 'size' => $this->container->getParameter('paging_size'), 'from' => ($page - 1) * $this->container->getParameter('paging_size')];
            //2. Override parameters because when exporting we need all results, not paged
            if ($request->query->get('form') && array_key_exists('massExport', $request->query->get('form'))) {
                //TODO: size 10000 is the default maximum size of an elasticsearch installation. In case of export it would be better to use the scroll API of elasticsearch in case of performance issues. Or when more then 10000 results are going to be exported.
                //TODO: consideration: will there be an export limit? Because for giant loads of data it might be better to call an API of the system that needs our exported data. Then again, they could simply connect to elasticsearch as a standalone application!
                $params['from'] = 0;
                $params['size'] = 10000;
            }
            // 			   "highlight": {
            // 			      "fields": {
            // 			         "_all": {}
            // 			      }
            // 			   },
            $body = array_merge($body, json_decode('{
			   "aggs": {
			      "types": {
			         "terms": {
			            "field": "_type",
						"size": 15
			         }
			      },
			      "indexes": {
			         "terms": {
			            "field": "_index",
						"size": 15
			         }
			      }
			   }
			}', true));
            $params['body'] = $body;
            try {
                $results = $client->search($params);
                $lastPage = ceil($results['hits']['total'] / $this->container->getParameter('paging_size'));
            } catch (ElasticsearchException $e) {
                $this->addFlash('warning', $e->getMessage());
                $lastPage = 0;
                $results = ['hits' => ['total' => 0]];
            }
            $currentFilters = $request->query;
            $currentFilters->remove('search_form[_token]');
            //Form treatement after the "Export results" button has been pressed (= ask for a "content type" <-> "template" mapping)
            if ($form->isValid() && $request->query->get('search_form') && array_key_exists('exportResults', $request->query->get('search_form'))) {
                //Store all the content types present in the current resultset
                $contentTypes = $this->getAllContentType($results);
                /**@var ContentTypeService $contenttypeService*/
                $contenttypeService = $this->get('ems.service.contenttype');
                /**@var EnvironmentService $environmentService*/
                $environmentService = $this->get('ems.service.environment');
                //Check for each content type that an export template is available.
                //If no export template is defined, ignore the content type.
                //If one or more export templates are defined, allow choice of the template to be dynamic
                $form = null;
                foreach ($contentTypes as $name) {
                    /** @var ContentType $contentType */
                    $contentType = $types[$name];
                    $templateChoices = ['JSON export' => 0];
                    /** @var Template $template */
                    foreach ($contentType->getTemplates() as $template) {
                        if (RenderOptionType::EXPORT == $template->getRenderOption() && $template->getBody()) {
                            $templateChoices[$template->getName()] = $template->getId();
                        }
                    }
                    if (!empty($templateChoices)) {
                        if (!$form) {
                            $encoders = array(new JsonEncoder());
                            $normalizers = array(new ObjectNormalizer());
                            $serializer = new Serializer($normalizers, $encoders);
                            $jsonSearch = $serializer->serialize($search, 'json');
                            $form = $this->createFormBuilder()->setMethod('GET')->add('search-data', HiddenType::class, array('data' => $jsonSearch));
                        }
                        $form->add($name, ChoiceType::class, array('label' => 'Export template for ' . $contenttypeService->getByName($name)->getPluralName(), 'choices' => $templateChoices));
                    }
                }
                if ($form) {
                    $form = $form->add('massExport', SubmitType::class)->getForm();
                    $form->handlerequest($request);
                    return $this->render('elasticsearch/export-search.html.twig', ['form' => $form->createView()]);
                } else {
                    return $this->render('elasticsearch/export-search.html.twig');
                }
            }
            //Form treatement after the "Mass export" button has been pressed (= download all the results with the given preset)
            if ($request->query->get('form') && array_key_exists('massExport', $request->query->get('form'))) {
                //TODO: ? CANNOT DO THE ISVALID CHECK HERE :(
                //Load the selected templates for each content type
                /** @var EntityManager $em */
                $em = $this->getDoctrine()->getManager();
                /** @var ContentTypeRepository $repository */
                $templateRepository = $em->getRepository('AppBundle:Template');
                $templateChoises = $request->query->get('form');
                $templateMapping = [];
                $templateBodyMapping = [];
                $twig = $this->getTwig();
                $errorList = [];
                foreach ($templateChoises as $contentName => $templateChoise) {
                    if ('search-data' != $contentName && 'massExport' != $contentName && '_token' != $contentName) {
                        $template = $templateRepository->find($templateChoise);
                        if ($template) {
                            $templateMapping[$contentName] = $template;
                            try {
                                //TODO why is the body generated and passed to the twig file while the twig file does not use it?
                                //Asked by dame
                                //If there is an error in the twig the user will get an 500 error page, this solution is not perfect but at least the template is tested
                                $body = $twig->createTemplate($template->getBody());
                            } catch (\Twig_Error $e) {
                                $this->addFlash('error', 'There is something wrong with the template ' . $template->getName());
                                $body = $twig->createTemplate('error in the template!');
                                $errorList[] = "Error in template->getBody() for: " . $template->getName();
                                continue;
                            }
                            $templateBodyMapping[$contentName] = $body;
                        } else {
                            //Default JSON export
                            $templateMapping[$contentName] = NULL;
                            $templateBodyMapping[$contentName] = NULL;
                        }
                    }
                }
                //Create the file for each result and accumulate in a zip stream
                $extime = ini_get('max_execution_time');
                ini_set('max_execution_time', 0);
                $fileTime = date("D, d M Y H:i:s T");
                $zip = new ZipStream("eMSExport.zip");
                $contentTypes = $this->getAllContentType($results);
                $resultsSize = count($results['hits']['hits']);
                $loop = [];
                $accumulatedContent = "";
                foreach ($results['hits']['hits'] as $result) {
                    if (array_key_exists('first', $loop)) {
                        $loop['first'] = false;
                    } else {
                        $loop['first'] = true;
                    }
                    if (array_key_exists('index0', $loop)) {
                        $loop['index0'] = $loop['index0'] + 1;
                    } else {
                        $loop['index0'] = 0;
                    }
                    if (array_key_exists('index1', $loop)) {
                        $loop['index1'] = $loop['index1'] + 1;
                    } else {
                        $loop['index1'] = 1;
                    }
                    $loop['last'] = $resultsSize == $loop['index1'];
                    $name = $result['_type'];
                    $template = $templateMapping[$name];
                    $body = $templateBodyMapping[$name];
                    if ($template) {
                        $filename = $result['_id'];
                        if (null != $template->getFilename()) {
                            try {
                                $filename = $twig->createTemplate($template->getFilename());
                            } catch (\Twig_Error $e) {
                                $this->addFlash('error', 'There is something wrong with the template filename field ' . $template->getName());
                                $filename = $result['_id'];
                                $errorList[] = "Error in template->getFilename() for: " . $filename;
                                continue;
                            }
                            $filename = $filename->render(['loop' => $loop, 'contentType' => $template->getContentType(), 'object' => $result, 'source' => $result['_source']]);
                            $filename = preg_replace('~[\\r\\n]+~', '', $filename);
                        }
                        if (null != $template->getExtension()) {
                            $filename = $filename . '.' . $template->getExtension();
                        }
                        try {
                            $content = $body->render(['loop' => $loop, 'contentType' => $template->getContentType(), 'object' => $result, 'source' => $result['_source']]);
                        } catch (\Twig_Error $e) {
                            $this->addFlash('error', 'There is something wrong with the template filename field ' . $template->getName());
                            $content = "There was an error rendering the content";
                            $errorList[] = "Error in templateBody->render() for: " . $filename;
                            continue;
                        }
                        if ($template->getAccumulateInOneFile()) {
                            $accumulatedContent = $accumulatedContent . $content;
                            if ($loop['last']) {
                                $zip->addFile($template->getName() . '.' . $template->getExtension(), $accumulatedContent);
                            }
                        } else {
                            $zip->addFile($filename, $content);
                        }
                    } else {
                        //JSON export
                        $zip->addFile($result['_type'] . ' ' . $result['_id'] . '.json', json_encode($result['_source']));
                    }
                }
                if (!empty($errorList)) {
                    $zip->addFile("All-Errors.txt", implode("\n", $errorList));
                }
                $zip->finish();
                exit;
            }
            return $this->render('elasticsearch/search.html.twig', ['results' => $results, 'lastPage' => $lastPage, 'paginationPath' => 'elasticsearch.search', 'types' => $types, 'alias' => $mapAlias, 'indexes' => $mapIndex, 'form' => $form->createView(), 'page' => $page, 'searchId' => $searchId, 'currentFilters' => $request->query, 'body' => $body, 'openSearchForm' => $openSearchForm, 'search' => $search]);
        } catch (\Elasticsearch\Common\Exceptions\NoNodesAvailableException $e) {
            return $this->redirectToRoute('elasticsearch.status');
        }
    }
Ejemplo n.º 20
0
 /**
  * @param string $bundleComposer
  *
  * @return bool|Bundle
  */
 private function getBundle($bundleComposer)
 {
     if (!file_exists($bundleComposer)) {
         return false;
     }
     $bundleComposerData = file_get_contents($bundleComposer);
     $normalizer = new GetSetMethodNormalizer();
     $normalizer->setIgnoredAttributes(array('require', 'keywords'));
     $encoder = new JsonEncoder();
     $serializer = new Serializer(array($normalizer), array($encoder));
     $bundle = $serializer->deserialize($bundleComposerData, 'CampaignChain\\CoreBundle\\Entity\\Bundle', 'json');
     // Set the version of the installed bundle.
     $version = $this->packageService->getVersion($bundle->getName());
     /*
      * If version does not exist, this means two things:
      *
      * 1) Either, it is a package in require-dev of composer.json, but
      * CampaignChain is not in dev mode. Then we don't add this package.
      *
      * 2) Or it is a bundle in Symfony's src/ directory. Then we want to
      * add it.
      */
     if (!$version) {
         // Check if bundle is in src/ dir.
         $bundlePath = str_replace($this->rootDir . DIRECTORY_SEPARATOR, '', $bundleComposer);
         if (strpos($bundlePath, 'src' . DIRECTORY_SEPARATOR) !== 0) {
             // Not in src/ dir, so don't add this bundle.
             return false;
         } else {
             $version = 'dev-master';
         }
     }
     $bundle->setVersion($version);
     // Set relative path of bundle.
     $bundle->setPath(str_replace($this->rootDir . DIRECTORY_SEPARATOR, '', str_replace(DIRECTORY_SEPARATOR . 'composer.json', '', $bundleComposer)));
     return $bundle;
 }
Ejemplo n.º 21
0
 /**
  * Edits an existing Groups entity.
  *
  */
 public function updateAction(Request $request, $id)
 {
     $content = null;
     $status = null;
     $encoders = array(new XmlEncoder(), new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     if (!$this->validJson(json_decode($request->getContent()))) {
         return new Response($serializer->serialize(array('result' => 'Error', 'message' => 'Invalid group data'), 'json'), Response::HTTP_BAD_REQUEST, array('content-type' => 'application/json'));
     }
     $group_data = $serializer->deserialize($request->getContent(), 'Miw\\PadelBundle\\Entity\\Groups', 'json');
     if ($group_data != null) {
         // valid JSON
         $em = $this->getDoctrine()->getManager();
         $group = $em->getRepository('MiwPadelBundle:Groups')->find($id);
         if (!$group) {
             $content = array('result' => 'NOT FOUND', 'group_id' => $id);
             $status = Response::HTTP_NOT_FOUND;
         } else {
             $group->setName($group_data->getName());
             $group->setRoles($group_data->getRoles());
             $em->flush();
             $content = $group;
             $status = Response::HTTP_OK;
         }
     }
     return new Response($serializer->serialize($content, 'json'), $status, array('content-type' => 'application/json'));
 }
 /**
  * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
  */
 public function testDeserializeNoEncoder()
 {
     $serializer = new Serializer(array(), array());
     $data = array('title' => 'foo', 'numbers' => array(5, 3));
     $serializer->deserialize(json_encode($data), '\\Symfony\\Component\\Serializer\\Tests\\Model', 'json');
 }
Ejemplo n.º 23
0
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $session = $this->get('phpcr.session');
        $path = $input->getArgument('path');
        if (UUIDHelper::isUUID($path)) {
            // If the node is a UUID, then just get it
            $node = $session->getNodeByIdentifier($path);
        } else {
            $path = $session->getAbsPath($path);
            // Otherwise it is a path which may or may not exist
            $parentPath = $this->get('helper.path')->getParentPath($path);
            $nodeName = $this->get('helper.path')->getNodeName($path);
            $type = $input->getOption('type');
            try {
                // if it exists, then great
                $node = $session->getNodeByPathOrIdentifier($path);
            } catch (PathNotFoundException $e) {
                // if it doesn't exist then we create it
                $parentNode = $session->getNode($parentPath);
                $node = $parentNode->addNode($nodeName, $type);
            }
        }
        $editor = $this->get('helper.editor');
        $dialog = $this->get('helper.question');
        $skipBinary = true;
        $noRecurse = true;
        // for now we only support YAML
        $encoders = [new YamlEncoder()];
        $nodeNormalizer = new NodeNormalizer();
        $serializer = new Serializer([$nodeNormalizer], $encoders);
        $outStr = $serializer->serialize($node, 'yaml');
        $tryAgain = false;
        $message = '';
        $error = '';
        $notes = implode("\n", $nodeNormalizer->getNotes());
        do {
            $message = '';
            if ($error) {
                $template = <<<'EOT'
Error encounred:
%s

EOT;
                $message .= sprintf($template, $error);
            }
            if ($notes) {
                $template = <<<'EOT'
NOTE:
%s

EOT;
                $message .= sprintf($template, $notes);
            }
            // string pass to editor
            if ($message) {
                $inStr = $editor->fromStringWithMessage($outStr, $message, '# ', 'yml');
            } else {
                $inStr = $editor->fromString($outStr, 'yml');
            }
            try {
                $norm = $serializer->deserialize($inStr, 'PHPCR\\NodeInterface', 'yaml', ['node' => $node]);
                $tryAgain = false;
            } catch (\Exception $e) {
                $error = $e->getMessage();
                $output->writeln('<error>' . $error . '</error>');
                if (false === $input->getOption('no-interaction')) {
                    $tryAgain = $dialog->ask($input, $output, new ConfirmationQuestion('Do you want to try again? (y/n)'));
                }
                $outStr = $inStr;
            }
        } while ($tryAgain == true);
        if ($error) {
            return 1;
        }
        return 0;
    }
 /**
  * @Route("/casos/search" ,name="case_search")
  * @Method("POST")
  * @Template("BcTicAtencionCrmCamBundle:Case:index.html.twig")
  */
 public function searchAction(Request $request)
 {
     $entity = new CustomerCaseSearch();
     $form = $this->createSearchForm($entity);
     $form->handleRequest($request);
     $file = $this->container->get('kernel')->getRootDir() . '/Resources/data/server/case-' . $entity->getTicket() . '-data.json';
     if ($form->isValid()) {
         try {
             if (!is_readable($file)) {
                 throw new \Exception("No fue posible encontrar un caso asociado a este número y el email indicado.");
             }
             //Persisto el objeto como Json
             $normalizer = new GetSetMethodNormalizer();
             //$normalizer->setIgnoredAttributes(array('age'));
             $encoder = new JsonEncoder();
             $serializer = new Serializer(array($normalizer), array($encoder));
             $content = file_get_contents($file);
             $data = json_decode(json_encode($content), true);
             $obj = $serializer->deserialize($data, 'BcTic\\Bundle\\AtencionCrmCamBundle\\Entity\\CustomerCase', 'json');
             if ($obj->getEmail() != $entity->getEmail()) {
                 throw new \Exception("No fue posible encontrar un caso asociado a este número y el email indicado.");
             }
             return $this->forward('BcTicAtencionCrmCamBundle:Case:show', array('ticket' => $entity->getTicket()));
         } catch (\Exception $e) {
             $this->get('session')->getFlashBag()->add('error', $e->getMessage());
             return array('entity' => $entity, 'form' => $form->createView());
         }
     }
     return array('entity' => $entity, 'form' => $form->createView());
 }
 private function getMessages($fileName, $numberOfLines)
 {
     $normalizer = new GetSetMethodNormalizer();
     $encoder = new JsonEncoder();
     $serializer = new Serializer(array($normalizer), array($encoder));
     $normalizer->setCamelizedAttributes(array('level_name'));
     $messages = [];
     $file = array_reverse(file($fileName));
     foreach ($file as $line) {
         $messages[] = $serializer->deserialize($line, 'Sopinet\\Bundle\\LogBundle\\Entities\\Message', 'json');
         if (count($messages) == $numberOfLines) {
             break;
         }
     }
     return $messages;
 }
Ejemplo n.º 26
0
 public function deserialize($data)
 {
     $class = null === $this->class ? 'Gos\\Bundle\\WebSocketBundle\\Pusher\\Message' : $this->class;
     return $this->serializer->deserialize($data, $class, 'json');
 }
Ejemplo n.º 27
0
 /**
  * @Route("/movies/search/add/{imdbID}", name="add_movie", defaults={"imdbID" = null})
  */
 public function addMovieAction($imdbID)
 {
     $encoders = array(new JsonEncoder());
     $normalizers = array(new ObjectNormalizer());
     $serializer = new Serializer($normalizers, $encoders);
     $repository = $this->getDoctrine()->getRepository('AppBundle:Movie');
     $product = $repository->findOneBy(array('imdbID' => $imdbID));
     if ($product) {
         $this->get('session')->getFlashBag()->add('info', "Movie already exists");
         return $this->redirectToRoute('search');
     }
     $response = $this->get("http")->JSONRequest('http://www.omdbapi.com/?i=' . $imdbID . '&plot=short&tomatoes=true&r=json');
     $movie = $serializer->deserialize(json_encode($response), 'AppBundle\\Entity\\Movie', 'json');
     $em = $this->getDoctrine()->getManager();
     $em->persist($movie);
     $em->flush();
     $this->get('session')->getFlashBag()->add('success', "Movie added successfully");
     return $this->redirectToRoute('search');
 }
Ejemplo n.º 28
0
 /**
  * {@inheritdoc}
  */
 public function importContent($module)
 {
     $created = array();
     $folder = drupal_get_path('module', $module) . "/content";
     if (file_exists($folder)) {
         $file_map = array();
         foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) {
             $reflection = new \ReflectionClass($entity_type->getClass());
             // We are only interested in importing content entities.
             if ($reflection->implementsInterface('\\Drupal\\Core\\Config\\Entity\\ConfigEntityInterface')) {
                 continue;
             }
             if (!file_exists($folder . '/' . $entity_type_id)) {
                 continue;
             }
             $files = $this->scanner()->scan($folder . '/' . $entity_type_id);
             // Default content uses drupal.org as domain.
             // @todo Make this use a uri like default-content:.
             $this->linkManager->setLinkDomain(static::LINK_DOMAIN);
             // Parse all of the files and sort them in order of dependency.
             foreach ($files as $file) {
                 $contents = $this->parseFile($file);
                 // Decode the file contents.
                 $decoded = $this->serializer->decode($contents, 'hal_json');
                 // Get the link to this entity.
                 $self = $decoded['_links']['self']['href'];
                 // Throw an exception when this URL already exists.
                 if (isset($file_map[$self])) {
                     $args = array('@href' => $self, '@first' => $file_map[$self]->uri, '@second' => $file->uri);
                     // Reset link domain.
                     $this->linkManager->setLinkDomain(FALSE);
                     throw new \Exception(SafeMarkup::format('Default content with href @href exists twice: @first @second', $args));
                 }
                 // Store the entity type with the file.
                 $file->entity_type_id = $entity_type_id;
                 // Store the file in the file map.
                 $file_map[$self] = $file;
                 // Create a vertex for the graph.
                 $vertex = $this->getVertex($self);
                 $this->graph[$vertex->link]['edges'] = [];
                 if (empty($decoded['_embedded'])) {
                     // No dependencies to resolve.
                     continue;
                 }
                 // Here we need to resolve our dependencies;
                 foreach ($decoded['_embedded'] as $embedded) {
                     foreach ($embedded as $item) {
                         $edge = $this->getVertex($item['_links']['self']['href']);
                         $this->graph[$vertex->link]['edges'][$edge->link] = TRUE;
                     }
                 }
             }
         }
         // @todo what if no dependencies?
         $sorted = $this->sortTree($this->graph);
         foreach ($sorted as $link => $details) {
             if (!empty($file_map[$link])) {
                 $file = $file_map[$link];
                 $entity_type_id = $file->entity_type_id;
                 $resource = $this->resourcePluginManager->getInstance(array('id' => 'entity:' . $entity_type_id));
                 $definition = $resource->getPluginDefinition();
                 $contents = $this->parseFile($file);
                 $class = $definition['serialization_class'];
                 $entity = $this->serializer->deserialize($contents, $class, 'hal_json', array('request_method' => 'POST'));
                 $entity->enforceIsNew(TRUE);
                 $entity->save();
                 $created[$entity->uuid()] = $entity;
             }
         }
         $this->eventDispatcher->dispatch(DefaultContentEvents::IMPORT, new ImportEvent($created, $module));
     }
     // Reset the tree.
     $this->resetTree();
     // Reset link domain.
     $this->linkManager->setLinkDomain(FALSE);
     return $created;
 }
Ejemplo n.º 29
0
 public function testDeserializeArray()
 {
     $jsonData = '[{"title":"foo","numbers":[5,3]},{"title":"bar","numbers":[2,8]}]';
     $expectedData = array(Model::fromArray(array('title' => 'foo', 'numbers' => array(5, 3))), Model::fromArray(array('title' => 'bar', 'numbers' => array(2, 8))));
     $serializer = new Serializer(array(new GetSetMethodNormalizer(), new ArrayDenormalizer()), array('json' => new JsonEncoder()));
     $this->assertEquals($expectedData, $serializer->deserialize($jsonData, __NAMESPACE__ . '\\Model[]', 'json'));
 }
Ejemplo n.º 30
0
 public function testDeserializeObjectConstructorWithObjectTypeHint()
 {
     $jsonData = '{"bar":{"value":"baz"}}';
     $serializer = new Serializer(array(new ObjectNormalizer()), array('json' => new JsonEncoder()));
     $this->assertEquals(new Foo(new Bar('baz')), $serializer->deserialize($jsonData, Foo::class, 'json'));
 }