getFilename example



  /** * This will ensure the filename length is valid. */
  public function testFileValidateNameLength() {
    // Create a new file entity.     $file = File::create();

    // Add a filename with an allowed length and test it.     $file->setFilename(str_repeat('x', 240));
    $this->assertEquals(240, strlen($file->getFilename()));
    $errors = file_validate_name_length($file);
    $this->assertCount(0, $errors, 'No errors reported for 240 length filename.');

    // Add a filename with a length too long and test it.     $file->setFilename(str_repeat('x', 241));
    $errors = file_validate_name_length($file);
    $this->assertCount(1, $errors, 'An error reported for 241 length filename.');

    // Add a filename with an empty string and test it.     $file->setFilename('');
    $errors = file_validate_name_length($file);
    

function drupal_phpunit_find_extension_directories($scan_directory) {
  $extensions = [];
  $dirs = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($scan_directory, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS));
  foreach ($dirs as $dir) {
    if (str_contains($dir->getPathname(), '.info.yml')) {
      // Cut off ".info.yml" from the filename for use as the extension name. We       // use getRealPath() so that we can scan extensions represented by       // directory aliases.       $extensions[substr($dir->getFilename(), 0, -9)] = $dir->getPathInfo()
        ->getRealPath();
    }
  }
  return $extensions;
}

/** * Returns directories under which contributed extensions may exist. * * @param string $root * (optional) Path to the root of the Drupal installation. * * @return array * An array of directories under which contributed extensions may exist. */

    public function getAttachment(MediaEntity $media, Context $context): array
    {
        $fileBlob = '';
        $mediaService = $this;
        $context->scope(Context::SYSTEM_SCOPE, static function DContext $context) use ($mediaService$media, &$fileBlob): void {
            $fileBlob = $mediaService->loadFile($media->getId()$context);
        });

        return [
            'content' => $fileBlob,
            'fileName' => $media->getFilename() . '.' . $media->getFileExtension(),
            'mimeType' => $media->getMimeType(),
        ];
    }

    private function getMediaDefaultFolderId(string $folder, Context $context): ?string
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('media_folder.defaultFolder.entity', $folder));
        $criteria->addAssociation('defaultFolder');
        $criteria->setLimit(1);
        $defaultFolder = $this->mediaFolderRepository->search($criteria$context);
        
return FALSE;
  }

  /** * {@inheritdoc} */
  public function listAll() {
    $names = [];
    if (file_exists($this->directory)) {
      foreach (new \DirectoryIterator($this->directory) as $fileinfo) {
        if (!$fileinfo->isDot()) {
          $name = $fileinfo->getFilename();
          if ($name != '.htaccess') {
            $names[] = $name;
          }
        }
      }
    }
    return $names;
  }

  /** * {@inheritdoc} */
return $errors;
    }

    private function createScripts(): void
    {
        $finder = (new Finder())
            ->files()
            ->in(__DIR__ . '/Scripts')
            ->name('*.groovy');

        foreach ($finder as $file) {
            $name = pathinfo($file->getFilename(), \PATHINFO_FILENAME);

            $this->client->putScript([
                'id' => $name,
                'body' => [
                    'script' => [
                        'lang' => 'painless',
                        'source' => file_get_contents($file->getPathname()),
                    ],
                ],
            ]);
        }
    }

    public function setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '')static
    {
        if ('' === $filename) {
            $filename = $this->file->getFilename();
        }

        if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || str_contains($filename, '%'))) {
            $encoding = mb_detect_encoding($filename, null, true) ?: '8bit';

            for ($i = 0, $filenameLength = mb_strlen($filename$encoding)$i < $filenameLength; ++$i) {
                $char = mb_substr($filename$i, 1, $encoding);

                if ('%' === $char || \ord($char) < 32 || \ord($char) > 126) {
                    $filenameFallback .= '_';
                } else {
                    
if (!file_exists($this->root)) {
            return false;
        }

        /** @var SplFileInfo $file */
        foreach ($this->createRecursiveFileIterator($this->root) as $file) {
            if (!$file->isFile()) {
                continue;
            }

            // skip .gitkeep             if ($file->getFilename() === '.gitkeep') {
                continue;
            }

            unlink($file->getPathname());
        }

        return true;
    }

    /** * Purges data for the given Header. * * @param string $name * @param string|null $value * * @return bool */
/** * Resolves the passed directory to a theme class. * Returns a new instance of the \Shopware\Theme * * @throws Exception * * @return Theme */
    public function getThemeByDirectory(DirectoryIterator $directory)
    {
        $namespace = 'Shopware\\Themes\\' . $directory->getFilename();
        /** @var class-string<Theme> $class */
        $class = $namespace . '\\Theme';

        $file = $directory->getPathname() . DIRECTORY_SEPARATOR . 'Theme.php';

        if (!file_exists($file)) {
            throw new Exception(sprintf('Theme directory %s contains no Theme.php', $directory->getPathname()));
        }

        require_once $file;

        

        return $this->name.'.php';
    }

    public function build(): string
    {
        $rootPath = explode(\DIRECTORY_SEPARATOR, $this->getDirectory());
        $require = '';
        foreach ($this->require as $class) {
            // figure out relative path.             $path = explode(\DIRECTORY_SEPARATOR, $class->getDirectory());
            $path[] = $class->getFilename();
            foreach ($rootPath as $key => $value) {
                if ($path[$key] !== $value) {
                    break;
                }
                unset($path[$key]);
            }
            $require .= sprintf('require_once __DIR__.\DIRECTORY_SEPARATOR.\'%s\';', implode('\'.\DIRECTORY_SEPARATOR.\'', $path))."\n";
        }
        $use = $require ? "\n" : '';
        foreach (array_keys($this->use) as $statement) {
            $use .= sprintf('use %s;', $statement)."\n";
        }
// Create a new node with the uploaded file.     $nid = $this->uploadNodeFile($test_file$field_name$type_name);

    // Load the node and the file.     $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $file = File::load($node->{$field_name}->target_id);

    // Generate and test sanitized tokens.     $tests = [];
    $tests['[file:fid]'] = $file->id();
    $tests['[file:name]'] = Html::escape($file->getFilename());
    $tests['[file:path]'] = Html::escape($file->getFileUri());
    $tests['[file:mime]'] = Html::escape($file->getMimeType());
    $tests['[file:size]'] = format_size($file->getSize());
    $tests['[file:url]'] = Html::escape($file->createFileUrl(FALSE));
    $tests['[file:created]'] = $date_formatter->format($file->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
    $tests['[file:created:short]'] = $date_formatter->format($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
    $tests['[file:changed]'] = $date_formatter->format($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
    $tests['[file:changed:short]'] = $date_formatter->format($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
    $tests['[file:owner]'] = Html::escape($this->adminUser->getDisplayName());
    $tests['[file:owner:uid]'] = $file->getOwnerId();

    
private $mediaType;
    private $cid;

    /** * @param resource|string|File $body Use a File instance to defer loading the file until rendering */
    public function __construct($body, string $filename = null, string $contentType = null, string $encoding = null)
    {
        unset($this->_parent);

        if ($body instanceof File && !$filename) {
            $filename = $body->getFilename();
        }

        $contentType ??= $body instanceof File ? $body->getContentType() : 'application/octet-stream';
        [$this->mediaType, $subtype] = explode('/', $contentType);

        parent::__construct($body, null, $subtype$encoding);

        if (null !== $filename) {
            $this->filename = $filename;
            $this->setName($filename);
        }
        
new \RecursiveCallbackFilterIterator(
                new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
                fn (\SplFileInfo $current) => !str_starts_with($current->getBasename(), '.')
            ),
            \RecursiveIteratorIterator::SELF_FIRST
        ));
        usort($filesfn (\SplFileInfo $a, \SplFileInfo $b) => (string) $a > (string) $b ? 1 : -1);

        /** @var \SplFileInfo $file */
        foreach ($files as $file) {
            if ($file->isDir()) {
                $collection->addCollection($this->loadFromDirectory($file->getPathname()$psr4Prefix.'\\'.$file->getFilename()));

                continue;
            }
            if ('php' !== $file->getExtension() || !class_exists($className = $psr4Prefix.'\\'.$file->getBasename('.php')) || (new \ReflectionClass($className))->isAbstract()) {
                continue;
            }

            $collection->addCollection($this->import($className, 'attribute'));
        }

        return $collection;
    }
UploadedFile $file,
        string $sourceEntity,
        string $delimiter = ';',
        string $enclosure = '"',
        string $escape = '\\'
    ): MappingCollection {
        if ($this->fileService->detectType($file) !== 'text/csv') {
            throw new UnexpectedFileTypeException($file->getClientMimeType(), 'text/csv');
        }

        if ($file->getSize() < 1) {
            throw new FileEmptyException($file->getFilename());
        }

        $filePath = $file->getRealPath();
        if (!$filePath) {
            throw new \RuntimeException('File does not exists');
        }

        $fileHandle = fopen($filePath, 'rb');
        if (!$fileHandle) {
            throw new FileNotReadableException($filePath);
        }

        

    }

    private function createStreamedResponse(MediaEntity $media, SalesChannelContext $context): StreamedResponse
    {
        $stream = $context->getContext()->scope(
            Context::SYSTEM_SCOPE,
            fn (Context $context): StreamInterface => $this->mediaService->loadFileStream($media->getId()$context)
        );

        if (!$stream instanceof StreamInterface) {
            throw MediaException::fileNotFound($media->getFilename() . '.' . $media->getFileExtension());
        }

        $stream = $stream->detach();

        if (!\is_resource($stream)) {
            if (!Feature::isActive('v6.6.0.0')) {
                throw new FileNotFoundException($media->getFilename() . '.' . $media->getFileExtension());
            }

            throw MediaException::fileNotFound($media->getFilename() . '.' . $media->getFileExtension());
        }

        
return $this->get('events')->filter('Shopware_Theme_Listing_Query_Created', $builder);
    }

    /** * Helper function to decompress zip files. * * @throws Exception */
    private function unzip(UploadedFile $file, string $targetDirectory): void
    {
        $filePath = $file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename();
        $zipUtils = ZipUtils::openZip($filePath);
        $zipUtils->extractTo($targetDirectory);
    }

    /** * Helper function which checks if the passed template * or the inheritance templates has configuration sets. */
    private function hasTemplateConfigSet(Template $template): bool
    {
        $theme = $this->get(Util::class)->getThemeByTemplate($template);

        
Home | Imprint | This part of the site doesn't use cookies.