/** * In an API context, converts any data to a XML response. * * @param GetResponseForControllerResultEvent $event * * @return Response|mixed */ public function onKernelView(GetResponseForControllerResultEvent $event) { $controllerResult = $event->getControllerResult(); if ($controllerResult instanceof Response) { return $controllerResult; } $request = $event->getRequest(); $format = $request->attributes->get('_api_format'); if (self::FORMAT !== $format) { return $controllerResult; } switch ($request->getMethod()) { case Request::METHOD_POST: $status = 201; break; case Request::METHOD_DELETE: $status = 204; break; default: $status = 200; break; } $resourceType = $request->attributes->get('_resource_type'); $response = new Response($this->serializer->serialize($controllerResult, self::FORMAT, $resourceType->getNormalizationContext()), $status, ['Content-Type' => 'application/xml']); $event->setResponse($response); }
/** * Processes entity to export format * * @param mixed $object * @return array * @throws RuntimeException */ public function process($object) { if (!$this->serializer) { throw new RuntimeException('Serializer must be injected.'); } $data = $this->serializer->serialize($object, null); if ($this->dataConverter) { $data = $this->dataConverter->convertToExportFormat($data); } return $data; }
/** * Confirms that modules can register normalizers and encoders. */ public function testSerializerComponentRegistration() { $object = new \stdClass(); $format = 'serialization_test'; $expected = 'Normalized by SerializationTestNormalizer, Encoded by SerializationTestEncoder'; // Ensure the serialization invokes the expected normalizer and encoder. $this->assertIdentical($this->serializer->serialize($object, $format), $expected); // Ensure the serialization fails for an unsupported format. try { $this->serializer->serialize($object, 'unsupported_format'); $this->fail('The serializer was expected to throw an exception for an unsupported format, but did not.'); } catch (UnexpectedValueException $e) { $this->pass('The serializer threw an exception for an unsupported format.'); } }
/** * Processing the API request. */ public function processRequest(Request $request, RouteMatchInterface $route_match, $service_endpoint_id, $service_definition_id) { /** @var $service_endpoint \Drupal\services\ServiceEndpointInterface */ $service_endpoint = $this->entityManager()->getStorage('service_endpoint')->load($service_endpoint_id); //TODO - pull in settings from service API and alter response /** @var $service_def \Drupal\services\ServiceDefinitionInterface */ $service_def = $this->serviceDefinitionManager->createInstance($service_definition_id, []); /** * Iterate over any contexts defined for this plugin and extract them from * the request defaults if the naming is identical. This means that a * context named 'node' would match to a url parameter {node} or a route * default named 'node'. */ foreach ($service_def->getContextDefinitions() as $context_id => $context_definition) { if ($request->attributes->has($context_id)) { $context = new Context($context_definition, $request->attributes->get($context_id)); $service_def->setContext($context_id, $context); } } // Get the data from the plugin. $data = $service_def->processRequest($request, $route_match, $this->serializer); $code = $service_def->getPluginDefinition()['response_code']; $headers = []; $messages = drupal_get_messages(); if ($messages) { foreach ($messages as $type => $type_message) { $headers["X-Drupal-Services-Messages-{$type}"] = implode("; ", $type_message); } } // Find the request format to determin how we're going to serialize this data $format = $request->getRequestFormat(); $data = $this->serializer->serialize($data, $format); /** * Create a new Cacheable Response object with our serialized data, set its * Content-Type to match the format of our Request and add the service * definition plugin as a cacheable dependency. * * This last step will extract the cache context, tags and max-ages from * any context the plugin required to operate. */ $response = new CacheableResponse($data, $code, $headers); $response->headers->add(['Content-Type' => $request->getMimeType($format)]); $response->addCacheableDependency($service_def); // Be explicit about the caching needs of this response. $response->setVary('Accept'); $service_def->processResponse($response); return $response; }
/** * Serialize data of ProcessJob * * @param ProcessJob $processJob */ protected function serialize(ProcessJob $processJob) { $processData = $processJob->getData(); $serializedData = $this->serializer->serialize($processData, $this->format, array('processJob' => $processJob)); $processJob->setSerializedData($serializedData); $processData->setModified(false); }
/** * Performs the routes dump. * * @param InputInterface $input The command input * @param OutputInterface $output The command output */ private function doDump(InputInterface $input, OutputInterface $output) { if (!is_dir($dir = dirname($this->targetPath))) { $output->writeln('<info>[dir+]</info> ' . $dir); if (false === @mkdir($dir, 0777, true)) { throw new \RuntimeException('Unable to create directory ' . $dir); } } $output->writeln('<info>[file+]</info> ' . $this->targetPath); $baseUrl = $this->getContainer()->hasParameter('fos_js_routing.request_context_base_url') ? $this->getContainer()->getParameter('fos_js_routing.request_context_base_url') : $this->extractor->getBaseUrl(); $content = $this->serializer->serialize(new RoutesResponse($baseUrl, $this->extractor->getRoutes($input->getOption('sets')), $input->getOption('locale'), $this->extractor->getHost(), $this->extractor->getScheme()), 'json'); $content = sprintf("%s(%s);", $input->getOption('callback'), $content); if (false === @file_put_contents($this->targetPath, $content)) { throw new \RuntimeException('Unable to write file ' . $this->targetPath); } }
/** * @param GetResponseEvent $event * @param Response $response * @param RpcResponse $rpcResponse */ protected function setResponse(GetResponseEvent $event, Response $response, RpcResponse $rpcResponse) { $responseType = $response->headers->get('Content-Type'); list($protocol, $encoding) = $this->factory->getContentType($responseType); $content = $this->serializer->serialize($rpcResponse, $protocol, ['encoding' => $encoding]); $response->setContent($content); $event->setResponse($response); }
/** * @param mixed $body * * @return string */ public function serializeBody($body, array $options) { $context = []; if (array_key_exists('groups', $options)) { $context['groups'] = $options['groups']; } return $this->serializer->serialize($body, 'json', $context); }
/** * {@inheritdoc} */ public function handle($config, CertificateResponse $response) { $domain = $response->getCertificateRequest()->getDistinguishedName()->getCommonName(); $privateKey = $response->getCertificateRequest()->getKeyPair()->getPrivateKey(); $certificate = $response->getCertificate(); $this->repository->save('nginxproxy/' . $domain . '.key', $this->serializer->serialize($privateKey, PemEncoder::FORMAT)); // Simple certificate $certPem = $this->serializer->serialize($certificate, PemEncoder::FORMAT); // Issuer chain $issuerChain = []; $issuerCertificate = $certificate->getIssuerCertificate(); while (null !== $issuerCertificate) { $issuerChain[] = $this->serializer->serialize($issuerCertificate, PemEncoder::FORMAT); $issuerCertificate = $issuerCertificate->getIssuerCertificate(); } $chainPem = implode("\n", $issuerChain); // Full chain $fullChainPem = $certPem . $chainPem; $this->repository->save('nginxproxy/' . $domain . '.crt', $fullChainPem); }
/** * The controller for the meteor.whoami route. * * @return \Symfony\Component\HttpFoundation\Response * A JSON response. */ public function whoami() { $account = $this->accountProxy->getAccount(); $uid = $account->id(); $name = $account->getAccountName(); $display_name = $account->getDisplayName(); $roles = $this->accountProxy->getRoles(); $result = $this->serializer->serialize(['uid' => $uid, 'name' => $name, 'displayName' => $display_name, 'roles' => $roles], 'json'); $response = new Response($result, Response::HTTP_OK); $response->headers->set('Content-type', 'application/json'); return $response; }
/** * Renders the template and initializes a new response object with the * rendered template content. * * @param GetResponseForControllerResultEvent $event A GetResponseForControllerResultEvent instance */ public function onKernelView(GetResponseForControllerResultEvent $event) { $request = $event->getRequest(); $result = $event->getControllerResult(); if (!$request->attributes->get('__hydra_serialize')) { return; } if (is_array($result) || $result instanceof \ArrayAccess || $result instanceof \Traversable) { $result = new Collection($request->getUri(), $result); } elseif (null === $result) { $event->setResponse(new JsonLdResponse('', 200)); return; } elseif (!is_object($result)) { throw new \Exception("A Hydra controller must return either an array or an object, got a(n) " . gettype($result)); } $serialized = $this->serializer->serialize($result, 'jsonld'); $event->setResponse(new JsonLdResponse($serialized)); }
/** * {@inheritdoc} */ public function storeDomainCertificate($domain, Certificate $certificate) { // Simple certificate $certPem = $this->serializer->serialize($certificate, PemEncoder::FORMAT); // Issuer chain $issuerChain = []; $issuerCertificate = $certificate->getIssuerCertificate(); while (null !== $issuerCertificate) { $issuerChain[] = $this->serializer->serialize($issuerCertificate, PemEncoder::FORMAT); $issuerCertificate = $issuerCertificate->getIssuerCertificate(); } $chainPem = implode("\n", $issuerChain); // Full chain $fullChainPem = $certPem . $chainPem; // Combined $keyPair = $this->loadDomainKeyPair($domain); $combinedPem = $fullChainPem . $this->serializer->serialize($keyPair->getPrivateKey(), PemEncoder::FORMAT); // Save $this->save('certs/' . $domain . '/cert.pem', $certPem); $this->save('certs/' . $domain . '/chain.pem', $chainPem); $this->save('certs/' . $domain . '/fullchain.pem', $fullChainPem); $this->save('certs/' . $domain . '/combined.pem', $combinedPem); }
/** * Launch quick export dispatching action and serialize results */ protected function quickExport() { $results = $this->massActionDispatcher->dispatch($this->request); echo $this->serializer->serialize($results, $this->getFormat(), $this->getContext()); }
/** * Serializes data in the appropriate format. * * @param mixed $data any data * @param string $format format name * @param array $context options normalizers/encoders have access to * * @return string */ public function serialize($data, $format, array $context = array()) { return $this->serializer->serialize($data, $format, $context); }
/** * Serializes the data array. * * @param array $data * * @return string */ protected function serialize(array $data) { // Prepend API key to all serialized data $data['key'] = $this->apiKey; return $this->serializer->serialize($data, 'json'); }
/** * {@inheritDoc} */ public function serialize($data) { return $this->serializer->serialize($data, 'json'); }
/** * Serialize a single product * * @param ProductInterface $product * @param string[] $channels * @param string[] $locales * @param string $url * * @return array */ public function get(ProductInterface $product, $channels, $locales, $url) { $data = $this->serializer->serialize($product, 'json', ['locales' => $locales, 'channels' => $channels, 'resource' => $url]); return $data; }
/** * {@inheritdoc} */ public function handleGetRequest(Request $request, $identifier) { $resource = $this->getResourceById($identifier); $data = $this->serializer->serialize($resource, self::RESPONSE_FORMAT, ['group' => $this->getResourceType()]); return new Response($data); }
/** * Serialize a single product * * @param ProductInterface $product * @param string[] $channels * @param string[] $locales * @param string $url * * @return array */ public function get(ProductInterface $product, $channels, $locales, $url) { $data = $this->serializer->serialize($product, 'json', ['locales' => $locales, 'channels' => $channels, 'resource' => $url, 'filter_type' => 'pim.external_api.product.view']); return $data; }
/** * Renders a resource response. * * Serialization can invoke rendering (e.g., generating URLs), but the * serialization API does not provide a mechanism to collect the * bubbleable metadata associated with that (e.g., language and other * contexts), so instead, allow those to "leak" and collect them here in * a render context. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * @param \Drupal\rest\ResourceResponseInterface $response * The response from the REST resource. * @param \Symfony\Component\Serializer\SerializerInterface $serializer * The serializer to use. * @param string|null $format * The response format, or NULL in case the response does not need a format, * for example for the response to a DELETE request. * @param \Drupal\rest\RestResourceConfigInterface $resource_config * The resource config. * * @return \Drupal\rest\ResourceResponse * The altered response. * * @todo Add test coverage for language negotiation contexts in * https://www.drupal.org/node/2135829. */ protected function renderResponse(Request $request, ResourceResponseInterface $response, SerializerInterface $serializer, $format, RestResourceConfigInterface $resource_config) { $data = $response->getResponseData(); if ($response instanceof CacheableResponseInterface) { // Add rest config's cache tags. $response->addCacheableDependency($resource_config); } // If there is data to send, serialize and set it as the response body. if ($data !== NULL) { if ($response instanceof CacheableResponseInterface) { $context = new RenderContext(); $output = $this->container->get('renderer')->executeInRenderContext($context, function () use($serializer, $data, $format) { return $serializer->serialize($data, $format); }); if (!$context->isEmpty()) { $response->addCacheableDependency($context->pop()); } } else { $output = $serializer->serialize($data, $format); } $response->setContent($output); $response->headers->set('Content-Type', $request->getMimeType($format)); } return $response; }
/** * Serializes data in the appropriate format. * * @param mixed $data any data * @param string $format format name * @param SerializationContext|array $context options normalizers/encoders have access to * * @return string */ public function serialize($data, $format, $context = null) { return $this->target->serialize($data, $format, $context ? $context : ($this->expectsEmptyArray ? [] : null)); }
/** * @param array $decodedBody * @param string $contentType * * @return string */ private function serializeRequestBody(array $decodedBody, $contentType) { return $this->serializer->serialize($decodedBody, DecoderUtils::extractFormatFromContentType($contentType)); }
public function onManifestPush(ManifestEvent $event) { $manifest = $event->getManifest(); $message = new Message($this->serializer->serialize($manifest, 'json', ['groups' => ['manifest_push']])); $this->publisher->publish('manifest_push', $message); $manifest->setUpdatedAt(new \DateTime()); $this->om->flush(); }