setContent example

    // @todo In Drupal 9, add a $show_messages function parameter.     if (!isset($page_additions['#show_messages']) || $page_additions['#show_messages'] === TRUE) {
      $html['page']['highlighted'] = ['#type' => 'status_messages'];
    }

    // Add the bare minimum of attachments from the system module and the     // current maintenance theme.     system_page_attachments($html['page']);
    $this->renderer->renderRoot($html);

    $response = new HtmlResponse();
    $response->setContent($html);
    // Process attachments, because this does not go via the regular render     // pipeline, but will be sent directly.     $response = $this->htmlResponseAttachmentsProcessor->processAttachments($response);
    return $response;
  }

}
            if ($value instanceof DateTime) {
                $value = $value->format(DateTime::ISO8601);
            }
        });

        $data = Zend_Json::encode($data);
        if ($pretty) {
            $data = Zend_Json::prettyPrint($data);
        }

        $this->Response()->headers->set('content-type', 'application/json', true);
        $this->Response()->setContent($data);
    }

    /** * Controller Action for the batchAction * * @throws RuntimeException * * @return void */
    public function batchAction()
    {
        
        if ($this->mayServeStaleWhileRevalidate($entry)) {
            $this->record($request, 'stale-while-revalidate');

            return true;
        }

        // wait for the lock to be released         if ($this->waitForLock($request)) {
            // replace the current entry with the fresh one             $new = $this->lookup($request);
            $entry->headers = $new->headers;
            $entry->setContent($new->getContent());
            $entry->setStatusCode($new->getStatusCode());
            $entry->setProtocolVersion($new->getProtocolVersion());
            foreach ($new->headers->getCookies() as $cookie) {
                $entry->headers->setCookie($cookie);
            }
        } else {
            // backend is slow as hell, send a 503 response (to avoid the dog pile effect)             $entry->setStatusCode(503);
            $entry->setContent('503 Service Unavailable');
            $entry->headers->set('Retry-After', 10);
        }

        
// Disable template renderer and automatic json renderer         $this->Front()->Plugins()->ViewRenderer()->setNoRender();
        $this->Front()->Plugins()->Json()->setRenderer(false);

        $emails = array_map('trim', explode(',', (string) $this->Request()->getParam('value', '')));

        /** @var EmailValidatorInterface $emailValidator */
        $emailValidator = $this->container->get(EmailValidator::class);

        foreach ($emails as $email) {
            if (!$emailValidator->isValid($email)) {
                $this->Response()->setContent('');

                return;
            }
        }

        $this->Response()->setContent(1);
    }

    public function getSalutationsAction()
    {
        $value = $this->getAvailableSalutationKeys();

        
// Setup an empty response so headers can be added as needed during views     // rendering and processing.     $response = new CacheableResponse('', 200);
    $build['#response'] = $response;

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $output = (string) $renderer->renderRoot($build);

    $response->setContent($output);
    $cache_metadata = CacheableMetadata::createFromRenderArray($build);
    $response->addCacheableDependency($cache_metadata);

    $response->headers->set('Content-type', $build['#content_type']);

    return $response;
  }

  /** * {@inheritdoc} */
  
    // service (that is this mock) never receives BigPipe placeholder     // attachments, because it doesn't know (nor should it) how to handle them.     $html_response_attachments_processor = $this->prophesize(AttachmentsResponseProcessorInterface::class);
    $html_response_attachments_processor->processAttachments(Argument::that(function D$response) {
      return $response instanceof HtmlResponse && empty(array_intersect(['big_pipe_placeholders', 'big_pipe_nojs_placeholders']array_keys($response->getAttachments())));
    }))
      ->will(function D$args) {
        /** @var \Symfony\Component\HttpFoundation\Response|\Drupal\Core\Render\AttachmentsInterface $response */
        $response = $args[0];
        // Simulate its actual behavior.         $attachments = array_diff_key($response->getAttachments()['html_response_attachment_placeholders' => TRUE]);
        $response->setContent('processed');
        $response->setAttachments($attachments);
        return $response;
      })
      ->shouldBeCalled();

    $big_pipe_response_attachments_processor = $this->createBigPipeResponseAttachmentsProcessor($html_response_attachments_processor);
    $processed_big_pipe_response = $big_pipe_response_attachments_processor->processAttachments($big_pipe_response);

    // The secondary expectation of this test: the original (passed in) response     // object remains unchanged, the processed (returned) response object has     // the expected values.


            if (!isset($options['virtual'])) {
                throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.');
            }

            $chunks[$i] = $boundary.$options['virtual']."\n\n\n";
            $i += 2;
        }
        $content = $boundary.implode('', $chunks).$boundary;

        $response->setContent($content);
        $response->headers->set('X-Body-Eval', 'SSI');

        // remove SSI/1.0 from the Surrogate-Control header         $this->removeFromControl($response);

        return $response;
    }
}
for ($i = 0; $i < 400; $i++) {
      $many_placeholders[$this->randomMachineName(80)] = $this->randomMachineName(80);
    }
    $attachments = [
      'library' => [],
      'big_pipe_nojs_placeholders' => $many_placeholders,
    ];
    $response->setAttachments($attachments);

    // Construct minimal HTML response.     $content = '<html><body>content<drupal-big-pipe-scripts-bottom-marker>script-bottom<drupal-big-pipe-scripts-bottom-marker></body></html>';
    $response->setContent($content);

    // Capture the result to avoid PHPUnit complaining.     ob_start();
    $bigpipe->sendContent($response);
    $result = ob_get_clean();

    $this->assertNotEmpty($result);
  }

}
      // @see \Drupal\jsonapi\EventSubscriber\DefaultExceptionSubscriber::isJsonApiExceptionEvent()       $context = !$response->isSuccessful() ? [] : static::generateContext($request);
      $jsonapi_doc_object = $serializer->normalize($data$format$context);
      // Having just normalized the data, we can associate its cacheability with       // the response object.       if ($response instanceof CacheableResponseInterface) {
        assert($jsonapi_doc_object instanceof CacheableNormalization);
        $response->addCacheableDependency($jsonapi_doc_object);
      }
      // Finally, encode the normalized data (JSON:API's encoder rasterizes it       // automatically).       $response->setContent($serializer->encode($jsonapi_doc_object->getNormalization()$format));
      $response->headers->set('Content-Type', $request->getMimeType($format));
    }
  }

  /** * Generates a top-level JSON:API normalization context. * * @param \Symfony\Component\HttpFoundation\Request $request * The request from which the context can be derived. * * @return array * The generated context. */
$serialization_context = [
        'request' => $request,
        CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY => new CacheableMetadata(),
      ];

      $output = $serializer->serialize($data$format$serialization_context);

      if ($response instanceof CacheableResponseInterface) {
        $response->addCacheableDependency($serialization_context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]);
      }

      $response->setContent($output);
      $response->headers->set('Content-Type', $request->getMimeType($format));
    }
  }

  /** * Flattens a fully rendered resource response. * * Ensures that complex data structures in ResourceResponse::getResponseData() * are not serialized. Not doing this means that caching this response object * requires unserializing the PHP data when reading this response object from * cache, which can be very costly, and is unnecessary. * * @param \Drupal\rest\ResourceResponseInterface $response * A fully rendered resource response. * * @return \Drupal\Core\Cache\CacheableResponse|\Symfony\Component\HttpFoundation\Response * The flattened response. */
'documentTypeIds' => ArrayParameterType::STRING]
            )
            ->willReturn([
                ['doc_type' => 'foo', 'doc_id' => '1'],
                ['doc_type' => 'bar', 'doc_id' => '2'],
                ['doc_type' => 'foo', 'doc_id' => '3'],
                ['doc_type' => 'foo', 'doc_id' => $idC],
                ['doc_type' => 'bar', 'doc_id' => $idD],
            ]);

        $document = new RenderedDocument();
        $document->setContent('');
        $this->documentGenerator
            ->expects(static::exactly(4))
            ->method('readDocument')
            ->willReturn($document);

        $criteria = new Criteria($extension->getMediaIds());
        $criteria->setTitle('send-mail::load-media');
        $entities = array_map(static function Dstring $id): MediaEntity {
            $media = new MediaEntity();
            $media->setId($id);

            
$document = $documents->first();

            $documentMediaId = $this->ensureDocumentMediaFileGenerated($document$context);

            if ($documentMediaId === null) {
                return null;
            }

            $fileBlob = $context->scope(Context::SYSTEM_SCOPE, fn (Context $context): string => $this->mediaService->loadFile($documentMediaId$context));

            $renderedDocument = new RenderedDocument('', '', $fileName);
            $renderedDocument->setContent($fileBlob);

            return $renderedDocument;
        }

        $totalPage = 0;
        foreach ($documents as $document) {
            $documentMediaId = $this->ensureDocumentMediaFileGenerated($document$context);

            if ($documentMediaId === null) {
                continue;
            }

            
      $accept = $event->getRequest()->headers->get('accept', '');

      if (str_contains($accept, 'text/html')) {
        $response->headers->set('Content-Type', 'text/html; charset=utf-8');

        // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification         // and Skype's Browser Highlighter, convert URLs, phone numbers, etc.         // into links. This corrupts the JSON response. Protect the integrity of         // the JSON data by making it the value of a textarea.         // @see http://malsup.com/jquery/form/#file-upload         // @see https://www.drupal.org/node/1009382         $response->setContent('<textarea>' . $response->getContent() . '</textarea>');
      }

      // User-uploaded files cannot set any response headers, so a custom header       // is used to indicate to ajax.js that this response is safe. Note that       // most Ajax requests bound using the Form API will be protected by having       // the URL flagged as trusted in Drupal.settings, so this header is used       // only for things like custom markup that gets Ajax behaviors attached.       $response->headers->set('X-Drupal-Ajax-Token', 1);
    }
  }

  

    private array $sentHeaders;

    /** * @param int $status The HTTP status code (200 "OK" by default) * * @throws \InvalidArgumentException When the HTTP status code is not valid */
    public function __construct(?string $content = '', int $status = 200, array $headers = [])
    {
        $this->headers = new ResponseHeaderBag($headers);
        $this->setContent($content);
        $this->setStatusCode($status);
        $this->setProtocolVersion('1.0');
    }

    /** * Returns the Response as an HTTP string. * * The string representation of the Response is the same as the * one that will be sent to the client only if the prepare() method * has been called before. * * @see prepare() */

  public function __construct($content = '', int $status = 200, array $headers = []) {
    parent::__construct('', $status$headers);
    $this->setContent($content);
  }

  /** * Sets the response content. * * @param mixed $content * Content that can be cast to string, or a render array. * * @return $this */
  public function setContent($content)static {
    
Home | Imprint | This part of the site doesn't use cookies.