/** * Initialize a project in a directory. * * @param string $dir * The existing repository directory. * @param string $projectId * The project ID (optional). If no project is specified, the project ID * and git URL will be automatically detected from the repository. * @param string $gitUrl * The project's git URL (optional). * * @throws \RuntimeException * * @return string The absolute path to the project. */ public function initialize($dir, $projectId = null, $gitUrl = null) { $realPath = realpath($dir); if (!$realPath) { throw new \RuntimeException("Directory not readable: {$dir}"); } $dir = $realPath; if (!file_exists("{$dir}/.git")) { throw new \RuntimeException('The directory is not a Git repository'); } if (file_exists($dir . '/../' . self::PROJECT_CONFIG)) { throw new \RuntimeException("The project is already initialized"); } // Get the project ID from the Git repository. if ($projectId === null || $gitUrl === null) { $gitUrl = $this->getGitRemoteUrl($dir); $projectId = $this->getProjectId($gitUrl); } // Move the directory into a 'repository' subdirectory. $backupDir = $this->getBackupDir($dir); $repositoryDir = $dir . '/' . LocalProject::REPOSITORY_DIR; $fs = new Filesystem(); $fs->rename($dir, $backupDir); $fs->mkdir($dir, 0755); $fs->rename($backupDir, $repositoryDir); // Set up the project. $this->createProjectFiles($dir, $projectId); $this->ensureGitRemote($repositoryDir, $gitUrl); return $dir; }
/** * 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; }
/** * Move file. * * @param string $directory * @param null|string $name * @param bool $overwrite * * @return File */ public function move($directory, $name = null, $overwrite = false) { $targetFile = $this->getTargetFile($directory, $name); $this->fileSystem->rename($this->getPathname(), $targetFile, $overwrite); $this->fileSystem->chmod($targetFile, 0666, umask()); return $targetFile; }
private function symlinkPackageToVendor($packagePath, $vendorPath) { $relative = $this->fileSystem->makePathRelative(realpath($packagePath), realpath($vendorPath . '/../')); $this->fileSystem->rename($vendorPath, $vendorPath . '_linked', true); $this->fileSystem->symlink($relative, $vendorPath); $this->fileSystem->remove($vendorPath . '_linked'); }
/** * @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 rename(string $origin, string $target, bool $override = false) { try { $this->filesystem->rename($origin, $target, $override); } catch (IOException $exception) { throw new FilesystemException($exception->getMessage(), $exception->getPath(), $exception); } catch (Exception $exception) { throw new FilesystemException($exception->getMessage(), null, $exception); } }
/** * Execute the action */ public function execute() { parent::execute(); //--Get the id of the link to mediaitem $id = \SpoonFilter::getPostValue('id', null, '', 'string'); //--Get new name for file $nameGet = \SpoonFilter::getPostValue('name', null, '', 'string'); //--Check if the id is not empty if (!empty($id)) { //--Get link to mediaitem $mediaModule = BackendMediaModel::getMediaModule($id); //--Get mediaitem $media = BackendMediaModel::get($mediaModule['media_id']); //--Clean new name for file $name = preg_replace("([^\\w\\s\\d\\-_~,;:\\[\\]\\(\\).])", '', $nameGet); //--Get all image folders defined by sizes $folders = BackendModel::getThumbnailFolders(FRONTEND_FILES_PATH . '/Media/Images', true); //--Create filesystem for file actions $fs = new Filesystem(); //--Get path to files $path = FRONTEND_FILES_PATH . '/Media/'; //--If old and new name is not the same -> do rename if ($media['filename'] != $name . '.' . $media['extension']) { //--Rename files on disk if ($media['filetype'] == 1) { if ($fs->exists($path . 'Images/Source/' . $media['filename'])) { $fs->rename($path . 'Images/Source/' . $media['filename'], FRONTEND_FILES_PATH . '/Media/Images/Source/' . $name . '.' . $media['extension']); } foreach ($folders as $folder) { if ($fs->exists($path . 'Images/' . $folder['dirname'] . '/' . $media['filename'])) { $fs->rename($path . 'Images/' . $folder['dirname'] . '/' . $media['filename'], FRONTEND_FILES_PATH . '/Media/Images/' . $folder['dirname'] . '/' . $name . '.' . $media['extension']); } } } else { if ($fs->exists($path . 'Files/' . $media['filename'])) { $fs->rename($path . 'Files/' . $media['filename'], FRONTEND_FILES_PATH . '/Media/Files/' . $name . '.' . $media['extension']); } } //--Set new name on mediaitem $media['filename'] = $name . '.' . $media['extension']; //--Update mediaitem BackendMediaModel::update($mediaModule['media_id'], $media); //--Create url to new file for ajax $url = FRONTEND_FILES_URL . '/Media/Files/' . $media['filename']; //--Return the new URL -> replaces the old url of the media on page $this->output(self::OK, $url, 'file renamed'); } else { $this->output(self::OK, null, 'file name is the same'); } } // success output }
/** * @expectedException \InvalidArgumentException * @expectedExceptionMessage Could not find rule set: yomama */ public function testItThrowsExceptionOnInvalidRuleSets() { $subject = new AbstractCommandTest_Subject(); $subject->setInput(new ArrayInput(['--ruleSet' => 'yomama', 'previous' => 'HEAD~1'], $subject->getDefinition())); $fs = new Filesystem(); $fs->rename('phpsemver.xml', '_phpsemver.xml'); $subject->setOutput(new NullOutput()); try { $subject->getConfig(); } catch (\Exception $e) { throw $e; } finally { $fs->rename('_phpsemver.xml', 'phpsemver.xml'); } }
/** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $key = $input->getArgument('write_key'); $file = $input->getOption('file'); $debug = $input->getOption('debug'); $client = $this->createClient($key, $debug); $filesystem = new Filesystem(); if (!$filesystem->exists($file)) { throw new \RuntimeException('The specified file does not exist!'); } $temp = sys_get_temp_dir() . sprintf("/segment-io-%s.log", uniqid()); $filesystem->rename($file, $temp); $events = $this->getEvents($temp); $output->writeln(sprintf("<info>Found %s events in the log to Send</info>", sizeof($events))); if (!sizeof($events)) { return 0; } $batches = array_chunk(array_filter($events), 100); foreach ($batches as $batch) { $client->import(['batch' => $batch]); } $output->writeln(sprintf("<comment>Sent %s batches to Segment.io</comment>", sizeof($batches))); $filesystem->remove($temp); return 0; }
/** * @expectedException \RuntimeException */ public function testRenameThrowsExceptionOnError() { $file = $this->workspace.DIRECTORY_SEPARATOR.uniqid(); $newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file'; $this->filesystem->rename($file, $newPath); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $directory = $input->getArgument('directory'); $version = $input->getArgument('version'); $latest = $input->getOption('latest'); if (!$version && $latest) { $version = current($this->getDrupalApi()->getProjectReleases('drupal', 1, true)); } $projectPath = $this->downloadProject($io, 'drupal', $version, 'core'); $downloadPath = sprintf('%sdrupal-%s', $projectPath, $version); $copyPath = sprintf('%s%s', $projectPath, $directory); if ($this->isAbsolutePath($directory)) { $copyPath = $directory; } else { $copyPath = sprintf('%s%s', $projectPath, $directory); } try { $fileSystem = new Filesystem(); $fileSystem->rename($downloadPath, $copyPath); } catch (IOExceptionInterface $e) { $io->commentBlock(sprintf($this->trans('commands.site.new.messages.downloaded'), $version, $downloadPath)); $io->error(sprintf($this->trans('commands.site.new.messages.error-copying'), $e->getPath())); return; } $io->success(sprintf($this->trans('commands.site.new.messages.downloaded'), $version, $copyPath)); }
/** * @param InputInterface $input * @param OutputInterface $output * * @throws Exception * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $fs = new Filesystem(); $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; $tmpDir = dirname($localFilename); $tmpFilename = 'forge-cli-tmp.phar'; $tmpFilepath = $tmpDir . '/' . $tmpFilename; if (!is_writable($tmpDir)) { throw new Exception('Forge update failed: "' . $tmpDir . '" is not writable. Try `sudo !!`.'); } if (!is_writable($localFilename)) { throw new Exception('Forge update failed: "' . $localFilename . '" is not writable. Try `sudo !!`.'); } $output->writeln('<info>Updating ' . $localFilename . '...</info>'); $file = file_get_contents(self::SRC, false, $this->createStreamContext($output)); $fs->dumpFile($tmpFilepath, $file, true); if ($fs->exists($tmpFilepath)) { $fs->rename($tmpFilepath, $localFilename, true); $fs->remove($tmpFilepath); $fs->chmod($localFilename, 0777); $output->writeln('<info>Update completed!</info>'); } else { throw new Exception('Update Failed...'); } }
/** * @internal */ public function fetchThumbnail($retryCount = 0) { return (new FulfilledPromise(null))->then(function () { $lockTimeout = new \DateTime($this->maxAge); $siteInfo = $this->siteRepository->yieldSiteForThumbnailUpdate($lockTimeout); if ($siteInfo === null) { $this->logger->info('No sites to update thumbnails, delay.'); return $this->loop([$this, 'fetchThumbnail'], [CallbackOptions::DELAY => 60000]); } $lockAcquired = $this->siteRepository->lockSiteForThumbnailUpdate($siteInfo->getId(), $lockTimeout); if (!$lockAcquired) { $this->logger->info('Race condition occurred, retrying after a small delay.'); return $this->loop([$this, 'fetchThumbnail'], [CallbackOptions::DELAY => random_int(10, 200)]); } $capturePath = tempnam(sys_get_temp_dir(), 'pjs'); $resizePath = tempnam(sys_get_temp_dir(), 'pjr'); // See bin/phantomjs-capture.js for options. // There is a strange breaking point where a quality 89 generates a 52KB image, // but a quality of 90 generates a 5.5MB image. $quality = 89; $format = 'png'; $width = 1024; $height = 582; $process = ProcessBuilder::create([$this->phantomJsPath, $siteInfo->getUrl(), $capturePath])->setPrefix('phantomjs')->add('--quality=' . $quality)->add('--format=' . $format)->add('--width=' . $width)->add('--height=' . $height)->getProcess(); return $this->loop($process)->then(function (Process $process) use($siteInfo, $capturePath, $resizePath) { $currentHash = $siteInfo->getThumbnailPath() ? md5_file($this->thumbnailDir . $siteInfo->getThumbnailPath()) : null; (new Imagine())->open($capturePath)->thumbnail(new Box(400, 256))->save($resizePath, ['format' => 'jpeg']); // Remove the temp image and its traces. $this->fs->remove($capturePath); if (($newHash = md5_file($resizePath)) === $currentHash) { $this->fs->remove($resizePath); $this->logger->info('Site thumbnail did not change, update the timestamp only.', ['siteId' => $siteInfo->getId(), 'thumbnailPath' => $siteInfo->getThumbnailPath()]); $this->siteRepository->updateSiteThumbnail($siteInfo->getId(), $siteInfo->getThumbnailPath()); return $this->loop([$this, 'fetchThumbnail']); } $thumbnailPath = sprintf('/%s_%s.jpg', $siteInfo->getId(), $newHash); if ($siteInfo->getThumbnailPath() !== null) { // Remove the old thumbnail. $this->fs->remove($this->thumbnailDir . $siteInfo->getThumbnailPath()); } $this->fs->rename($resizePath, $this->thumbnailDir . $thumbnailPath, true); $this->siteRepository->updateSiteThumbnail($siteInfo->getId(), $thumbnailPath); $this->logger->info('Site thumbnail captured.', ['siteId' => $siteInfo->getId(), 'thumbnailPath' => $thumbnailPath]); return $this->loop([$this, 'fetchThumbnail']); })->otherwise(function ($reason) use($capturePath, $resizePath) { // An exception was thrown, clean-up files, then leave the rest to the error handler. try { $this->fs->remove([$capturePath, $resizePath]); } catch (IOException $e) { } return new RejectedPromise($reason); }); })->otherwise(function ($reason) use($retryCount) { /** @var \Exception $exception */ $exception = \GuzzleHttp\Promise\exception_for($reason); $this->logger->log($retryCount >= 60 ? LogLevel::CRITICAL : LogLevel::ERROR, 'An error occurred in the daemon.', ['message' => $exception->getMessage()]); $retryCount++; return $this->loop([$this, 'fetchThumbnail'], [CallbackOptions::ARGS => [$retryCount], CallbackOptions::DELAY => min($retryCount, 60) * 1000]); }); }
protected function execute(InputInterface $input, OutputInterface $output) { $httpClient = $this->getHttpClientHelper(); $site_name = $input->getArgument('site-name'); $version = $input->getArgument('version'); if ($version) { $release_selected = $version; } else { // Getting Module page header and parse to get module Node $output->writeln('[+] <info>' . sprintf($this->trans('commands.site.new.messages.getting-releases')) . '</info>'); // Page for Drupal releases filter by Drupal 8 $project_release_d8 = 'https://www.drupal.org/node/3060/release?api_version%5B%5D=7234'; // Parse release module page to get Drupal 8 releases try { $html = $httpClient->getHtml($project_release_d8); } catch (\Exception $e) { $output->writeln('[+] <error>' . $e->getMessage() . '</error>'); return; } $crawler = new Crawler($html); $releases = []; foreach ($crawler->filter('span.file a') as $element) { if (strpos($element->nodeValue, ".tar.gz") > 0) { $release_name = str_replace('.tar.gz', '', str_replace('drupal-', '', $element->nodeValue)); $releases[$release_name] = $element->nodeValue; } } if (empty($releases)) { $output->writeln('[+] <error>' . $this->trans('commands.module.site.new.no-releases') . '</error>'); return; } // List module releases to enable user to select his favorite release $questionHelper = $this->getQuestionHelper(); $question = new ChoiceQuestion('Please select your favorite release', array_combine(array_keys($releases), array_keys($releases)), 0); $release_selected = $questionHelper->ask($input, $output, $question); } $release_file_path = 'http://ftp.drupal.org/files/projects/drupal-' . $release_selected . '.tar.gz'; // Destination file to download the release $destination = tempnam(sys_get_temp_dir(), 'drupal.') . "tar.gz"; try { // Start the process to download the zip file of release and copy in contrib folter $output->writeln('[+] <info>' . sprintf($this->trans('commands.site.new.messages.downloading'), $release_selected) . '</info>'); $httpClient->downloadFile($release_file_path, $destination); $output->writeln('[+] <info>' . sprintf($this->trans('commands.site.new.messages.extracting'), $release_selected) . '</info>'); $zippy = Zippy::load(); $archive = $zippy->open($destination); $archive->extract('./'); try { $fs = new Filesystem(); $fs->rename('./drupal-' . $release_selected, './' . $site_name); } catch (IOExceptionInterface $e) { $output->writeln('[+] <error>' . sprintf($this->trans('commands.site.new.messages.error-copying'), $e->getPath()) . '</error>'); } $output->writeln('[+] <info>' . sprintf($this->trans('commands.site.new.messages.downloaded'), $release_selected, $site_name) . '</info>'); } catch (\Exception $e) { $output->writeln('[+] <error>' . $e->getMessage() . '</error>'); return; } return true; }
public function edit(Application $app, $id = null) { $Payment = $app['eccube.repository.payment']->findOrCreate($id); $form = $app['form.factory']->createBuilder('payment_register')->getForm(); $form->setData($Payment); // 登録ボタン押下 if ('POST' === $app['request']->getMethod()) { $form->handleRequest($app['request']); if ($form->isValid()) { $PaymentData = $form->getData(); // 手数料を設定できない場合には、手数料を0にする if ($PaymentData->getChargeFlg() == 2) { $PaymentData->setCharge(0); } // ファイルアップロード $file = $form['payment_image']->getData(); $fs = new Filesystem(); if ($file && $fs->exists($app['config']['image_temp_realdir'] . '/' . $file)) { $fs->rename($app['config']['image_temp_realdir'] . '/' . $file, $app['config']['image_save_realdir'] . '/' . $file); } $app['orm.em']->persist($PaymentData); $app['orm.em']->flush(); $app->addSuccess('admin.register.complete', 'admin'); return $app->redirect($app->url('admin_setting_shop_payment')); } } return $app->render('Setting/Shop/payment_edit.twig', array('form' => $form->createView(), 'payment_id' => $id, 'Payment' => $Payment)); }
/** * Moves file or directory from source to destination. * * @param \Djordje\Filebrowser\Entity\FileInterface|string $source * @param string $destination * @return bool */ public function move($source, $destination) { $source = $this->getLocation($source); $destination = $this->getLocation($destination); $this->filesystem->rename($source, $destination); return true; }
/** * {@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')); }
/** * @expectedException \RuntimeException */ public function testRenameThrowsExceptionIfTargetAlreadyExists() { $file = $this->workspace . DIRECTORY_SEPARATOR . 'file'; $newPath = $this->workspace . DIRECTORY_SEPARATOR . 'new_file'; touch($file); touch($newPath); $this->filesystem->rename($file, $newPath); }
/** * Write a file and create a backup if the contents have changed. * * @param string $filename * @param string $contents */ protected function writeAliasFile($filename, $contents) { if (is_readable($filename) && $contents !== file_get_contents($filename)) { $backupName = dirname($filename) . '/' . str_replace('.php', '.bak.php', basename($filename)); $this->fs->rename($filename, $backupName, true); } $this->fs->dumpFile($filename, $contents); }
protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $httpClient = $this->getHttpClientHelper(); $siteName = $input->getArgument('site-name'); $version = $input->getArgument('version'); if ($version) { $releaseSelected = $version; } else { // Getting Module page header and parse to get module Node $io->info(sprintf($this->trans('commands.site.new.messages.getting-releases'))); // Page for Drupal releases filter by Drupal 8 $projectReleaseSelected = 'https://www.drupal.org/node/3060/release?api_version%5B%5D=7234'; // Parse release module page to get Drupal 8 releases try { $html = $httpClient->getHtml($projectReleaseSelected); } catch (\Exception $e) { $io->error($e->getMessage()); return; } $crawler = new Crawler($html); $releases = []; foreach ($crawler->filter('span.file a') as $element) { if (strpos($element->nodeValue, ".tar.gz") > 0) { $releaseName = str_replace('.tar.gz', '', str_replace('drupal-', '', $element->nodeValue)); $releases[$releaseName] = $element->nodeValue; } } if (empty($releases)) { $io->error($this->trans('commands.site.new.messages.no-releases')); return; } $releaseSelected = $io->choice($this->trans('commands.site.new.messages.release'), array_keys($releases)); } $releaseFilePath = 'http://ftp.drupal.org/files/projects/drupal-' . $releaseSelected . '.tar.gz'; // Destination file to download the release $destination = tempnam(sys_get_temp_dir(), 'drupal.') . "tar.gz"; try { // Start the process to download the zip file of release and copy in contrib folter $io->info(sprintf($this->trans('commands.site.new.messages.downloading'), $releaseSelected)); $httpClient->downloadFile($releaseFilePath, $destination); $io->info(sprintf($this->trans('commands.site.new.messages.extracting'), $releaseSelected)); $zippy = Zippy::load(); $archive = $zippy->open($destination); $archive->extract('./'); try { $filesyStem = new Filesystem(); $filesyStem->rename('./drupal-' . $releaseSelected, './' . $siteName); } catch (IOExceptionInterface $e) { $io->error(sprintf($this->trans('commands.site.new.messages.error-copying'), $e->getPath())); } $io->success(sprintf($this->trans('commands.site.new.messages.downloaded'), $releaseSelected, $siteName)); } catch (\Exception $e) { $io->error($e->getMessage()); return false; } return true; }
/** * Execute the action */ public function execute() { parent::execute(); //--Get the ids and split them $id = \SpoonFilter::getPostValue('id', null, '', 'string'); //--Get new name for image $nameGet = \SpoonFilter::getPostValue('name', null, '', 'string'); //--Check if the id is not empty if (!empty($id)) { //--Get image $image = BackendGalleryModel::get($id); //--Clean new name for file $name = preg_replace("([^\\w\\s\\d\\-_~,;:\\[\\]\\(\\).])", '', $nameGet); //--Get all image folders defined by sizes $folders = BackendModel::getThumbnailFolders(FRONTEND_FILES_PATH . '/Gallery/Images', true); //--Create filesystem for file actions $fs = new Filesystem(); //--Get extention $extension = pathinfo($image['filename'], PATHINFO_EXTENSION); //--Get path to files $path = FRONTEND_FILES_PATH . '/Gallery/Images/'; //--If old and new name is not the same -> do rename if ($image['filename'] != $name . '.' . $extension) { //--Rename files on disk if (!$fs->exists($path . '/Source/' . $name . '.' . $extension)) { if ($fs->exists($path . '/Source/' . $image['filename'])) { $fs->rename($path . '/Source/' . $image['filename'], $path . '/Source/' . $name . '.' . $extension); } foreach ($folders as $folder) { if ($fs->exists($path . $folder['dirname'] . '/' . $image['filename'])) { $fs->rename($path . $folder['dirname'] . '/' . $image['filename'], $path . $folder['dirname'] . '/' . $name . '.' . $extension); } } //--Rename file $image['filename'] = $name . '.' . $extension; BackendGalleryModel::update($image); $this->output(self::OK, null, 'file renamed'); } else { $this->output(self::ERROR, null, 'file name already exists'); } } else { $this->output(self::OK, null, 'file name is the same'); } } }
public function save() { /** @var \PharData $newArchive */ $newArchive = $this->archive->compress(static::COMPRESSION_METHOD, $this->getExtension()); $fileSystem = new Filesystem(); $fileSystem->remove($this->archivePath); $fileSystem->rename($newArchive->getPath(), $this->archivePath); $this->archive = new \PharData($this->archivePath); }
protected function execute(InputInterface $input, OutputInterface $output) { $timeStart = microtime(true); $workerName = $input->getArgument('workerName'); $em = $this->getContainer()->get('doctrine.orm.entity_manager'); $em->getConfiguration()->setSQLLogger(null); $lockRepository = $em->getRepository('Scandio\\JobQueueBundle\\Entity\\Lock'); $jobRepository = $em->getRepository('Scandio\\JobQueueBundle\\Entity\\Job'); $maxCount = $input->getOption('maxJobs'); $fl = new Filesystem(); $_lock = '/tmp/worker_lock_' . $workerName; $_unlock = '/tmp/worker_unlock_' . $workerName; if (!$fl->exists($_lock) && !$fl->exists($_unlock)) { touch($_unlock); } $count = 0; $deadlockMessage = ''; $isLocked = $fl->exists($_lock); if ($isLocked && $lockRepository->isDead($workerName)) { $pid = $lockRepository->getPid($workerName); $fl->rename($_lock, $_unlock); $deadlockMessage = "<error>{$pid}</error>"; } if (!$isLocked && $maxCount > 0) { $fl->rename($_unlock, $_lock); do { if ($maxCount > 0 && $count >= $maxCount) { break; } $job = $jobRepository->getNextJob($workerName); if ($job instanceof \Scandio\JobQueueBundle\Entity\Job) { $jobRepository->start($job); $return = shell_exec($job->getCommand()); $jobRepository->finish($job, $return); } $count++; } while ($job instanceof \Scandio\JobQueueBundle\Entity\Job); $fl->rename($_lock, $_unlock); } $message = date('Y-m-d H:i:s') . ';'; $message .= '<info>' . round(microtime(true) - $timeStart, 2) . '</info>' . ';'; $message .= $deadlockMessage; $output->writeln($message); }
/** * @param Filesystem $filesystem * @param $path * @param $fileName * @param array|null $options */ public function save(Filesystem $filesystem, $path, $fileName, array $options = null) { $origin = "{$path}/{$fileName}"; $snapshotFileName = SnapshotManager::createNameForSnapshot(); $target = "{$path}/{$snapshotFileName}"; $freshFileName = SnapshotManager::FRESH_FILE; $freshFilePath = "{$path}/{$freshFileName}"; $filesystem->rename($origin, $target); $filesystem->symlink($target, $freshFilePath); }
/** * {@inheritdoc} */ public function rename($origin, $target, $overwrite = false) { try { $this->symfony_filesystem->rename($origin, $target, $overwrite); } catch (\Symfony\Component\Filesystem\Exception\IOException $e) { $msg = $e->getMessage(); $filename = substr($msg, strpos($msg, '"'), strrpos($msg, '"')); throw new filesystem_exception('CANNOT_RENAME_FILE', $filename, array(), $e); } }
/** * @param Event $event */ public static function checkMultiLangConfigs(Event $event) { $options = static::getOptions($event); $appDir = getcwd() . '/' . $options['symfony-app-dir']; $configDir = $appDir . '/config'; $parametersFile = $configDir . '/parameters.yml'; $routingFile = $configDir . '/routing.yml'; $securityFile = $configDir . '/security.yml'; $singleLangRoutingFile = $configDir . '/routing.singlelang.yml'; $singleLangSecurityFile = $configDir . '/security.singlelang.yml'; $multiLangRoutingFile = $configDir . '/routing.multilang.yml'; $multiLangSecurityFile = $configDir . '/security.multilang.yml'; if (is_file($parametersFile)) { $parameters = self::getConfigParameters($parametersFile); if (isset($parameters[$options['multi-language-option']])) { $multiLanguage = $parameters[$options['multi-language-option']]; if (!$multiLanguage) { $fs = new Filesystem(); // move routing if (is_file($singleLangRoutingFile) && !is_file($multiLangRoutingFile)) { try { $fs->rename($routingFile, $multiLangRoutingFile); $fs->rename($singleLangRoutingFile, $routingFile); $event->getIO()->write(sprintf("Replaced routing config with single language config")); } catch (IOException $ioE) { $event->getIO()->write(sprintf('Exception while moving routing file to singlelang routing file: <error>%s</error>', $ioE->getMessage())); } } // move security if (is_file($singleLangSecurityFile) && !is_file($multiLangSecurityFile)) { try { $fs->rename($securityFile, $multiLangSecurityFile); $fs->rename($singleLangSecurityFile, $securityFile); $event->getIO()->write(sprintf("Replaced security config with single language config")); } catch (IOException $ioE) { $event->getIO()->write(sprintf('Exception while moving routing file to singlelang routing file: <error>%s</error>', $ioE->getMessage())); } } } } } }
/** * {@inheritdoc} */ public function create() { $dir = $this->getConfig('directory'); $git = $this->initRepository($dir); $this->fs->mkdir($dir . '/src', 0755); $this->fs->mkdir($dir . '/test', 0755); // Move all files, add everything to repo except dummy class file foreach ($this->getFilenames() as $filename) { $this->copy($filename, $dir); if ($filename != 'src/DummyClass.php') { $git->add($filename); } } // Rename the dummy class file and add it to the repo $classFilepath = 'src/' . $this->getConfig('class') . '.php'; $this->fs->rename($dir . '/src/DummyClass.php', $dir . '/' . $classFilepath); $git->add($classFilepath); $git->commit('Initial commit.'); $git->remote('add', 'origin', 'git@github.com:' . $this->projectName->get() . '.git'); return true; }
/** * Initialize a project in a directory. * * @param string $dir * * @throws \RuntimeException * * @return string The absolute path to the project. */ public function initialize($dir) { $realPath = realpath($dir); if (!$realPath) { throw new \RuntimeException("Directory not readable: {$dir}"); } $dir = $realPath; if (file_exists($dir . '/../' . self::PROJECT_CONFIG)) { throw new \RuntimeException("The project is already initialized"); } // Get the project ID from the Git repository. $projectId = $this->getProjectIdFromGit($dir); // Move the directory into a 'repository' subdirectory. $backupDir = $this->getBackupDir($dir); $fs = new Filesystem(); $fs->rename($dir, $backupDir); $fs->mkdir($dir, 0755); $fs->rename($backupDir, $dir . '/' . LocalProject::REPOSITORY_DIR); $this->createProjectFiles($dir, $projectId); return $dir; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $directory = $input->getArgument('directory'); $version = $input->getArgument('version'); $latest = $input->getOption('latest'); $composer = $input->getOption('composer'); if (!$directory) { $io->error($this->trans('commands.site.new.messages.missing-directory')); return 1; } if ($composer) { if (!$version) { $version = '8.x-dev'; } $io->newLine(); $io->comment(sprintf($this->trans('commands.site.new.messages.executing'), 'drupal', $version)); $command = sprintf('composer create-project %s:%s %s --no-interaction', 'drupal-composer/drupal-project', $version, $directory); $io->commentBlock($command); $shellProcess = $this->get('shell_process'); if ($shellProcess->exec($command)) { $io->success(sprintf($this->trans('commands.site.new.messages.composer'), $version, $directory)); return 0; } else { return 1; } } if (!$version && $latest) { $version = current($this->getApplication()->getDrupalApi()->getProjectReleases('drupal', 1, true)); } if (!$version) { $io->error('Missing version'); return 1; } $projectPath = $this->downloadProject($io, 'drupal', $version, 'core'); $downloadPath = sprintf('%sdrupal-%s', $projectPath, $version); if ($this->isAbsolutePath($directory)) { $copyPath = $directory; } else { $copyPath = sprintf('%s%s', $projectPath, $directory); } try { $fileSystem = new Filesystem(); $fileSystem->rename($downloadPath, $copyPath); } catch (IOExceptionInterface $e) { $io->commentBlock(sprintf($this->trans('commands.site.new.messages.downloaded'), $version, $downloadPath)); $io->error(sprintf($this->trans('commands.site.new.messages.error-copying'), $e->getPath())); return 1; } $io->success(sprintf($this->trans('commands.site.new.messages.downloaded'), $version, $copyPath)); return 0; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $current = $this->getApplication()->getVersion(); if (false === ($latest = @file_get_contents('http://kzykhys.com/coupe/version'))) { $output->writeln('<error>Failed to connect to http://kzykhys.com/coupe/version</error>'); return 255; } if (!$input->getOption('force')) { if ($current === $latest) { $output->writeln('<info>You are using the latest version [' . $current . ']</info>'); return 0; } } /* @var \Symfony\Component\Console\Helper\ProgressHelper $progress */ $progress = $this->getHelper('progress'); $fileSize = 0; $currentPercent = 0; $progress->start($output, 100); $context = stream_context_create(); stream_context_set_params($context, ["notification" => function ($c, $s, $m, $mc, $transferred, $max) use(&$progress, &$fileSize, &$currentPercent) { switch ($c) { case STREAM_NOTIFY_FILE_SIZE_IS: $fileSize = $max; break; case STREAM_NOTIFY_PROGRESS: if ($transferred > 0) { $percent = (int) ($transferred / $fileSize * 100); $progress->advance($percent - $currentPercent); $currentPercent = $percent; } break; } }]); $output->writeln('Downloading <fg=green;options=bold>' . $latest . '</fg=green;options=bold> ...'); if (false === ($phar = @file_get_contents('http://kzykhys.com/coupe/coupe.phar', false, $context))) { $output->writeln('<error>Failed to download new coupe version</error>'); return 255; } $progress->setCurrent(100); $progress->finish(); $pharPath = $GLOBALS['argv'][0]; $fs = new Filesystem(); $fs->copy($pharPath, $backup = tempnam(sys_get_temp_dir(), 'coupe_phar_backup')); if (false == @file_put_contents($pharPath, $phar)) { $fs->remove($pharPath); $fs->rename($backup, $pharPath); $output->writeln('<error>Failed to update coupe to the latest version</error>'); return 1; } $fs->remove($backup); return 0; }