JsonResponse example


  public function getTimezone($abbreviation = '', $offset = -1, $is_daylight_saving_time = NULL) {
    $offset = intval($offset);
    // Out of bounds check for offset. Offset +/- UTC is typically no     // smaller/larger than -12/+14.     if ($offset < -60000 || $offset > 60000) {
      return new JsonResponse(FALSE);
    }

    if (isset($is_daylight_saving_time)) {
      $original = intval($is_daylight_saving_time);
      $is_daylight_saving_time = min(1, max(-1, intval($is_daylight_saving_time)));
      // Catch if out of boundary.       if ($original !== $is_daylight_saving_time) {
        return new JsonResponse(FALSE);
      }
    }

    


    // The original_format parameter will only exist when switching text format.     $original_format_id = $request->request->get('original_format_id');
    $original_format = NULL;
    if (isset($original_format_id)) {
      $original_format = $this->entityTypeManager()
        ->getStorage('filter_format')
        ->load($original_format_id);
    }

    return new JsonResponse(editor_filter_xss($value$filter_format$original_format));
  }

}

  public function storageLegacyHandler($form_build_id) {
    $form_state = new FormState();
    $form = $this->formBuilder()->getCache($form_build_id$form_state);
    $result = [
      'form' => $form,
      'form_state' => $form_state,
    ];
    $form['#poisoned'] = TRUE;
    $form_state->set('poisoned', TRUE);
    $this->formBuilder()->setCache($form_build_id$form$form_state);
    return new JsonResponse($result);
  }

}
$prefix . '_d' => 'd',
      $prefix . '_c' => new TranslatableMarkup('main c'),
      $prefix . '_b' => new TranslatableMarkup('main b'),
      $prefix . '_a' => 'a',
    ];
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setResponse(new JsonResponse($form_state->getValues()));
  }

}
$node = $this->entityTypeManager()->getStorage('node')->load($nid);
      $new = $this->commentManager->getCountNewComments($node);
      $page_number = $this->entityTypeManager()->getStorage('comment')
        ->getNewCommentPageNumber($node->{$field_name}->comment_count, $new$node$field_name);
      $query = $page_number ? ['page' => $page_number] : NULL;
      $links[$nid] = [
        'new_comment_count' => (int) $new,
        'first_new_comment_link' => Url::fromRoute('entity.node.canonical', ['node' => $node->id()]['query' => $query, 'fragment' => 'new'])->toString(),
      ];
    }

    return new JsonResponse($links);
  }

}
public function getParentOptions(Request $request) {
    $available_menus = [];
    if ($menus = $request->request->all('menus')) {
      foreach ($menus as $menu) {
        $available_menus[$menu] = $menu;
      }
    }
    // @todo Update this to use the optional $cacheability parameter, so that     // a cacheable JSON response can be sent.     $options = $this->menuParentSelector->getParentSelectOptions('', $available_menus);

    return new JsonResponse($options);
  }

  /** * Route title callback. * * @param \Drupal\system\MenuInterface $menu * The menu entity. * * @return array * The menu label as a render array. */
  


namespace Symfony\Component\HttpFoundation\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\JsonResponse;

class JsonResponseTest extends TestCase
{
    public function testConstructorEmptyCreatesJsonObject()
    {
        $response = new JsonResponse();
        $this->assertSame('{}', $response->getContent());
    }

    public function testConstructorWithArrayCreatesJsonArray()
    {
        $response = new JsonResponse([0, 1, 2, 3]);
        $this->assertSame('[0,1,2,3]', $response->getContent());
    }

    public function testConstructorWithAssocArrayCreatesJsonObject()
    {
        

}

class WithMapQueryStringController
{
    public function __invoke(#[MapQueryString] ?QueryString $query): Response     {
        if (!$query) {
            return new Response('', Response::HTTP_NO_CONTENT);
        }

        return new JsonResponse(
            ['filter' => ['status' => $query->filter->status, 'quantity' => $query->filter->quantity]],
        );
    }
}

class WithMapRequestPayloadController
{
    public function __invoke(#[MapRequestPayload] ?RequestBody $body, Request $request): Response     {
        if ('json' === $request->getPreferredFormat('json')) {
            if (!$body) {
                
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;

class JsonAuthenticationFailureHandler implements AuthenticationFailureHandlerInterface
{
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
    {
        return new JsonResponse(['message' => 'Something went wrong'], 500);
    }
}

        throw new BadCredentialsException();
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
    {
        return new JsonResponse([
            'error' => $exception->getMessageKey(),
        ], JsonResponse::HTTP_FORBIDDEN);
    }

    public function start(Request $request, AuthenticationException $authException = null): Response
    {
    }
}
if (empty($_SESSION['trace-handler'])) {
      $_SESSION['trace-handler'] = 1;
    }
    else {
      $_SESSION['trace-handler']++;
    }
    $request->getSession()->save();

    // Collect traces and return them in JSON format.     $trace = \Drupal::service('session_test.session_handler_proxy_trace')->getArrayCopy();

    return new JsonResponse($trace);
  }

  /** * Returns the values stored in the active session and the user ID. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A response object containing the session values and the user ID. */
  
if (!isset($replace_token)) {
        throw new AccessDeniedHttpException("Missing 'replace_token' query parameter.");
      }
      elseif (!$this->tokenGenerator->validate($replace_token$replace_pattern)) {
        throw new AccessDeniedHttpException("Invalid 'replace_token' query parameter.");
      }

      // Quote the pattern delimiter and remove null characters to avoid the e       // or other modifiers being injected.       $transliterated = preg_replace('@' . strtr($replace_pattern['@' => '\@', chr(0) => '']) . '@', $replace$transliterated);
    }
    return new JsonResponse($transliterated);
  }

}
foreach ($ids as $key => $id) {
      if (!isset($tokens[$key]) || !hash_equals($tokens[$key], Crypt::hmacBase64($id, Settings::getHashSalt() . \Drupal::service('private_key')->get()))) {
        throw new BadRequestHttpException('Invalid contextual ID specified.');
      }
      $element = [
        '#type' => 'contextual_links',
        '#contextual_links' => _contextual_id_to_links($id),
      ];
      $rendered[$id] = $this->renderer->renderRoot($element);
    }

    return new JsonResponse($rendered);
  }

}
$tags[] = $tag;
          if (mb_stripos($tag$string) !== FALSE) {
            $matches[] = ['value' => $tag, 'label' => Html::escape($tag)];
            if (count($matches) >= 10) {
              break 2;
            }
          }
        }
      }
    }

    return new JsonResponse($matches);
  }

  /** * Returns the form to edit a view. * * @param \Drupal\views_ui\ViewUI $view * The view to be edited. * @param string|null $display_id * (optional) The display ID being edited. Defaults to NULL, which will load * the first available display. * * @return array * An array containing the Views edit and preview forms. */
$form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Submit',
    ];
    return $form;
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setResponse(new JsonResponse($form_state->getValues()));
  }

}
Home | Imprint | This part of the site doesn't use cookies.