本文整理汇总了PHP中Symfony\Component\Filesystem\Filesystem::rename方法的典型用法代码示例。如果您正苦于以下问题:PHP Filesystem::rename方法的具体用法?PHP Filesystem::rename怎么用?PHP Filesystem::rename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Symfony\Component\Filesystem\Filesystem
的用法示例。
在下文中一共展示了Filesystem::rename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: initialize
/**
* 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;
}
示例2: deploy_build
/**
* 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;
}
示例3: move
/**
* 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;
}
示例4: symlinkPackageToVendor
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');
}
示例5: upgrade
/**
* @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.');
}
}
示例6: rename
/**
* {@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);
}
}
示例7: execute
/**
* 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
}
示例8: testItThrowsExceptionOnInvalidRuleSets
/**
* @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');
}
}
示例9: execute
/**
* {@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;
}
示例10: testRenameThrowsExceptionOnError
/**
* @expectedException \RuntimeException
*/
public function testRenameThrowsExceptionOnError()
{
$file = $this->workspace.DIRECTORY_SEPARATOR.uniqid();
$newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file';
$this->filesystem->rename($file, $newPath);
}
示例11: execute
/**
* {@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));
}
示例12: execute
/**
* @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...');
}
}
示例13: fetchThumbnail
/**
* @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]);
});
}
示例14: execute
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;
}
示例15: edit
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));
}