File path original token

Created on 14 October 2024, about 2 months ago

Problem/Motivation

Similarly to the File name - original token, it is sometimes necessary for the File path to remain original.

Steps to reproduce

For example, when we want to move the files in the public folder to the private folder, but we want to keep the existing structure.
Currently, if the old File path was [date:custom:Y]-[date:custom:m], then after moving all files will be in the current year/month folder, which is not good because everything will be in one folder, even if there is a file with the same name, we get a FileWriteException.

Proposed resolution

In my custom module, I created another token ([file:ffp-path-original]) that returns the original path.

use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */
function mymodule_token_info() {
  $info['tokens']['file']['ffp-path-original'] = [
    'name' => t("File path - original"),
    'description' => t("File path - original"),
  ];

  return $info;
}

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];

  if ($type === 'file' && !empty($data['file'])) {
    /** @var \Drupal\file\FileInterface $file */
    $file = $data['file'];

    foreach ($tokens as $name => $original) {
      // The original file path.
      if ($name === 'ffp-path-original') {
        $path = str_replace('public://', '', $file->getFileUri());
        $path = str_replace($file->getFilename(), '', $path);

        $replacements[$original] = $path;
        break;
      }
    }
  }

  return $replacements;
}

Feature request
Status

Active

Component

Code

Created by

🇷🇸Serbia norbert-goco Subotica

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024