本文整理汇总了PHP中Symfony\Component\Serializer\Serializer::decode方法的典型用法代码示例。如果您正苦于以下问题:PHP Serializer::decode方法的具体用法?PHP Serializer::decode怎么用?PHP Serializer::decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Serializer\Serializer
的用法示例。
在下文中一共展示了Serializer::decode方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: deserialize
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);
}
示例2: handler
/**
* Process the client-side request and send response.
*
* @param string $class
* Defines a form class.
*
* @param callable $callback
* Defines a callback function.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* Response represents an HTTP response in JSON format.
*/
public function handler($class, $callback = NULL)
{
$response = $this->response();
$request = $this->request();
$output = array();
$params = NULL;
// Get the Request body and decode the JSON content.
$content = $request->getContent();
if ($this->isJson($content)) {
$params = $this->serializer->decode($content, 'json');
} else {
$response->setStatusCode($response::HTTP_BAD_REQUEST);
}
// Submit the form.
if ($request->getMethod() == 'POST' && $params) {
$output = $this->submitForm($class, $params);
// Success.
if (isset($output['data'])) {
// Execute pre-process callback, if provided.
if (is_callable($callback)) {
$callback($output['data']);
}
$response->setStatusCode($response::HTTP_ACCEPTED);
} elseif (isset($output['error'])) {
$response->setStatusCode($response::HTTP_BAD_REQUEST);
} else {
$response->setStatusCode($response::HTTP_FORBIDDEN);
}
}
// Return the response.
return $response->setData($output);
}
示例3: testLogoutCsrfProtection
/**
* Test csrf protection of User Logout route.
*/
public function testLogoutCsrfProtection()
{
$client = \Drupal::httpClient();
$login_status_url = $this->getLoginStatusUrlString();
$account = $this->drupalCreateUser();
$name = $account->getUsername();
$pass = $account->passRaw;
$response = $this->loginRequest($name, $pass);
$this->assertEquals(200, $response->getStatusCode());
$result_data = $this->serializer->decode($response->getBody(), 'json');
$logout_token = $result_data['logout_token'];
// Test third party site posting to current site with logout request.
// This should not logout the current user because it lacks the CSRF
// token.
$response = $this->logoutRequest('json');
$this->assertEquals(403, $response->getStatusCode());
// Ensure still logged in.
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);
// Try with an incorrect token.
$response = $this->logoutRequest('json', 'not-the-correct-token');
$this->assertEquals(403, $response->getStatusCode());
// Ensure still logged in.
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_IN);
// Try a logout request with correct token.
$response = $this->logoutRequest('json', $logout_token);
$this->assertEquals(204, $response->getStatusCode());
// Ensure actually logged out.
$response = $client->get($login_status_url, ['cookies' => $this->cookies]);
$this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);
}
示例4: decodeData
/**
* Decode tha data
* @param string $req_obj
* @return array
*/
public function decodeData($req_obj)
{
//get serializer instance
$serializer = new Serializer(array(), array('json' => new \Symfony\Component\Serializer\Encoder\JsonEncoder(), 'xml' => new \Symfony\Component\Serializer\Encoder\XmlEncoder()));
$jsonContent = $serializer->decode($req_obj, 'json');
return $jsonContent;
}
示例5: login
/**
* Logs in a user.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request.
*
* @return \Symfony\Component\HttpFoundation\Response
* A response which contains the ID and CSRF token.
*/
public function login(Request $request)
{
$format = $this->getRequestFormat($request);
$content = $request->getContent();
$credentials = $this->serializer->decode($content, $format);
if (!isset($credentials['name']) && !isset($credentials['pass'])) {
throw new BadRequestHttpException('Missing credentials.');
}
if (!isset($credentials['name'])) {
throw new BadRequestHttpException('Missing credentials.name.');
}
if (!isset($credentials['pass'])) {
throw new BadRequestHttpException('Missing credentials.pass.');
}
$this->floodControl($request, $credentials['name']);
if ($this->userIsBlocked($credentials['name'])) {
throw new BadRequestHttpException('The user has not been activated or is blocked.');
}
if ($uid = $this->userAuth->authenticate($credentials['name'], $credentials['pass'])) {
$this->flood->clear('user.http_login', $this->getLoginFloodIdentifier($request, $credentials['name']));
/** @var \Drupal\user\UserInterface $user */
$user = $this->userStorage->load($uid);
$this->userLoginFinalize($user);
// Send basic metadata about the logged in user.
$response_data = [];
if ($user->get('uid')->access('view', $user)) {
$response_data['current_user']['uid'] = $user->id();
}
if ($user->get('roles')->access('view', $user)) {
$response_data['current_user']['roles'] = $user->getRoles();
}
if ($user->get('name')->access('view', $user)) {
$response_data['current_user']['name'] = $user->getAccountName();
}
$response_data['csrf_token'] = $this->csrfToken->get('rest');
$logout_route = $this->routeProvider->getRouteByName('user.logout.http');
// Trim '/' off path to match \Drupal\Core\Access\CsrfAccessCheck.
$logout_path = ltrim($logout_route->getPath(), '/');
$response_data['logout_token'] = $this->csrfToken->get($logout_path);
$encoded_response_data = $this->serializer->encode($response_data, $format);
return new Response($encoded_response_data);
}
$flood_config = $this->config('user.flood');
if ($identifier = $this->getLoginFloodIdentifier($request, $credentials['name'])) {
$this->flood->register('user.http_login', $flood_config->get('user_window'), $identifier);
}
// Always register an IP-based failed login event.
$this->flood->register('user.failed_login_ip', $flood_config->get('ip_window'));
throw new BadRequestHttpException('Sorry, unrecognized username or password.');
}
示例6: testDecode
public function testDecode()
{
$serializer = new Serializer(array(), array('json' => new JsonEncoder()));
$data = array('foo', array(5, 3));
$result = $serializer->decode(json_encode($data), 'json');
$this->assertEquals($data, $result);
}
示例7: decode
/**
* @param string $string
* @param string $format
* @param array $context
*
* @return array
*/
public function decode($string, $format = null, array $context = [])
{
$array = $this->serializer->decode($string, $context['encoding'], $context);
$array = $this->decodeValue($array);
return $array;
}
示例8: editAction
/**
* Displays a form to edit an existing Products product.
*
* @Security("has_role('ROLE_ACCOUNTANT')")
* @Route("/{id}/edit", name="products_edit")
* @Method({"GET", "PUT"})
* @Template()
*/
public function editAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('MeVisaERPBundle:Products')->find($id);
if (!$product) {
throw $this->createNotFoundException('Unable to find Products product.');
}
if (!is_array($product->getRequiredDocuments())) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$product->setRequiredDocuments($serializer->decode($product->getRequiredDocuments(), 'json'));
}
$editForm = $this->createEditForm($product);
$editForm->handleRequest($request);
if ($editForm->isSubmitted()) {
if ($editForm->isValid()) {
$productPrices = $product->getPricing();
foreach ($productPrices as $price) {
if (empty($price->getId())) {
$product->addPricing($price);
} else {
$em->refresh($price);
}
}
$em->flush();
return $this->redirect($this->generateUrl('products_show', array('id' => $id)));
}
}
return array('product' => $product, 'product_form' => $editForm->createView());
}
示例9: serialize
/**
* @inheritdoc
*/
protected function serialize($data)
{
return new ParameterBag((array) $this->serializer->decode($data, 'xml'));
}
示例10: deserialize
/**
* Parses JSON into a PHP array.
*
* This method, when supplied with a JSON stream, converts JSON
* into a PHP array structure.
*
* @param string $jsonFormatedString The string containing JSON formatted text.
*
* @return array The JSON string converted into a PHP array.
*
* @api
*/
public function deserialize(string $jsonFormatedString) : array
{
return $this->serializer->decode($jsonFormatedString, static::FORMAT);
}
示例11: decode
/**
* @param string $string
* @param null $format
* @param array $context
*
* @return mixed
*/
public function decode($string, $format = null, array $context = [])
{
return $this->serializer->decode($string, $context['encoding'], $context);
}
示例12: importContent
/**
* {@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;
}
示例13: downloadInfos
/**
* Fonction pour télécharger les informations d'un livre
*
* @param string $isbn ISBN
* @return array Livre
* @throws \Exception
*/
private function downloadInfos($isbn)
{
$serializer = new Serializer(array(), array(new XmlEncoder()));
// Récupération du livre
$url = "http://isbndb.com/api/books.xml?access_key=45L5NTHL&index1=isbn&value1=" . $isbn;
if (!($reponse = file_get_contents($url))) {
throw new \Exception('Impossible de télécharger les résultats !');
}
if (!($book = $serializer->decode($reponse, 'xml')['BookList']['BookData'])) {
throw new \Exception('Le livre n\'a pas été trouvé : ' . $isbn);
}
return $book;
}