image_to_media_swapper-2.x-dev/tests/src/Traits/VfsFileTestTrait.php

tests/src/Traits/VfsFileTestTrait.php
<?php

declare(strict_types=1);

namespace Drupal\Tests\image_to_media_swapper\Traits;

/**
 * Provides helper methods for tests using the virtual file system.
 */
trait VfsFileTestTrait {

  /**
   * Converts a VFS file path to a public:// URI for tests.
   *
   * @param string $filePath
   *   The VFS file path to convert.
   *
   * @return string|null
   *   The public:// URI for tests, or NULL if not a VFS path.
   */
  protected function convertVfsPathToPublicUri(string $filePath): ?string {
    // Handle VFS paths used in Drupal kernel tests.
    if (str_starts_with($filePath, '/vfs:') || str_starts_with($filePath, 'vfs:')) {
      // Extract the path after the test files directory.
      if (preg_match('|(vfs://root/sites/simpletest/\d+/files/)(.*)$|', $filePath, $matches)) {
        return 'public://' . $matches[2];
      }
      elseif (preg_match('|/vfs://root/sites/simpletest/\d+/files/(.*)$|', $filePath, $matches)) {
        return 'public://' . $matches[1];
      }
      // If we can identify this is a VFS path but can't parse it properly,
      // still allow it in test environments.
      elseif (defined('DRUPAL_TEST_IN_CHILD_SITE') && DRUPAL_TEST_IN_CHILD_SITE) {
        return 'public://' . basename($filePath);
      }
    }

    // Handle standard web paths that are typically used in tests.
    if (str_starts_with($filePath, '/sites/default/files/')) {
      $relativePath = substr($filePath, strlen('/sites/default/files/'));
      return 'public://' . $relativePath;
    }

    // If it's a URL with the standard Drupal files path.
    if (str_contains($filePath, '/sites/default/files/')) {
      $parts = explode('/sites/default/files/', $filePath);
      if (isset($parts[1])) {
        return 'public://' . $parts[1];
      }
    }

    // If it's just a filename, treat it as public://filename.
    if (!str_contains($filePath, '/') && !str_contains($filePath, '\\')) {
      return 'public://' . $filePath;
    }

    return NULL;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc