本文整理汇总了PHP中Symfony\Component\Serializer\SerializerInterface::serialize方法的典型用法代码示例。如果您正苦于以下问题:PHP SerializerInterface::serialize方法的具体用法?PHP SerializerInterface::serialize怎么用?PHP SerializerInterface::serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Serializer\SerializerInterface
的用法示例。
在下文中一共展示了SerializerInterface::serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: onKernelView
/**
* 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);
}
示例2: process
/**
* 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;
}
示例3: testSerializerComponentRegistration
/**
* 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.');
}
}
示例4: processRequest
/**
* 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;
}
示例5: serialize
/**
* 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);
}
示例6: doDump
/**
* 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);
}
}
示例7: setResponse
/**
* @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);
}
示例8: serializeBody
/**
* @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);
}
示例9: handle
/**
* {@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);
}
示例10: whoami
/**
* 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;
}
示例11: onKernelView
/**
* 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));
}
示例12: storeDomainCertificate
/**
* {@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);
}
示例13: quickExport
/**
* 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());
}
示例14: serialize
/**
* 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);
}
示例15: serialize
/**
* 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');
}