/** * {@inheritdoc} */ public function saveFile(UploadedFile $uploadedFile, $fileName) { $stream = fopen($uploadedFile->getRealPath(), 'r+'); $result = $this->filesystem->writeStream($this->getMediaBasePath() . '/' . $fileName . '.' . $uploadedFile->guessClientExtension(), $stream); fclose($stream); return $result; }
public function writeStream($path, $resource) { try { return $this->filesystem->writeStream($path, $resource); } catch (FileExistsException $exception) { return $this->filesystem->updateStream($path, $resource); } }
/** * 1.txt * 2.txt. */ public function testWriteStream() { $stream = tmpfile(); fwrite($stream, 'OSS text'); rewind($stream); $this->assertTrue($this->filesystem->writeStream('2.txt', $stream)); fclose($stream); }
function it_should_successfully_update_stream($path, Filesystem $filesystem) { $filesystem->writeStream($path, 'resource2')->willThrow('League\\Flysystem\\FileExistsException'); $filesystem->updateStream($path, 'resource2')->willReturn(true); $this->writeStream($path, 'resource2'); $filesystem->writeStream($path, 'resource2')->shouldBeCalled(); $filesystem->updateStream($path, 'resource2')->shouldBeCalled(); }
/** * {@inheritdoc} */ public function persist(File $file) : bool { // only write temporary, i.e. not yet persisted files, to backend file storage if ($file->isTmpFile()) { // use streams for writing to backend file storage $stream = fopen($file->getTmpPathname(), 'r+'); return $this->filesystem->writeStream($file->getKey(), $stream); } return true; }
/** * @param string $fileName * @return bool */ public function uploadFile($fileName) { if (true === $this->fileExists($fileName)) { $fileStream = $this->openFile($fileName, 'r'); $result = $this->fileSystem->writeStream($this->getFileNameFromPath($fileName), $fileStream); $this->closeFile($fileStream); return false !== $result; } return false; }
/** * @param array $fileList */ public function store(array $fileList) { foreach ($fileList as $file) { $this->logger->notice('Storing ' . $file . ' in s3 bucket ' . $this->filesystem->getAdapter()->getBucket()); try { $stream = fopen($file, 'r'); $this->filesystem->writeStream($this->getStoredFilename($file), $stream, ['visibility' => AdapterInterface::VISIBILITY_PRIVATE]); } catch (\Exception $e) { $this->logger->error('Exception while storing ' . $file . ': ' . $e->getMessage()); } if (isset($stream) && is_resource($stream)) { fclose($stream); } } }
function it_should_execute_the_transfer_file_command(Filesystem $source, Filesystem $destination) { $source->readStream('source')->willReturn('data'); $destination->writeStream('destination', 'data')->shouldBeCalled(); $this->beConstructedWith($source, 'source', $destination, 'destination'); $this->execute(); }
/** * @expectedException InvalidArgumentException */ public function testWriteStreamFail() { $adapter = Mockery::mock('League\\Flysystem\\AdapterInterface'); $adapter->shouldReceive('has')->andReturn(false); $filesystem = new Filesystem($adapter); $filesystem->writeStream('file.txt', 'not a resource'); }
/** * Saves the file with a unique file name. * * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file * @param string $directory what subdirectory to upload the file into * @return mixed If the Flysystem transfer succeeded, returns the final * file name used. */ public function handle(UploadedFile $file = null, $directory = null) { if (null == $file) { return null; } $stream = fopen($file->getRealPath(), 'r+'); $this->fileNameGenerator->setFilename($file->getClientOriginalName()); if (null === $directory) { $directory = ''; } do { $filename = $this->fileNameGenerator->nextName(); } while ($this->flysystem->has($directory . $filename)); // TODO error not being handled $result = $this->flysystem->writeStream($directory . $filename, $stream); return $filename; }
/** * Write a new file using a stream. * * @param string $path The path of the new file. * @param resource $resource The file handle. * @param array $config An optional configuration array. * * @throws InvalidArgumentException If $resource is not a file handle. * @throws FileExistsException * * @return bool True on success, false on failure. */ public function writeStream($path, $resource, array $config = []) { $result = parent::writeStream($path, $resource, $config); if ($result && ($resource = $this->get($path))) { return $this->dispatch(new SyncFile($resource)); } return $result; }
/** * {@inheritdoc} */ public function backup(Filesystem $source, Filesystem $destination, Database $database, array $parameter) { $this->output->writeln(' * <comment>export "' . $parameter['path'] . '" to "export.xml"</comment>'); $tempfile = $this->temporaryFileSystem->createTemporaryFile('jackrabbit'); $stream = fopen($tempfile, 'w+'); $this->export($this->getSession($parameter), $parameter['path'], $stream); fclose($stream); $destination->writeStream('export.xml', fopen($tempfile, 'r')); }
function it_throws_an_exception_if_the_file_already_exists_on_the_filesystem($mountManager, $factory, \SplFileInfo $rawFile, Filesystem $fs, FileInfoInterface $fileInfo) { $rawFile->getPathname()->willReturn(__FILE__); $fs->has(Argument::any())->willReturn(true); $fs->writeStream(Argument::any(), Argument::any())->willThrow(new FileExistsException('The file exists.')); $mountManager->getFilesystem('destination')->willReturn($fs); $factory->createFromRawFile($rawFile, 'destination')->willReturn($fileInfo); $fileInfo->getKey()->willReturn('key-file'); $this->shouldThrow(new FileTransferException(sprintf('Unable to move the file "%s" to the "destination" filesystem.', __FILE__)))->during('store', [$rawFile, 'destination']); }
/** * Deploy files to the remote filesystem. * * @return void */ public function deployToRemote() { $local_path = $this->relativeDumpPath(); $files = $this->localAdapter->listContents($local_path); foreach ($files as $file) { $contents = $this->localAdapter->readStream($local_path . $file['basename']); $file_size = $this->localAdapter->getSize($local_path . $file['basename']); $this->out($this->parseString('Uploading %s (%s)', [$file['basename'], $this->formatBytes($file_size)], 'light_green')); $this->remoteAdapter->writeStream($local_path . $file['basename'], $contents); } }
/** * @return mixed */ public function doBackup() { $date = date('YmdHisO'); $dumpName = trim($this->options->getPath() . $date . '.sql', '/'); switch ($this->dumperOptions->getCompress()) { case Mysqldump::GZIP: $dumpName = $dumpName . '.gz'; break; case Mysqldump::BZIP2: $dumpName = $dumpName . '.bz2'; break; } $tmpFile = tempnam(sys_get_temp_dir(), 'bsb-flysystem-mysql-backup-'); $fileStream = fopen($tmpFile, 'rb'); try { if (false === $fileStream) { throw new \RuntimeException("A temp file could not be created"); } // start dump and backup $this->dumper->start($tmpFile); $this->filesystem->writeStream($dumpName, $fileStream); // write a latest file if ($this->options->getWriteLatest()) { $this->filesystem->put($this->options->getPath() . $this->options->getWriteLatest(), pathinfo($dumpName, PATHINFO_BASENAME)); } if ($this->options->getAutoPrune()) { $this->pruneStorage(); } } catch (\Exception $e) { throw new \RuntimeException($e->getMessage()); } finally { if (is_resource($fileStream)) { fclose($fileStream); } if (file_exists($tmpFile)) { unlink($tmpFile); } } return $dumpName; }
/** * @inheritdoc */ public function writeStream($path, $resource, array $config = []) { $innerPath = $this->getInnerPath($path); try { $return = $this->fileSystem->writeStream($innerPath, $resource, $config); } catch (FileExistsException $e) { throw $this->exceptionWrapper($e, $path); } if ($return !== false) { $this->invokePlugin("addPathToIndex", [$path, $innerPath], $this); } return $return; }
public function do() { $this->io->writeln('Deploying via Codedeploy!'); $s3Client = new S3Client(['version' => 'latest', 'region' => 'us-east-1']); $adapter = new AwsS3Adapter($s3Client, $this->config->get('bucket')); $s3 = new Filesystem($adapter); $build_file = $this->config->get('build_path', getcwd() . '/build') . '/build.zip'; if (!file_exists($build_file)) { throw new \Exception('Could not find build file.'); } $stream = fopen($build_file, 'r+'); $fileMd5 = md5_file($build_file); $s3File = $this->config->get('AppName') . '/revisions/' . $fileMd5 . '.zip'; $s3->writeStream($s3File, $stream); $codedeploy = new CodeDeployClient(['region' => 'us-east-1', 'version' => 'latest']); $codedeploy->registerApplicationRevision(['applicationName' => $this->config->get('AppName'), 'revision' => ['revisionType' => 'S3', 's3Location' => ['bucket' => $this->config->get('bucket'), 'key' => $s3File, 'bundleType' => 'zip']]]); $codedeploy->createDeployment(['applicationName' => $this->config->get('AppName'), 'deploymentGroupName' => $this->config->get('AppName'), 'revision' => ['revisionType' => 'S3', 's3Location' => ['bucket' => $this->config->get('bucket'), 'key' => $s3File, 'bundleType' => 'zip']], 'ignoreApplicationStopFailures' => false]); }
/** * @param File[] $files * * @throws CanNotSavedException * * @return File[] */ public function save($files) { $fileSystemAdapter = $this->getAdapter(); $fileSystem = new Filesystem($fileSystemAdapter); $savedFiles = []; $i = 0; foreach ($files as $file) { $i++; $saveLocation = $this->fileNameResolver->resolve(new \DateTime('now', new \DateTimeZone('UTC')), 'database', $file->getExtension()); if ($fileSystem->has($saveLocation)) { $fileSystem->delete($saveLocation); } $stream = fopen($file->getPath(), 'r+'); $uploadFile = $fileSystem->writeStream($saveLocation, $stream); fclose($stream); if (!$uploadFile) { throw new CanNotSavedException(); } $savedFiles[] = new File($fileSystemAdapter->applyPathPrefix($saveLocation)); } return $savedFiles; }
public function writeStream($path, $resource, array $config = []) { try { return parent::writeStream($path, $resource, $config); } catch (\Exception $e) { $this->errors[] = $e->getMessage(); } return false; }
/** * {@inheritdoc} * * @throws FileExistsException * @throws \InvalidArgumentException * @throws FileNotFoundException * @throws LogicException */ public function restore(Filesystem $source, Filesystem $destination, ReadonlyDatabase $database, array $parameter) { // TODO make it smoother $files = $source->listFiles('', true); $progressBar = new ProgressBar($this->output, count($files)); $progressBar->setOverwrite(true); $progressBar->setFormat(' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%'); $progressBar->start(); foreach ($files as $file) { $path = $file['path']; $fullPath = $parameter['directory'] . '/' . $file['path']; if ($destination->has($fullPath)) { if ($destination->hash($fullPath) === $source->hash($path)) { $progressBar->advance(); continue; } $destination->delete($fullPath); } $destination->writeStream($fullPath, $source->readStream($path)); $progressBar->advance(); } $progressBar->finish(); }
public function testWriteStreamInvalid() { $this->setExpectedException('InvalidArgumentException'); $this->filesystem->writeStream('path.txt', '__INVALID__'); }
/** @inheritdoc */ public function import($request) { $_from = null; $_instance = $request->getInstance(); $_mount = $_instance->getStorageMount(); $this->info('[provisioning:storage:import] instance "' . $_instance->instance_id_text . '" begin'); // Grab the target (zip archive) and pull out the target of the import $_zip = $request->getTarget(); /** @var \ZipArchive $_archive */ /** @noinspection PhpUndefinedMethodInspection */ $_archive = $_zip->getAdapter()->getArchive(); $_path = null; foreach ($_zip->listContents() as $_file) { if ('dir' != $_file['type'] && false !== strpos($_file['path'], '.storage.zip')) { $_from = Disk::segment([sys_get_temp_dir(), 'dfe', 'import', sha1($_file['path'])], true); if (!$_archive->extractTo($_from, $_file['path'])) { throw new \RuntimeException('Unable to unzip archive file "' . $_file['path'] . '" from snapshot.'); } $_path = Disk::path([$_from, $_file['path']], false); if (!$_path || !file_exists($_path)) { throw new \InvalidArgumentException('$from file "' . $_file['path'] . '" missing or unreadable.'); } $_from = new Filesystem(new ZipArchiveAdapter($_path)); break; } } if (!$_mount instanceof Filesystem) { $_mount = new Filesystem(new ZipArchiveAdapter($_mount)); } // If "clean" == true, storage is wiped clean before restore if (true === $request->get('clean', false)) { $_mount->deleteDir('./'); } // Extract the files $_restored = []; /** @type Filesystem $_archive */ foreach ($_from->listContents() as $_file) { $_filename = $_file['path']; if ('dir' == array_get($_file, 'type')) { $_mount->createDir($_filename); } else { $_mount->writeStream($_filename, $_archive->readStream($_filename)); } $_restored[] = $_file; } unset($_from); $_path && is_dir(dirname($_path)) && Disk::deleteTree(dirname($_path)); // Fire off a "storage.imported" event... \Event::fire('dfe.storage.imported', [$this, $request]); $this->info('[provisioning:storage:import] instance "' . $_instance->instance_id_text . '" complete'); return $_restored; }
/** * @throws \InvalidArgumentException */ public function execute() { $this->destinationFilesystem->writeStream($this->destinationPath, $this->sourceFilesystem->readStream($this->sourcePath)); }
public function writeFile($directory, $file) { $stream = fopen($file->getRealPath(), 'r+'); $this->flysystem->writeStream($directory . '/' . $file->getClientOriginalName(), $stream); fclose($stream); }