/** * @param FileInterface $file */ protected function guardFileExists(FileInterface $file) { $location = $file->getPath(); if (!$this->filesystem->exists($location)) { throw new \RuntimeException('File does not exist: ' . $location); } }
/** * @override \ComponentManager\Step\Step * * @param \ComponentManager\Task\InstallTask $task */ public function execute($task, LoggerInterface $logger) { $resolvedComponentVersions = $task->getResolvedComponentVersions(); foreach ($resolvedComponentVersions as $resolvedComponentVersion) { $logger->info('Installing component', ['component' => $resolvedComponentVersion->getComponent()->getName(), 'packageRepository' => $resolvedComponentVersion->getPackageRepository()->getName(), 'version' => $resolvedComponentVersion->getVersion()->getVersion(), 'release' => $resolvedComponentVersion->getVersion()->getRelease()]); $projectLockFile = $this->project->getProjectLockFile(); $component = $resolvedComponentVersion->getComponent(); $packageSource = $this->project->getPackageSource($resolvedComponentVersion->getSpecification()->getPackageSource()); $typeDirectory = $this->moodle->getPluginTypeDirectory($component->getPluginType()); $targetDirectory = $this->platform->joinPaths([$typeDirectory, $component->getPluginName()]); $tempDirectory = $this->platform->createTempDirectory(); $sourceDirectory = $packageSource->obtainPackage($tempDirectory, $resolvedComponentVersion, $this->filesystem, $logger); if ($resolvedComponentVersion->getFinalVersion() === null) { $logger->warning('Package source did not indicate final version; defaulting to desired version', ['version' => $resolvedComponentVersion->getVersion()->getVersion()]); $resolvedComponentVersion->setFinalVersion($resolvedComponentVersion->getVersion()->getVersion()); } $logger->debug('Downloaded component source', ['packageSource' => $packageSource->getName(), 'sourceDirectory' => $sourceDirectory]); if ($this->filesystem->exists($targetDirectory)) { $logger->info('Component directory already exists; removing', ['targetDirectory' => $targetDirectory]); $this->filesystem->remove($targetDirectory); } $logger->info('Copying component source to Moodle directory', ['sourceDirectory' => $sourceDirectory, 'targetDirectory' => $targetDirectory]); $this->filesystem->mirror($sourceDirectory, $targetDirectory); $logger->info('Pinning component at installed final version', ['finalVersion' => $resolvedComponentVersion->getFinalVersion()]); $projectLockFile->addResolvedComponentVersion($resolvedComponentVersion); $logger->info('Cleaning up after component installation', ['tempDirectory' => $tempDirectory]); try { $this->filesystem->chmod([$tempDirectory], 0750, 00, true); $this->filesystem->remove([$tempDirectory]); } catch (IOException $e) { $logger->warning('Unable to clean up temporary directory', ['code' => $e->getCode(), 'message' => $e->getMessage(), 'tempDirectory' => $tempDirectory]); } } }
/** * @return void */ public static function prepareSharedFolders(array $paths = array()) { if (empty($paths)) { return false; } $fs = new Filesystem(); $releaseRoot = dirname(dirname(dirname(dirname(__FILE__)))) . '/'; // Current version root $root = dirname(dirname($releaseRoot)); $sharedDirectory = $root . '/shared/'; // Create the shared directory first (if it does not exists) if (!$fs->exists($sharedDirectory)) { $fs->mkdir($sharedDirectory, 0777); } foreach ($paths as $path) { $pathDirectory = $releaseRoot . $path; $sharedPathDirectory = $sharedDirectory . $path; if (!$fs->exists($sharedPathDirectory)) { $fs->mkdir($sharedPathDirectory, 0777); } $pathDirectoryTmp = $pathDirectory . '_tmp'; // Symlink it per hand exec("ln -f -s {$sharedPathDirectory} {$pathDirectoryTmp}"); exec("rm -rf {$pathDirectory}"); exec("mv -Tf {$pathDirectoryTmp} {$pathDirectory}"); // $fs->symlink($pathDirectory, $sharedPathDirectory, true); } }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $pathToIlios2 = $input->getArgument('pathToIlios2'); if (!$this->symfonyFileSystem->exists($pathToIlios2)) { throw new \Exception("'{$pathToIlios2}' does not exist."); } $learningMaterials = $this->learningMaterialManager->findFileLearningMaterials(); $helper = $this->getHelper('question'); $output->writeln(''); $question = new ConfirmationQuestion('<question>Ready to copy ' . count($learningMaterials) . ' learning materials. Shall we continue? </question>' . "\n", true); if ($helper->ask($input, $output, $question)) { $migrated = 0; foreach ($learningMaterials as $lm) { $fullPath = $pathToIlios2 . $lm->getRelativePath(); if (!$this->symfonyFileSystem->exists($fullPath)) { throw new \Exception('Unable to migrated learning material #' . $lm->getId() . ". No file found at '{$fullPath}'."); } $file = $this->iliosFileSystem->getSymfonyFileForPath($fullPath); $newPath = $this->iliosFileSystem->storeLearningMaterialFile($file); $lm->setRelativePath($newPath); $this->learningMaterialManager->updateLearningMaterial($lm, false); $migrated++; if ($migrated % 500) { $this->learningMaterialManager->flushAndClear(); } } $this->learningMaterialManager->flushAndClear(); $output->writeln("<info>Migrated {$migrated} learning materials successfully!</info>"); } else { $output->writeln('<comment>Migration canceled.</comment>'); } }
/** * {@inheritdoc} */ public function archive(OutputInterface $output) { $driver = $this->storageRegistry->getService(); if (!$this->filesystem->exists($this->archivePath)) { $this->filesystem->mkdir($this->archivePath); } $runIds = []; foreach ($driver->history() as $entry) { $runIds[] = $entry->getRunId(); } $output->writeln(sprintf('Archiving "%s" suites', count($runIds))); foreach ($runIds as $index => $runId) { $filename = $runId . '.xml'; $path = sprintf('%s/%s', $this->archivePath, $filename); if ($this->filesystem->exists($path)) { $this->writeProgress($output, $index, count($runIds), 'S'); continue; } $this->writeProgress($output, $index, count($runIds), '.'); $collection = $driver->fetch($runId); $document = $this->xmlEncoder->encode($collection); $document->save($path); } $output->writeln(PHP_EOL); }
/** * Creates a Terra instance. * * @return Terra * A configured Flo instance. */ private function createTerra() { $terra = new Terra(); // Get config from env variables or files. if ($config_env = getenv('TERRA')) { $config_env = Yaml::parse($config_env); $config = new Config($config_env); } else { $fs = new Filesystem(); $user_config = array(); $user_config_file = getenv('HOME') . '/.terra/terra'; if ($fs->exists($user_config_file)) { $user_config = Yaml::parse($user_config_file); } $project_config = array(); $process = new Process('git rev-parse --show-toplevel'); $process->run(); if ($process->isSuccessful()) { $project_config_file = trim($process->getOutput()) . '/terra.yml'; if ($fs->exists($project_config_file)) { $project_config = Yaml::parse($project_config_file); } } $config = new Config($user_config, $project_config); } $terra->setConfig($config); return $terra; }
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 function testDirectoryEmpty() { $this->assertFalse($this->fs->exists($this->directory)); $result = $this->runCommand('oro:cron:import-tracking', ['--directory' => $this->directory]); $this->assertTrue($this->fs->exists($this->directory)); $this->assertContains('Logs not found', $result); }
/** * @return string The string which identifies a given segment of the execution environment */ public function getIdentifier() { if (!$this->filesystem->exists($this->containerIdPath)) { return ''; } return file_get_contents($this->containerIdPath); }
/** * Copy all existing mocks onto a target directory. * * @param string $targetDir */ public function dumpMocksTo($targetDir) { if (!$this->filesystem->exists($this->mocksDir)) { return; } $this->filesystem->mirror($this->mocksDir, $targetDir, null, ['override' => true, 'delete' => true]); }
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"); } }
/** * Deploy build. * * @throws runtime_exception If deployment failed * @return $this */ public function deploy_build() { if (!$this->fs->exists($this->build_dir)) { return $this; } $this->build_parents(); $current_build = false; if ($this->fs->exists($this->production_link)) { if (is_link($this->production_link)) { $current_build = readlink($this->production_link); } } try { $new_build = $this->repo_dir . 'prod_' . time(); $this->fs->rename($this->build_dir, $new_build); $this->fs->remove($this->production_link); $this->fs->symlink($new_build, $this->production_link); } catch (\Exception $e) { $this->fs->remove($this->production_link); if ($current_build) { $this->fs->symlink($current_build, $this->production_link); } throw new runtime_exception('PACKAGES_BUILD_DEPLOYMENT_FAILED'); } if ($current_build) { $this->fs->remove($current_build); } return $this; }
/** * {@inheritdoc} */ public function launch(Payload $payload, Iteration $iteration, Config $config) { $name = XDebugUtil::filenameFromIteration($iteration); $dir = $config['output_dir']; $phpConfig = ['xdebug.trace_output_name' => $name, 'xdebug.trace_output_dir' => $dir, 'xdebug.trace_format' => '1', 'xdebug.auto_trace' => '1', 'xdebug.coverage_enable' => '0', 'xdebug.collect_params' => '3']; $payload->setPhpConfig($phpConfig); $path = $dir . DIRECTORY_SEPARATOR . $name . '.xt'; // if the file exists, remove it. XDebug might not be installed // on the PHP binary and the file may not be generated. We should // fail in such a case and not use the file from a previous run. if ($this->filesystem->exists($path)) { $this->filesystem->remove($path); } $result = $payload->launch(); if (false === $this->filesystem->exists($path)) { throw new \RuntimeException(sprintf('Trace file at "%s" was not generated.', $path)); } $dom = $this->converter->convert($path); $subject = $iteration->getVariant()->getSubject(); $class = $subject->getBenchmark()->getClass(); // remove leading slash from class name for matching // the class in the trace. if (substr($class, 0, 1) == '\\') { $class = substr($class, 1); } // extract only the timings for the benchmark class, ignore the bootstrapping $selector = '//entry[@function="' . $class . '->' . $subject->getName() . '"]'; // calculate stats from the trace $time = (int) ($dom->evaluate(sprintf('number(%s/@end-time) - number(%s/@start-time)', $selector, $selector)) * 1000000.0); $memory = (int) $dom->evaluate(sprintf('number(%s/@end-memory) - number(%s/@start-memory)', $selector, $selector)); $funcCalls = (int) $dom->evaluate('count(' . $selector . '//*)'); $iteration->setResult(new TimeResult($result['time'])); $iteration->setResult(MemoryResult::fromArray($result['mem'])); $iteration->setResult(new XDebugTraceResult($time, $memory, $funcCalls, $dom)); }
protected function execute(InputInterface $input, OutputInterface $output) { $drop = false; if ($input->getOption('drop') !== false) { $drop = true; } $path = getcwd(); if ($input->getArgument('path') !== null) { $path = $input->getArgument('path'); } $pathExtracted = $path; if ($input->getArgument('path-extracted') !== null) { $pathExtracted = $input->getArgument('path-extracted'); } $fs = new Filesystem(); if (!$fs->exists($path)) { throw new \Exception('Directory doesn\'t exist'); } if (!$fs->exists($pathExtracted)) { throw new \Exception('Extracted directory does\'t exist'); } $finder = new Finder(); $finder->files()->in($path)->name('*.zip')->name('*.rar'); foreach ($finder as $file) { $checker = AlreadyExtractFactory::create($file->getRealPath(), $file->getExtension()); $result = $checker->isAlreadyExtracted($pathExtracted); if ($result === 0 && $drop === true) { $fs->remove($file->getRealPath()); } $this->writeOutput($file->getRealPath(), $output, $result); } $output->writeln("Warnings: " . $this->countWarning . " Errors: " . $this->countError); }
/** * Break the execution of the command when file exists * * @param $destPath */ protected function breakIfFileExists($destPath) { if ($this->filesystem->exists($destPath)) { echo 'File already exists at ' . $destPath . PHP_EOL; exit(1); } }
/** * */ public function testSavingFile() { $this->dumpEntity->setCarefully(false); $this->dumpEntity->saveFile($this->filePath, 'test'); $this->assertTrue($this->filesystem->exists($this->filePath)); $this->assertEquals('test', file_get_contents($this->filePath)); }
/** * Normalize a source (string or SplInfo) into an instance of SplInfo. * * @param mixed $source * @return SplFileInfo * @throws Exception */ public function normalize($source) { $fileSystem = new Filesystem(); // if the source is a file info, it must exists and be readable if ($source instanceof SplFileInfo) { if (!$fileSystem->exists($source->getRealPath())) { throw new Exception('Unable to find ' . $source . ' during normalization process'); } // the source is already normalized return $source; } // if the source is not an instance of SplInfo, it should be a string if (!is_string($source)) { throw new Exception('The source should be a string if it is not an instance of SplInfo (instead of ' . gettype($source) . ')'); } $path = $source; // if the file does not exists, try to add the application path before if (!$fileSystem->exists($source)) { if (!$fileSystem->exists($this->applicationPath . '/' . $source)) { throw new Exception('File ' . $source . ' not found, searched in ' . implode(', ', [$source, $this->applicationPath . '/' . $source])); } $path = $this->applicationPath . '/' . $source; } // normalize source using SplInfo $source = new SplFileInfo($path); return $source; }
/** * @param $path * @throws \Exception */ public function generate($path) { if ($this->filesystem->exists($path)) { throw new \Exception("Error module already exists"); } $this->filesystem->mkdir($path, 0700); }
/** * @param Bundle $bundle * @param OutputInterface $output * @param array $parameters */ public function generateBehatTests(Bundle $bundle, OutputInterface $output, array $parameters) { $dirPath = sprintf("%s/Features", $bundle->getPath()); $skeletonDir = sprintf("%s/Features", $this->fullSkeletonDir); // First copy all the content $this->filesystem->mirror($this->fullSkeletonDir, $bundle->getPath()); // Now render the Context files to replace the namespace etc. if ($handle = opendir($skeletonDir . "/Context")) { while (false !== ($entry = readdir($handle))) { // Check to make sure we skip hidden folders // And we render the files ending in .php if (substr($entry, 0, 1) != '.' && substr($entry, -strlen(".php")) === ".php") { $this->renderFile("/Features/Context/" . $entry, $dirPath . "/Context/" . $entry, $parameters); } } closedir($handle); } $featureContext = $dirPath . "/Context/FeatureContext.php"; if ($this->filesystem->exists($featureContext)) { $contents = file_get_contents($featureContext); $contents = str_replace('-adminpwd-', $this->container->getParameter('kunstmaan_admin.admin_password'), $contents); file_put_contents($featureContext, $contents); } $output->writeln('Generating Behat Tests : <info>OK</info>'); }
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $fileSystem = new Filesystem(); $container->setParameter('symfonian_id.gammu.smsd_inject_path', $config['smsd_inject_path']); $container->setParameter('symfonian_id.gammu.gammu_path', $config['gammu_path']); foreach ($config['gammurc_path'] as $key => $gammurc) { if ($fileSystem->exists($gammurc['path'])) { throw new FileNotFoundException(sprintf('%s not found.')); } if (!$container->hasParameter('symfonian_id.gammu.gammurc.default')) { $container->setParameter('symfonian_id.gammu.gammurc.default', $gammurc['path']); } $container->setParameter('symfonian_id.gammu.gammurc.' . $key, $gammurc['path']); } foreach ($config['smsdrc_path'] as $key => $smsdrc) { if (!$fileSystem->exists($smsdrc['path'])) { throw new FileNotFoundException(sprintf('%s not found.', $smsdrc['path'])); } if (!$container->hasParameter('symfonian_id.gammu.smsdrc.default')) { $container->setParameter('symfonian_id.gammu.smsdrc.default', $smsdrc['path']); } $container->setParameter('symfonian_id.gammu.smsdrc.' . $key, $smsdrc['path']); } $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader->load('services.yml'); }
protected function execute(InputInterface $input, OutputInterface $output) { $class = $input->getArgument('class'); $loader = new \Twig_Loader_Filesystem(__DIR__ . '/../Templates/'); $twig = new \Twig_Environment($loader); $fs = new Filesystem(); $output = Output::style($output); $dir = getcwd() . '/database/seeds'; $file = $dir . '/' . ucfirst($class) . '.php'; $helper = $this->getHelper('question'); if (!$fs->exists($dir)) { $output->writeln('<error>The seeder directory does not exist. Make sure you run groovey seed:init first.</error>'); return; } $output->writeln('<highlight>Creating seeder file:</highlight>'); $output->writeln("<info>- {$file}</info>"); if ($fs->exists($file)) { $question = new ConfirmationQuestion('<question>The seeder file already exist. Are you sure you want to replace it? (Y/N):</question> ', false); if (!$helper->ask($input, $output, $question)) { return; } } else { $question = new ConfirmationQuestion('<question>Are you sure you want to proceed? (Y/n):</question> ', false); if (!$helper->ask($input, $output, $question)) { return; } } $contents = $twig->render('seeder.twig', ['class' => ucfirst($class), 'table' => strtolower($class)]); file_put_contents($file, $contents); $output->writeln('<info>Sucessfully created seed file.</info>'); }
/** * Creates a Flo instance. * * @return Flo * A configured Flo instance. */ private function createFlo() { $flo = new Flo(); // Get config from env variables or files. if ($config_env = getenv('FLO')) { $config_env = Yaml::parse($config_env); $config = new Config($config_env); } else { $fs = new Filesystem(); $user_config = array(); $user_config_file = getenv("HOME") . '/.config/flo'; if ($fs->exists($user_config_file)) { $user_config = Yaml::parse($user_config_file); } $project_config = array(); $process = new Process('git rev-parse --show-toplevel'); $process->run(); if ($process->isSuccessful()) { $project_config_file = trim($process->getOutput()) . '/flo.yml'; if ($fs->exists($project_config_file)) { $project_config = Yaml::parse($project_config_file); } } $config = new Config($user_config, $project_config); } $flo->setConfig($config); return $flo; }
protected function execute(InputInterface $input, OutputInterface $output) { if (1 === $this->getApplication()->find('doctrine:database:create')->run(new ArrayInput(['command' => 'doctrine:database:create', '--connection' => 'wordpress']), $output)) { return 1; } $fs = new Filesystem(); $fs->mkdir($this->getWordpressRoot(), 0755); if (false === $fs->exists($this->getWordpressRoot() . DIRECTORY_SEPARATOR . 'wp-cli.phar')) { $this->runCommand('curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'); $this->runCommand('php wp-cli.phar core download'); } if ($fs->exists($this->getWordpressRoot() . DIRECTORY_SEPARATOR . 'wp-config.php')) { $fs->remove($this->getWordpressRoot() . DIRECTORY_SEPARATOR . 'wp-config.php'); } $this->runCommand(sprintf('php wp-cli.phar core config --dbname=%s --dbuser=%s', $this->getContainer()->getParameter('wordpress_database_name'), $this->getContainer()->getParameter('wordpress_database_user'))); $this->runCommand(sprintf('php wp-cli.phar core install --url=%s --title=Demo --admin_user=admin --admin_password=admin --admin_email=admin@example.com', $this->getContainer()->getParameter('wordpress_url'))); $this->runCommand('php wp-cli.phar plugin install wordpress-importer --activate'); if (false === $fs->exists($this->getWordpressRoot() . DIRECTORY_SEPARATOR . 'wptest.xml')) { $this->runCommand('curl -OL https://raw.githubusercontent.com/manovotny/wptest/master/wptest.xml'); } $this->runCommand('php wp-cli.phar import wptest.xml --authors=create --skip=attachment'); $this->runCommand('php wp-cli.phar core multisite-convert'); $this->runCommand('php wp-cli.phar site create --slug=foo'); $this->runCommand('php wp-cli.phar site create --slug=bar'); return 0; }
public function test exists asserts every file exists() { $dummySuccess = rand(0, 1) === 1; $this->mockFilesystem->exists([$this->dummyStoragePath . '/public.pem', $this->dummyStoragePath . '/private.pem'])->willReturn($dummySuccess); $result = $this->service->exists(); $this->assertSame($dummySuccess, $result); }
public function testInvalidate() { $this->addCacheFile('test', 'test'); $this->assertTrue($this->filesystem->exists($this->tmpHttpCacheDir . '/test')); $this->httpCacheManager->invalidateAll(); $this->assertFalse($this->filesystem->exists($this->tmpHttpCacheDir)); }
/** * @param string $currentRevision * @param string $distantRevision */ protected function upgrade($currentRevision, $distantRevision) { $fs = new Filesystem(); $versionDir = sprintf('%s/versions', $this->config->get('twgit.protected.global.root_dir')); if (!is_dir($versionDir)) { mkdir($versionDir, 0755); } $newPharFile = sprintf('%s/twgit-%s.phar', $versionDir, $distantRevision); $oldPharFile = sprintf('%s/twgit-%s.phar-old', $versionDir, $currentRevision); $currentPharFile = realpath(str_replace(['phar://', '/src/NMR/Command'], ['', ''], __DIR__)); $this->getLogger()->info('Download new version...'); $this->getClient()->get(self::REMOTE_URL_PHAR, ['save_to' => $newPharFile]); if ($fs->exists($newPharFile)) { $this->getLogger()->info('Backup current version...'); if ($fs->exists($oldPharFile)) { $fs->remove($oldPharFile); } $fs->rename($currentPharFile, $oldPharFile); $this->getLogger()->info('Install new version...'); $fs->remove($currentPharFile); $fs->rename($newPharFile, $currentPharFile); $fs->chmod($currentPharFile, 0777); } else { $this->getLogger()->error('Failed to download new version.'); } }
/** * {@inheritdoc} */ public function execute(InputInterface $input, OutputInterface $output) { $ext = pathinfo($input->getArgument('destination'), PATHINFO_EXTENSION); if (!in_array($ext, array('zip', 'gz'))) { throw new \RuntimeException(sprintf('Invalid filename: %s', $input->getArgument('destination'))); } $fs = new Filesystem(); if ($fs->exists($input->getArgument('destination'))) { $fs->remove($input->getArgument('destination')); } $tmpFile = sprintf("%s/composer_archive_%s.%s", sys_get_temp_dir(), sha1($input->getArgument('destination')), $ext); if ($fs->exists($tmpFile)) { $fs->remove($tmpFile); } if ($ext == 'gz') { $cmd = sprintf("cd %s && tar czf %s . %s", $input->getArgument('folder'), $tmpFile, $input->getOption('vcs') ? '' : '--exclude-vcs'); } elseif ($ext == 'zip') { $cmd = sprintf("cd %s && zip -r -q %s . %s", $input->getArgument('folder'), $tmpFile, $input->getOption('vcs') ? '' : '-x *.git* *.svn*'); } $output->writeln(sprintf("Creating temporary file: <info>%s</info>", $tmpFile)); $output->writeln(sprintf("Starting command %s", $cmd)); $process = new Process($cmd); $process->setTimeout(null); $process->run(function ($type, $data) use($output) { $output->write($data, false, OutputInterface::OUTPUT_PLAIN); }); $fs->rename($tmpFile, $input->getArgument('destination')); }
/** * Test if entity persistence and removal is handled correctly. * Tests also that associated physical file exists/is removed. */ public function testPersistenceAndRemoval() { $container = static::$kernel->getContainer(); $filesystem = new Filesystem(); $repoFile = $this->em->getRepository('ReskumeFileBundle:File'); $fileFactory = new FileFactory(); $file = $fileFactory->create(); // test only one entry in database table $this->em->persist($file); $this->em->flush(); $result = $repoFile->findAll(); $this->assertCount(1, $result); // @important clear em and refetch entity to suppress foreign key mapping errors $this->em->clear(); $result = $repoFile->findAll(); $result = $result[0]; // check that associated file exists $fileStorageConfig = $container->get('reskume_file.configuration.file_storage_configuration'); $filePath = sprintf('%s%s', $fileStorageConfig->getFileDir(), $result->getKey()); $this->assertTrue($filesystem->exists($filePath)); // test correct removal $this->em->remove($result); $this->em->flush(); $result = $repoFile->findAll(); $this->assertEmpty($result); // test that associated file is deleted from filesystem $this->assertFalse($filesystem->exists($filePath)); }
/** * @param string $source * @param string $locale * * @return MessageCatalogueInterface | null */ public function extract($source, $locale) { if (!$this->isSourceAvailable($source)) { return; } $fs = new Filesystem(); /* @var Bundle $foundBundle */ $foundBundle = $this->kernel->getBundle($this->bundle); // load any messages from templates $extractedCatalogue = new MessageCatalogue($locale); $resourcesDir = $this->resolveResourcesDirectory($foundBundle); if ($fs->exists($resourcesDir)) { $this->extractor->extract($resourcesDir, $extractedCatalogue); } // load any existing messages from the translation files $translationsDir = $foundBundle->getPath() . '/Resources/translations'; if ($fs->exists($translationsDir)) { $currentCatalogue = new MessageCatalogue($locale); $this->loader->loadMessages($translationsDir, $currentCatalogue); foreach ($extractedCatalogue->getDomains() as $domain) { $messages = $currentCatalogue->all($domain); if (count($messages)) { $extractedCatalogue->add($messages, $domain); } } } return $extractedCatalogue; }
/** * @param InputInterface $input * @param OutputInterface $output * * @return int|void */ public function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $gitHooksPath = $this->paths()->getGitHooksDir(); $resourceHooksPath = $this->paths()->getGitHookTemplatesDir() . $this->grumPHP->getHooksPreset(); $resourceHooksPath = $this->paths()->getPathWithTrailingSlash($resourceHooksPath); $customHooksPath = $this->paths()->getPathWithTrailingSlash($this->grumPHP->getHooksDir()); // Some git clients to not automatically create a git hooks folder. if (!$this->filesystem->exists($gitHooksPath)) { $this->filesystem->mkdir($gitHooksPath); $output->writeln(sprintf('<fg=yellow>Created git hooks folder at: %s</fg=yellow>', $gitHooksPath)); } foreach (self::$hooks as $hook) { $gitHook = $gitHooksPath . $hook; $hookTemplate = $resourceHooksPath . $hook; if ($customHooksPath && $this->filesystem->exists($customHooksPath . $hook)) { $hookTemplate = $customHooksPath . $hook; } if (!$this->filesystem->exists($hookTemplate)) { throw new \RuntimeException(sprintf('Could not find hook template for %s at %s.', $hook, $hookTemplate)); } $content = $this->parseHookBody($hook, $hookTemplate); file_put_contents($gitHook, $content); $this->filesystem->chmod($gitHook, 0775); } $output->writeln('<fg=yellow>Watch out! GrumPHP is sniffing your commits!<fg=yellow>'); }