setFilename example


  protected function createOrUpdate(string $uri, string $destination, bool $rename): FileInterface {
    $file = $this->loadByUri($uri);
    if ($file === NULL) {
      $file = File::create(['uri' => $uri]);
      $file->setOwnerId($this->currentUser->id());
    }

    if ($rename && is_file($destination)) {
      $file->setFilename($this->fileSystem->basename($destination));
    }

    $file->setPermanent();
    $file->save();

    return $file;
  }

  /** * {@inheritdoc} */
  
// Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($owner->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();

    $this->image = File::create();
    $this->image->setFileUri('core/misc/druplicon.png');
    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    $this->image->setFilename($file_system->basename($this->image->getFileUri()));

    $this->nonImage = File::create();
    $this->nonImage->setFileUri('core/assets/vendor/jquery/jquery.min.js');
    $this->nonImage->setFilename($file_system->basename($this->nonImage->getFileUri()));
  }

  /** * Tests the file_validate_extensions() function. */
  public function testFileValidateExtensions() {
    $file = File::create(['filename' => 'asdf.txt']);
    
if ($destinationFilename === FALSE) {
      throw new FileExistsException(sprintf('Destination file "%s" exists', $destinationFilename));
    }

    $file = File::create([
      'uid' => $this->currentUser->id(),
      'status' => 0,
      'uri' => $uploadedFile->getRealPath(),
    ]);

    // This will be replaced later with a filename based on the destination.     $file->setFilename($filename);
    $file->setMimeType($mimeType);
    $file->setSize($uploadedFile->getSize());

    // Add in our check of the file name length.     $validators['file_validate_name_length'] = [];

    // Call the validation functions specified by this function's caller.     $errors = file_validate($file$validators);
    if (!empty($errors)) {
      throw new FileValidationException('File validation failed', $filename$errors);
    }

    
public function testEditorEntityHooks() {
    $image_paths = [
      0 => 'core/misc/druplicon.png',
      1 => 'core/misc/tree.png',
      2 => 'core/misc/help.png',
    ];

    $image_entities = [];
    foreach ($image_paths as $key => $image_path) {
      $image = File::create();
      $image->setFileUri($image_path);
      $image->setFilename(\Drupal::service('file_system')->basename($image->getFileUri()));
      $image->save();

      $file_usage = $this->container->get('file.usage');
      $this->assertSame([]$file_usage->listUsage($image), 'The image ' . $image_paths[$key] . ' has zero usages.');

      $image_entities[] = $image;
    }

    $body = [];
    $description = [];
    foreach ($image_entities as $key => $image_entity) {
      

function hook_file_copy(\Drupal\file\FileInterface $file, \Drupal\file\FileInterface $source) {
  // Make sure that the file name starts with the owner's user name.   if (!str_starts_with($file->getFilename()$file->getOwner()->name)) {
    $file->setFilename($file->getOwner()->name . '_' . $file->getFilename());
    $file->save();

    \Drupal::logger('file')->notice('Copied file %source has been renamed to %destination', ['%source' => $source->filename, '%destination' => $file->getFilename()]);
  }
}

/** * Respond to a file that has been moved. * * @param \Drupal\file\FileInterface $file * The updated file entity after the move. * @param \Drupal\file\FileInterface $source * The original file entity before the move. * * @see \Drupal\file\FileRepositoryInterface::move() */
if ($munge_everything) {
        $filename .= '_';
      }
      elseif (!empty($extensions) && !in_array(strtolower($filename_part)$extensions) && preg_match("/^[a-zA-Z]{2,5}\d?$/", $filename_part)) {
        $filename .= '_';
      }
    }
    if ($final_extension !== '') {
      $filename .= '.' . $final_extension;
    }
    if ($filename !== $event->getFilename()) {
      $event->setFilename($filename)->setSecurityRename();
    }
  }

}


    $GLOBALS['entity_crud_hook_test'] = [];
    $file = File::load($file->id());

    $this->assertHookMessageOrder([
      'entity_crud_hook_test_entity_load called for type file',
      'entity_crud_hook_test_file_load called',
    ]);

    $GLOBALS['entity_crud_hook_test'] = [];
    $file->setFilename('new.entity_crud_hook_test.file');
    $file->save();

    $this->assertHookMessageOrder([
      'entity_crud_hook_test_file_presave called',
      'entity_crud_hook_test_entity_presave called for type file',
      'entity_crud_hook_test_file_update called',
      'entity_crud_hook_test_entity_update called for type file',
    ]);

    $GLOBALS['entity_crud_hook_test'] = [];
    $file->delete();

    
$this->entity->save();
  }

  /** * {@inheritdoc} */
  protected function createEntity() {
    $this->author = User::load(1);

    $file = File::create();
    $file->setOwnerId($this->author->id());
    $file->setFilename('drupal.txt');
    $file->setMimeType('text/plain');
    $file->setFileUri('public://drupal.txt');
    $file->set('status', FileInterface::STATUS_PERMANENT);
    $file->save();

    file_put_contents($file->getFileUri(), 'Drupal');

    return $file;
  }

  /** * {@inheritdoc} */
// Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing.', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));

    $file->setFileUri($file_uri);
    $file->setSize(@filesize($temp_file_path));

    $violations = $this->validate($file$validators);
    if ($violations->count() > 0) {
      throw new UnprocessableEntityHttpException($violations->__toString());
    }

    try {
      
// Lock based on the prepared file URI.     $lock_id = $this->generateLockIdFromFileUri($file_uri);

    if (!$this->lock->acquire($lock_id)) {
      throw new HttpException(503, sprintf('File "%s" is already locked for writing', $file_uri), NULL, ['Retry-After' => 1]);
    }

    // Begin building file entity.     $file = File::create([]);
    $file->setOwnerId($this->currentUser->id());
    $file->setFilename($prepared_filename);
    $file->setMimeType($this->mimeTypeGuesser->guessMimeType($prepared_filename));
    $file->setFileUri($temp_file_path);
    // Set the size. This is done in File::preSave() but we validate the file     // before it is saved.     $file->setSize(@filesize($temp_file_path));

    // Validate the file against field-level validators first while the file is     // still a temporary file. Validation is split up in 2 steps to be the same     // as in \Drupal\file\Upload\FileUploadHandler::handleFileUpload().     // For backwards compatibility this part is copied from ::validate() to     // leave that method behavior unchanged.
/** * Write configuration to file. * * @param string $filename * @param bool $exclusiveLock * * @return void */
    public function write($filename = null, ?Enlight_Config $config = null, $exclusiveLock = null)
    {
        if ($filename !== null) {
            $this->setFilename($filename);
        }

        if ($config !== null) {
            $this->setConfig($config);
        }

        if ($exclusiveLock !== null) {
            $this->setExclusiveLock($exclusiveLock);
        }

        if ($this->_filename === null) {
            
protected $isSecurityRename = FALSE;

  /** * Constructs a file upload sanitize name event object. * * @param string $filename * The full filename (with extension, but not directory) being uploaded. * @param string $allowed_extensions * A list of allowed extensions. If empty all extensions are allowed. */
  public function __construct(string $filename, string $allowed_extensions) {
    $this->setFilename($filename);
    if ($allowed_extensions !== '') {
      $this->allowedExtensions = array_unique(explode(' ', trim(strtolower($allowed_extensions))));
    }
  }

  /** * Gets the filename. * * @return string * The filename. */
  

class FileUploadSanitizeNameEventTest extends UnitTestCase {

  /** * @covers ::setFilename * @covers ::getFilename */
  public function testSetFilename() {
    $event = new FileUploadSanitizeNameEvent('foo.txt', '');
    $this->assertSame('foo.txt', $event->getFilename());
    $event->setFilename('foo.html');
    $this->assertSame('foo.html', $event->getFilename());
  }

  /** * @covers ::setFilename */
  public function testSetFilenameException() {
    $event = new FileUploadSanitizeNameEvent('foo.txt', '');
    $this->assertSame('foo.txt', $event->getFilename());
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage('$filename must be a filename with no path information, "bar/foo.html" provided');
    
$ntfyOptions = (new NtfyOptions())
            ->setMessage('test message')
            ->setTitle('message title')
            ->setPriority(NtfyOptions::PRIORITY_URGENT)
            ->setTags(['tag1', 'tag2'])
            ->addTag('tag3')
            ->setDelay($delay)
            ->setActions([['action' => 'view', 'label' => 'View', 'url' => 'https://test.com']])
            ->addAction(['action' => 'http', 'label' => 'Open', 'url' => 'https://test2.com'])
            ->setClick('https://test3.com')
            ->setAttachment('https://filesrv.lan/space.jpg')
            ->setFilename('diskspace.jpg')
            ->setEmail('me@mail.com')
            ->setCache(false)
            ->setFirebase(false)
        ;

        $this->assertSame([
            'message' => 'test message',
            'title' => 'message title',
            'priority' => NtfyOptions::PRIORITY_URGENT,
            'tags' => ['tag1', 'tag2', 'tag3'],
            'delay' => (string) $delay->getTimestamp(),
            
Home | Imprint | This part of the site doesn't use cookies.