function FileExampleSubmitHandlerHelper::handleUnmanagedPhp

Submit handler to write an unmanaged file using plain PHP functions.

The key functions used here are:

  • FileSystemInterface::saveData(), which takes a buffer and saves it to a named file, but does not create any kind of tracking record in the database.
  • file_create_url(), which converts a URI in the form public://junk.txt or private://something/test.txt into a URL like http://example.com/sites/default/files/junk.txt.
  • drupal_tempnam() generates a temporary filename for use.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

File

modules/file_example/src/FileExampleSubmitHandlerHelper.php, line 186

Class

FileExampleSubmitHandlerHelper
A submit handler helper class for the file_example module.

Namespace

Drupal\file_example

Code

public function handleUnmanagedPhp(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();
    $data = $form_values['write_contents'];
    $destination = !empty($form_values['destination']) ? $form_values['destination'] : NULL;
    if (empty($destination)) {
        // If no destination has been provided, use a generated name.
        $destination = $this->fileSystem
            ->tempnam('public://', 'file');
    }
    // With all traditional PHP functions we can use the stream wrapper notation
    // for a file as well.
    $fp = fopen($destination, 'w');
    // To demonstrate the fact that everything is based on streams, we'll do
    // multiple 5-character writes to put this to the file. We could easily
    // (and far more conveniently) write it in a single statement with
    // fwrite($fp, $data).
    $length = strlen($data);
    $write_size = 5;
    for ($i = 0; $i < $length; $i += $write_size) {
        $result = fwrite($fp, substr($data, $i, $write_size));
        if ($result === FALSE) {
            $this->messenger
                ->addMessage($this->t('Failed writing to the file %file', [
                '%file' => $destination,
            ]), 'error');
            fclose($fp);
            return;
        }
    }
    $url = $this->fileHelper
        ->getExternalUrl($destination);
    $this->stateHelper
        ->setDefaultFile($destination);
    if ($url) {
        $this->messenger
            ->addMessage($this->t('Saved file as %filename (accessible via <a href=":url">this URL</a>, uri=<span id="uri">@uri</span>)', [
            '%filename' => $destination,
            '@uri' => $destination,
            ':url' => $url->toString(),
        ]));
    }
    else {
        $this->messenger
            ->addMessage($this->t('Saved file as %filename (not accessible externally)', [
            '%filename' => $destination,
            '@uri' => $destination,
        ]));
    }
}