/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $verbose = $input->getOption('verbose'); foreach ($this->importerIterator as $importer) { if (null === $input->getArgument('source') || $input->getArgument('source') === $importer->getSource()) { $this->filesystem->mkdir($importerDir = $this->path . '/' . $importer->getSource()); foreach ($importer->getLanguages() as $language) { if (null === $input->getArgument('language') || $input->getArgument('language') === $language) { $this->filesystem->mkdir($exporterDir = $importerDir . '/' . $language); $countries = $importer->getCountries($language); if (!is_array($countries)) { continue; } foreach ($this->exporterIterator as $exporter) { if (null === $input->getArgument('format') || $input->getArgument('format') === $exporter->getFormat()) { $file = $exporterDir . '/country.' . $exporter->getFormat(); $this->filesystem->touch($file); file_put_contents($file, $exporter->export($countries)); if ($verbose) { $output->write('<info>[file+]</info> ' . $file . PHP_EOL); } } } } } } } }
/** * {@inheritdoc} */ public function createEmptyFile($basePath, $prefix = null, $suffix = null, $extension = null, $maxTry = 65536) { if (false === is_dir($basePath) || false === is_writeable($basePath)) { throw new IOException(sprintf('`%s` should be a writeable directory', $basePath)); } if ($suffix === null && $extension === null) { if (false === ($file = @tempnam($basePath, $prefix))) { throw new IOException('Unable to generate a temporary filename'); } return $file; } while ($maxTry > 0) { $file = $basePath . DIRECTORY_SEPARATOR . $prefix . base_convert(mt_rand(0x19a100, 0x39aa3ff), 10, 36) . $suffix . ($extension ? '.' . $extension : ''); if (false === file_exists($file)) { try { $this->filesystem->touch($file); } catch (SfIOException $e) { throw new IOException('Unable to touch file', $e->getCode(), $e); } return $file; } $maxTry--; } throw new IOException('Unable to generate a temporary filename'); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $verbose = $input->getOption('verbose'); foreach ($this->importerIterator as $importer) { if (null === $input->getArgument('source') || $input->getArgument('source') === $importer->getSource()) { $this->filesystem->mkdir($importerDir = sprintf('%s/%s', $this->path, $importer->getSource())); foreach ($importer->getLanguages() as $language) { if (null === $input->getArgument('language') || $input->getArgument('language') === $language) { $this->filesystem->mkdir($exporterDir = sprintf('%s/%s', $importerDir, $language)); $countries = $importer->getCountries($language); foreach ($this->exporterIterator as $exporter) { if (null === $input->getArgument('format') || $input->getArgument('format') === $exporter->getFormat()) { $file = sprintf('%s/country.%s', $exporterDir, $exporter->getFormat()); $this->filesystem->touch($file); file_put_contents($file, $exporter->export($countries)); if ($verbose) { $output->write(sprintf('<info>[file+]</info> %s%s', $file, PHP_EOL)); } } } } } } } }
/** * @param string $request * @param string $url * @param string $response */ public function set($request, $url, $response) { if ($expires = $this->getRequestExpires($request)) { $filename = $this->getFilename($url); $this->fs->dumpFile($filename, $response); $this->fs->touch($filename, $expires); } }
public function setUp() { $this->filesystem = new Filesystem(); $this->basePath = sys_get_temp_dir() . '/aWebRoot'; $this->existingFile = $this->basePath . '/aCachePrefix/aFilter/existingPath'; $this->filesystem->mkdir(dirname($this->existingFile)); $this->filesystem->touch($this->existingFile); }
/** * @param string $filename */ public function createFile($filename) { if ($this->fs->exists($filename)) { throw new Exception('File already exist'); } else { $this->fs->touch($filename); } }
/** * {@inheritdoc} */ public function open($savePath, $sessionName) { try { $this->fs->touch($this->getSessionFileName($sessionName)); return true; } catch (IOException $e) { return false; } }
/** * {@inheritdoc} */ public function touch($files, int $time = null, int $atime = null) { try { $this->filesystem->touch($files, $time, $atime); } catch (IOException $exception) { throw new FilesystemException($exception->getMessage(), $exception->getPath(), $exception); } catch (Exception $exception) { throw new FilesystemException($exception->getMessage(), null, $exception); } }
/** * @dataProvider getCleanFiles * * @param string $expected * @param string $filename * @param bool $is_dir */ public function testClean($expected, $filename, $is_dir = false) { if ($is_dir) { $this->fs->mkdir($this->root . $filename); } else { $this->fs->touch($this->root . $filename); } $file = new SplFileInfo($this->root . $filename, '', ''); $this->assertEquals($expected, $this->cleaner->clean($file)); }
public function testDumpMocksTo() { $targetPath = $this->createTempDir(); $this->filesystem->touch($targetPath . DIRECTORY_SEPARATOR . 'badfile'); $this->responseLogger->dumpMocksTo($targetPath); $this->assertTrue(is_file($targetPath . DIRECTORY_SEPARATOR . 'file')); $this->assertTrue(is_dir($targetPath . DIRECTORY_SEPARATOR . 'dir')); $this->assertTrue(!is_file($targetPath . DIRECTORY_SEPARATOR . 'badfile')); $this->filesystem->remove($targetPath); }
/** * Get a temporary file and populate its data * * Any files created with this function will be destroyed on cleanup/destruction. * * @param string $data Data to populate file with * @param string $prefix Optional file prefix * @return string */ protected function getTempFile($data = null, $prefix = 'img-mngr-') { $file = tempnam(sys_get_temp_dir(), $prefix); if ($data) { file_put_contents($file, $data); } else { $this->filesystem->touch($file); } $this->temp_files[] = $file; return $file; }
public function testReadFileNotValid() { $filename = $this->directory . DIRECTORY_SEPARATOR . 'not_valid.log'; $this->fs->touch($filename); $this->context->expects($this->once())->method('hasOption')->with($this->equalTo('file'))->will($this->returnValue(true)); $this->context->expects($this->once())->method('getOption')->will($this->returnValue($filename)); $this->contextRegistry->expects($this->exactly(3))->method('getByStepExecution')->will($this->returnValue($this->context)); $this->reader->setStepExecution($this->stepExecution); $this->assertNull($this->reader->read()); $this->assertNull($this->reader->read()); }
/** * @covers Kunstmaan\MediaBundle\Helper\Transformer\PdfTransformer::apply */ public function testApplyDoesNotOverwriteExisting() { $pdfFilename = $this->tempDir . '/sample.pdf'; $jpgFilename = $pdfFilename . '.jpg'; $pdf = $this->filesDir . '/sample.pdf'; $this->filesystem->copy($pdf, $pdfFilename); $this->assertTrue(file_exists($pdfFilename)); $this->filesystem->touch($jpgFilename); $transformer = new PdfTransformer(new \Imagick()); $absolutePath = $transformer->apply($pdfFilename); $this->assertEquals($jpgFilename, $absolutePath); $this->assertEmpty(file_get_contents($jpgFilename)); }
/** * @return array */ public function getArgs() { $this->filesystem->mkdir($this->getTemporaryPath()); $fileCount = rand(2, 10); $realFiles = rand(1, $fileCount - 1); $files = []; foreach (range(1, $fileCount) as $index) { $file = sprintf('%s/%s.txt', $this->getTemporaryPath(), $this->faker->uuid); if ($index <= $realFiles) { $this->filesystem->touch($file); } $files[] = $file; } return $files; }
protected function fillDirectory($number) { $system = new Filesystem(); for ($i = 0; $i < $number; $i++) { $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid()), time() - $i * 60); } }
/** * {@inheritdoc} */ public function updateTimestamp($sessionId, $data) { try { $this->fs->touch($this->getSessionFileName($sessionId)); } catch (IOException $e) { } }
protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $handle = new Filesystem(); $path = './' . $name; try { if ($handle->exists($path)) { // 抛出目录已存在错误 throw new IOException('Directory exists!'); } // 创建目录 $handle->mkdir(array($path . '/posts', $path . '/themes/default/css')); // 创建文件 $handle->touch(array($path . '/config.json', $path . '/posts/hello.md', $path . '/themes/default/index.tpl', $path . '/themes/default/post.tpl')); // 填充文件 $handle->dumpFile($path . '/config.json', 'hello world'); $handle->dumpFile($path . '/posts/hello.md', 'hello world'); $handle->dumpFile($path . '/themes/default/index.tpl', 'index-tpl'); $handle->dumpFile($path . '/themes/default/post.tpl', 'post-tpl'); } catch (IOException $exception) { // 创建项目失败处理异常 $output->writeln('failed!'); exit; } // 输出成功 $output->writeln('created!'); }
/** * @Route("/send", name="send_massage") * @Template() */ public function sendAction(Request $request) { // Check for empty fields if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { echo "No arguments Provided!"; echo 'false'; exit; } $name = $_POST['name']; $email_address = $_POST['email']; $phone = $_POST['phone']; $message = $_POST['message']; // Create the email and send the message $email_subject = "Website Contact Form: {$name} \n\n\n"; $email_body = $email_subject . "You have received a new message from your website contact form.\n\n" . "Here are the details:\n\nName: {$name}\n\nEmail: {$email_address}\n\nPhone: {$phone}\n\nMessage:\n{$message}"; $fs = new Filesystem(); $file = '/mail/' . mt_rand() . '.txt'; try { $fs->touch($file); $fs->dumpFile($file, $email_body); } catch (IOExceptionInterface $e) { echo "An error occurred while creating your directory at " . $e->getPath(); } echo 'true'; exit; }
protected function execute(InputInterface $input, OutputInterface $outputInterface) { $lockHandler = new LockHandler($this->getName()); if (!$lockHandler->lock()) { echo "Jiná instance commandu ještě běží!"; return false; } $filesystem = new Filesystem(); $files = ["http://placekitten.com/408/287", "http://placekitten.com/300/128", "http://placekitten.com/123/456", "http://placekitten.com/54/68", "http://foo.bar/123"]; foreach ($files as $key => $file) { try { $targetDir = "tmp/" . $key; $filesystem->mkdir($targetDir); $targetFile = $targetDir . "/" . $key . ".jpg"; $outputInterface->write("kopíruji " . $file . " do " . $targetFile . " - "); $filesystem->copy($file, $targetFile); } catch (IOException $e) { $outputInterface->writeln("Chyba " . $e->getMessage()); continue; } $outputInterface->writeln("OK!"); //Pro další příklad si ještě upravíme čas přístupu $accessDate = new DateTime(); $accessDate->sub(new DateInterval("P" . $key . "D")); $filesystem->touch($targetFile, $accessDate->format("U"), $accessDate->format("U")); } }
/** * @dataProvider findFilesProvider */ public function testFindFiles($resource, $excludes, $files, $expected) { // create directory/file $file = new Filesystem(); if (!$file->exists($this->getTmpDir())) { $file->mkdir($this->getTmpDir()); } if ($files > 0) { foreach (range(1, $files) as $i) { $file->touch($this->getTmpDir() . "/testFindFilesByDirectory{$i}"); } } $register = $this->createRegisterMock(); $directory = $this->util->getProperty($register, 'directory'); if (is_string($expected) && class_exists($expected)) { $this->setExpectedException($expected); } $finder = $this->util->invoke($directory, 'findFiles', $resource, $excludes); $results = array(); foreach ($finder as $file) { $results[] = (string) $file; } sort($results); // sort by file name $this->assertSame($expected, $results); }
public function process(ContainerBuilder $container) { $directory = $container->getParameter('inter_nations.type_jail.proxy_dir'); $fs = new Filesystem(); $fs->mkdir($directory); $fs->touch($directory . '/.keep'); }
/** * Tests if command pops a question whether to continue installation to * non-empty folder. After giving 'n' as answer, check that * folder contents are unmodified. */ public function testItAskQuestionWhenOutputDirectoryNotEmpty() { $wd = TESTING_DIR; $folder = 'ps1'; $outputDirectory = $wd . '/' . $folder; $this->fs->mkdir($outputDirectory); $this->fs->touch($outputDirectory . '/test.txt'); $this->fs->dumpFile($outputDirectory . '/index.php', 'test'); $client = $this->getMockClient(['https://api.prestashop.com/xml/channel.xml' => TESTS_DIR . '/assets/xml/channel.xml', 'http://www.prestashop.com/download/releases/prestashop_1.6.1.4.zip' => TESTS_DIR . '/assets/zip/prestashop_1.6.1.4.zip']); $app = new Application('PrestaShop Installer', 'x.x.x'); $newCommand = new NewCommand($client, null, $wd); $app->add($newCommand); $helper = $newCommand->getHelper('question'); $helper->setInputStream($this->getInputStream('n\\n')); $commandTester = new CommandTester($newCommand); $commandTester->execute(['folder' => $folder, '--release' => '1.6.1.4']); $output = $commandTester ? $commandTester->getDisplay() : ''; // Asks question? $this->assertRegExp('/\\[y\\/n\\]\\?/i', $output); // Informs which directory is not empty? $this->assertTrue(strpos($output, $outputDirectory) !== false); // Has contextual question? $this->assertRegExp('/(not empty|contains)/i', $output); $this->assertRegExp('/(would you|do you|anyway)/i', $output); // $this->assertRegExp('/overwrite/i', $output); // Stub files remained? $this->assertTrue($this->fs->exists($outputDirectory)); $this->assertTrue($this->fs->exists($outputDirectory . '/test.txt')); $this->assertTrue($this->fs->exists($outputDirectory . '/index.php')); // File contents unmodified? $this->assertTrue(file_get_contents($outputDirectory . '/index.php') == 'test'); // No new files exist? $this->assertTrue(count(scandir($outputDirectory)) === 4); }
/** * @param SplFileInfo[] $sources * @param SplFileInfo[] $destinations * @return array|SplFileInfo[] */ public function run(array $sources, array $destinations) { $fileSystem = new Filesystem(); $mergedFiles = []; foreach ($this->getSupportedExtensions() as $extension) { $shouldAddMergeFile = false; $mergedFile = $this->getCacheDir() . 'merged.' . $extension; foreach ($sources as $source) { if ($source->getExtension() !== $extension) { continue; } // creating the merge file if not exists if (!$fileSystem->exists($mergedFile)) { $this->addNotification('creating ' . $mergedFile . ' merged file'); $fileSystem->touch($mergedFile); } $this->addNotification('merging file ' . $source); // append the current content to the merge file file_put_contents($mergedFile, file_get_contents($source), FILE_APPEND); $shouldAddMergeFile = true; } if ($shouldAddMergeFile) { $mergedFiles[] = $mergedFile; } } return $mergedFiles; }
private function composerUpdate(OutputInterface $output, KernelInterface $kernel) { $fs = new Filesystem(); $thirdPartyDir = $kernel->getRootDir() . '/../thirdparty'; $composerFile = $thirdPartyDir . '/' . str_replace(array('-', '/'), '_', $this->packageData[$this->packageName]['name']) . '.json'; if (!$fs->exists($composerFile)) { if (!$fs->exists($thirdPartyDir)) { $fs->mkdir($thirdPartyDir); } $fs->touch($composerFile); } file_put_contents($composerFile, str_replace(' ', ' ', json_encode($this->packageData[$this->packageName], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) . "\n"); $install = new Process('php composer.phar update', $kernel->getRootDir() . '/..', null, null, 600); $install->setPty(true); try { $install->mustRun(); $output->writeln($install->getOutput()); } catch (ProcessFailedException $e) { $output->writeln($e->getMessage()); } if ($install->isSuccessful()) { $output->writeln('<info>Packages succesfully installed</info>'); } else { $output->writeln('<error>Packages installation failed</error>'); } }
public static function createRequiredFiles(Event $event) { $fs = new Filesystem(); $root = static::getDrupalRoot(getcwd()); $dirs = ['modules', 'profiles', 'themes']; // Required for unit testing foreach ($dirs as $dir) { if (!$fs->exists($root . '/' . $dir)) { $fs->mkdir($root . '/' . $dir); $fs->touch($root . '/' . $dir . '/.gitkeep'); } } // Prepare the settings file for installation if (!$fs->exists($root . '/sites/default/settings.php')) { $fs->copy($root . '/sites/default/default.settings.php', $root . '/sites/default/settings.php'); $fs->chmod($root . '/sites/default/settings.php', 0666); $event->getIO()->write("Create a sites/default/settings.php file with chmod 0666"); } // Prepare the services file for installation if (!$fs->exists($root . '/sites/default/services.yml')) { $fs->copy($root . '/sites/default/default.services.yml', $root . '/sites/default/services.yml'); $fs->chmod($root . '/sites/default/services.yml', 0666); $event->getIO()->write("Create a sites/default/services.yml file with chmod 0666"); } // Create the files directory with chmod 0777 if (!$fs->exists($root . '/sites/default/files')) { $oldmask = umask(0); $fs->mkdir($root . '/sites/default/files', 0777); umask($oldmask); $event->getIO()->write("Create a sites/default/files directory with chmod 0777"); } }
public function testTouchCreatesEmptyFilesFromTraversableObject() { $basePath = $this->workspace . DIRECTORY_SEPARATOR; $files = new \ArrayObject(array($basePath . '1', $basePath . '2', $basePath . '3')); $this->filesystem->touch($files); $this->assertFileExists($basePath . '1'); $this->assertFileExists($basePath . '2'); $this->assertFileExists($basePath . '3'); }
/** * Creates named temporary file * * @param $fileName * @param bool $preserve * @return \SplFileInfo * @throws \Exception */ public function createFile($fileName, $preserve = false) { $this->initRunFolder(); $fileInfo = new \SplFileInfo($this->tmpRunFolder . DIRECTORY_SEPARATOR . $fileName); $this->filesystem->touch($fileInfo); $this->files[] = array('file' => $fileInfo, 'preserve' => $preserve); $this->filesystem->chmod($fileInfo, 0600); return $fileInfo; }
protected function setUp() { $this->legacy = isset($_SERVER['LEGACY_TESTS']) ? (bool) $_SERVER['LEGACY_TESTS'] : false; $this->workspace = sys_get_temp_dir() . DIRECTORY_SEPARATOR . uniqid(); $fs = new Filesystem(); $fs->mkdir($this->workspace . '/bar'); $fs->touch($this->workspace . '/foo.txt'); $fs->touch($this->workspace . '/bar/foo.txt'); $fs->touch($this->workspace . '/bar/.hidden'); if (!$this->legacy) { MongoGridTestHelper::getGridFS()->storeBytes('', array('filename' => $this->workspace, 'type' => 'dir')); MongoGridTestHelper::getGridFS()->storeBytes('', array('filename' => $this->workspace . '/bar', 'type' => 'dir')); MongoGridTestHelper::getGridFS()->storeFile($this->workspace . '/foo.txt', array('type' => 'file')); MongoGridTestHelper::getGridFS()->storeFile($this->workspace . '/bar/foo.txt', array('type' => 'file')); MongoGridTestHelper::getGridFS()->storeFile($this->workspace . '/bar/.hidden', array('type' => 'file')); $fs->remove($this->workspace); } }
/** * Load meta file */ protected function loadMetadata() { if (!file_exists($this->base . '/meta.json')) { $this->fs->touch($this->base . '/meta.json'); $this->fs->dumpFile($this->base . '/meta.json', []); } $meta = file_get_contents($this->base . '/meta.json'); $this->meta = json_decode($meta, true); }
private function init() { if (!file_exists($this->params['path'])) { $filesystem = new Filesystem(); $filesystem->touch($this->params['path']); chmod($this->params['path'], 0777); } $query = 'CREATE TABLE IF NOT EXISTS blender(id INTEGER PRIMARY KEY ASC, md5 TEXT UNIQUE);'; $this->conn->executeQuery($query); }