renderFromHtml example

      // @todo Decide to fix all the broken instances of class as a string       // in core or cast them.       $value = new AttributeArray($name$value);
    }
    elseif (is_bool($value)) {
      $value = new AttributeBoolean($name$value);
    }
    // As a development aid, we allow the value to be a safe string object.     elseif ($value instanceof MarkupInterface) {
      // Attributes are not supposed to display HTML markup, so we just convert       // the value to plain text.       $value = PlainTextOutput::renderFromHtml($value);
      $value = new AttributeString($name$value);
    }
    elseif (!is_object($value)) {
      $value = new AttributeString($name$value);
    }
    return $value;
  }

  /** * {@inheritdoc} */
  

  public function __construct($selector$title$content, array $dialog_options = []$settings = NULL) {
    $title = PlainTextOutput::renderFromHtml($title);
    $dialog_options += ['title' => $title];
    $this->selector = $selector;
    $this->content = $content;
    $this->dialogOptions = $dialog_options;
    $this->settings = $settings;
  }

  /** * Returns the dialog options. * * @return array */
    $remote_thumbnail_url = $resource->getThumbnailUrl();
    if (!$remote_thumbnail_url) {
      return NULL;
    }

    // Use the configured directory to store thumbnails. The directory can     // contain basic (i.e., global) tokens. If any of the replaced tokens     // contain HTML, the tags will be removed and XML entities will be decoded.     $configuration = $this->getConfiguration();
    $directory = $configuration['thumbnails_directory'];
    $directory = $this->token->replace($directory);
    $directory = PlainTextOutput::renderFromHtml($directory);

    // The local thumbnail doesn't exist yet, so try to download it. First,     // ensure that the destination directory is writable, and if it's not,     // log an error and bail out.     if (!$this->fileSystem->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
      $this->logger->warning('Could not prepare thumbnail destination directory @dir for oEmbed media.', [
        '@dir' => $directory,
      ]);
      return NULL;
    }

    

  protected function validate(FileInterface $file, array $validators) {
    $this->resourceValidate($file);

    // Validate the file based on the field definition configuration.     $errors = file_validate($file$validators);

    if (!empty($errors)) {
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map(function D$error) {
        return PlainTextOutput::renderFromHtml($error);
      }$errors));

      throw new UnprocessableEntityHttpException($message);
    }
  }

  /** * Prepares the filename to strip out any malicious extensions. * * @param string $filename * The file name. * @param array $validators * The array of upload validators. * * @return string * The prepared/munged filename. */

  public function on4xx(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    if ($exception && $exception instanceof HttpExceptionInterface && str_starts_with($exception->getStatusCode(), '4')) {
      $message = PlainTextOutput::renderFromHtml($exception->getMessage());
      // If the exception is cacheable, generate a cacheable response.       if ($exception instanceof CacheableDependencyInterface) {
        $response = new CacheableResponse($message$exception->getStatusCode()['Content-Type' => 'text/plain']);
        $response->addCacheableDependency($exception);
      }
      else {
        $response = new Response($message$exception->getStatusCode()['Content-Type' => 'text/plain']);
      }

      $response->headers->add($exception->getHeaders());
      $event->setResponse($response);
    }
// Each token value is markup if it implements MarkupInterface otherwise it     // is plain text. Convert them, but only if needed. It can cause corruption     // to render a string that's already plain text or to escape a string     // that's already markup.     foreach ($replacements as $token => $value) {
      if ($markup) {
        // Escape plain text tokens.         $replacements[$token] = $value instanceof MarkupInterface ? $value : new HtmlEscapedText($value);
      }
      else {
        // Render markup tokens to plain text.         $replacements[$token] = $value instanceof MarkupInterface ? PlainTextOutput::renderFromHtml($value) : $value;
      }
    }

    // Optionally alter the list of replacement values.     if (!empty($options['callback'])) {
      $function = $options['callback'];
      $function($replacements$data$options$bubbleable_metadata);
    }

    $tokens = array_keys($replacements);
    $values = array_values($replacements);

    

  protected function getUploadLocation(array $settings) {
    $destination = trim($settings['file_directory'], '/');

    // Replace tokens. As the tokens might contain HTML we convert it to plain     // text.     $destination = PlainTextOutput::renderFromHtml($this->token->replace($destination[][]new BubbleableMetadata()));
    return $settings['uri_scheme'] . '://' . $destination;
  }

  /** * Retrieves the upload validators for a field definition. * * This is copied from \Drupal\file\Plugin\Field\FieldType\FileItem as there * is no entity instance available here that a FileItem would exist for. * * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition * The field definition for which to get validators. * * @return array * An array suitable for passing to file_save_upload() or the file field * element's '#upload_validators' property. */
$field_definition = $this->validateAndLoadFieldDefinition($resource_type->getEntityTypeId()$resource_type->getBundle()$file_field_name);

    static::ensureFileUploadAccess($this->currentUser, $field_definition$entity);

    $filename = $this->fileUploader->validateAndParseContentDispositionHeader($request);
    $file = $this->fileUploader->handleFileUploadForField($field_definition$filename$this->currentUser);

    if ($file instanceof EntityConstraintViolationListInterface) {
      $violations = $file;
      $message = "Unprocessable Entity: file validation failed.\n";
      $message .= implode("\n", array_map(function DConstraintViolationInterface $violation) {
        return PlainTextOutput::renderFromHtml($violation->getMessage());
      }(array) $violations->getIterator()));
      throw new UnprocessableEntityHttpException($message);
    }

    if ($resource_type->getFieldByInternalName($file_field_name)->hasOne()) {
      $entity->{$file_field_name} = $file;
    }
    else {
      $entity->get($file_field_name)->appendItem($file);
    }
    static::validate($entity[$file_field_name]);
    
      // more hook_mail_alter() implementations. We set 'result' to NULL,       // because FALSE indicates an error in sending.       if (empty($message['send'])) {
        $message['result'] = NULL;
      }
      // Sending was originally requested and was not canceled.       else {
        // Ensure that subject is plain text. By default translated and         // formatted strings are prepared for the HTML context and email         // subjects are plain strings.         if ($message['subject']) {
          $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
        }
        $message['result'] = $system->mail($message);
        // Log errors.         if (!$message['result']) {
          $this->loggerFactory->get('mail')
            ->error('Error sending email (from %from to %to with reply-to %reply).', [
              '%from' => $message['from'],
              '%to' => $message['to'],
              '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
            ]);
          $error_message = $params['_error_message'] ?? $this->t('Unable to send email. Contact the site administrator if the problem persists.');
          
$this->assertSame(201, $response->getStatusCode());

    // Simulate a race condition where two files are uploaded at almost the same     // time, by removing the first uploaded file from disk (leaving the entry in     // the file_managed table) before trying to upload another file with the     // same name.     unlink(\Drupal::service('file_system')->realpath('public://foobar/example.txt'));

    // Make the same request again. The upload should fail validation.     $response = $this->fileRequest($uri$this->testFileData);
    $this->assertResourceErrorResponse(422, PlainTextOutput::renderFromHtml("Unprocessable Entity: file validation failed.\nThe file public://foobar/example.txt already exists. Enter a unique file URI.")$uri$response);
  }

  /** * Tests using the file upload route with any path prefixes being stripped. * * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives */
  public function testFileUploadStrippedFilePath() {
    $this->setUpAuthorization('POST');
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    

  }

  /** * {@inheritdoc} */
  public function execute($entity = NULL) {
    if (empty($this->configuration['node'])) {
      $this->configuration['node'] = $entity;
    }

    $recipient = PlainTextOutput::renderFromHtml($this->token->replace($this->configuration['recipient']$this->configuration));

    // If the recipient is a registered user with a language preference, use     // the recipient's preferred language. Otherwise, use the system default     // language.     $recipient_accounts = $this->storage->loadByProperties(['mail' => $recipient]);
    $recipient_account = reset($recipient_accounts);
    if ($recipient_account) {
      $langcode = $recipient_account->getPreferredLangcode();
    }
    else {
      $langcode = $this->languageManager->getDefaultLanguage()->getId();
    }
$entity = $violations->getEntity();
    foreach ($violations->getFieldNames() as $field_name) {
      $field_violations = $violations->getByField($field_name);
      $cardinality = $entity->get($field_name)
        ->getFieldDefinition()
        ->getFieldStorageDefinition()
        ->getCardinality();

      foreach ($field_violations as $violation) {
        /** @var \Symfony\Component\Validator\ConstraintViolation $violation */
        $error['detail'] = $violation->getPropertyPath() . ': '
          . PlainTextOutput::renderFromHtml($violation->getMessage());

        $pointer = '/data/attributes/'
          . str_replace('.', '/', $violation->getPropertyPath());
        if ($cardinality == 1) {
          // Remove erroneous '/0/' index for single-value fields.           $pointer = str_replace("/data/attributes/$field_name/0/", "/data/attributes/$field_name/", $pointer);
        }
        $error['source']['pointer'] = $pointer;

        $errors[] = $error;
      }
    }
if ($fields_to_validate) {
      // Filter violations by explicitly provided array of field names.       $violations->filterByFields(array_diff(array_keys($entity->getFieldDefinitions())$fields_to_validate));
    }

    if ($violations->count() > 0) {
      $message = "Unprocessable Entity: validation failed.\n";
      foreach ($violations as $violation) {
        // We strip every HTML from the error message to have a nicer to read         // message on REST responses.         $message .= $violation->getPropertyPath() . ': ' . PlainTextOutput::renderFromHtml($violation->getMessage()) . "\n";
      }
      throw new UnprocessableEntityHttpException($message);
    }
  }

}

  public function testRenderFromHtml($expected$string$args = []) {
    $markup = new FormattableMarkup($string$args);
    $output = PlainTextOutput::renderFromHtml($markup);
    $this->assertSame($expected$output);
  }

  /** * Data provider for ::testRenderFromHtml() */
  public static function providerRenderFromHtml() {
    $prophet = new Prophet();
    $data = [];

    $data['simple-text'] = ['Giraffes and wombats', 'Giraffes and wombats'];
    

  protected static function doGetUploadLocation(array $settings$data = []) {
    $destination = trim($settings['file_directory'], '/');

    // Replace tokens. As the tokens might contain HTML we convert it to plain     // text.     $destination = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($destination$data));
    return $settings['uri_scheme'] . '://' . $destination;
  }

  /** * Retrieves the upload validators for a file field. * * @return array * An array suitable for passing to file_save_upload() or the file field * element's '#upload_validators' property. */
  public function getUploadValidators() {
    
Home | Imprint | This part of the site doesn't use cookies.