ReplaceOp.php in Drupal 9
File
composer/Plugin/Scaffold/Operations/ReplaceOp.php
View source
<?php
namespace Drupal\Composer\Plugin\Scaffold\Operations;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use Drupal\Composer\Plugin\Scaffold\ScaffoldFilePath;
use Drupal\Composer\Plugin\Scaffold\ScaffoldOptions;
class ReplaceOp extends AbstractOperation {
const ID = 'replace';
protected $source;
protected $overwrite;
public function __construct(ScaffoldFilePath $sourcePath, $overwrite = TRUE) {
$this->source = $sourcePath;
$this->overwrite = $overwrite;
}
protected function generateContents() {
return file_get_contents($this->source
->fullPath());
}
public function process(ScaffoldFilePath $destination, IOInterface $io, ScaffoldOptions $options) {
$fs = new Filesystem();
$destination_path = $destination
->fullPath();
if ($this->overwrite === FALSE && file_exists($destination_path)) {
$interpolator = $destination
->getInterpolator();
$io
->write($interpolator
->interpolate(" - Skip <info>[dest-rel-path]</info> because it already exists and overwrite is <comment>false</comment>."));
return new ScaffoldResult($destination, FALSE);
}
$fs
->remove($destination_path);
$fs
->ensureDirectoryExists(dirname($destination_path));
if ($options
->symlink()) {
return $this
->symlinkScaffold($destination, $io);
}
return $this
->copyScaffold($destination, $io);
}
protected function copyScaffold(ScaffoldFilePath $destination, IOInterface $io) {
$interpolator = $destination
->getInterpolator();
$this->source
->addInterpolationData($interpolator);
$success = file_put_contents($destination
->fullPath(), $this
->contents());
if (!$success) {
throw new \RuntimeException($interpolator
->interpolate("Could not copy source file <info>[src-rel-path]</info> to <info>[dest-rel-path]</info>!"));
}
$io
->write($interpolator
->interpolate(" - Copy <info>[dest-rel-path]</info> from <info>[src-rel-path]</info>"));
return new ScaffoldResult($destination, $this->overwrite);
}
protected function symlinkScaffold(ScaffoldFilePath $destination, IOInterface $io) {
$interpolator = $destination
->getInterpolator();
try {
$fs = new Filesystem();
$fs
->relativeSymlink($this->source
->fullPath(), $destination
->fullPath());
} catch (\Exception $e) {
throw new \RuntimeException($interpolator
->interpolate("Could not symlink source file <info>[src-rel-path]</info> to <info>[dest-rel-path]</info>!"), [], $e);
}
$io
->write($interpolator
->interpolate(" - Link <info>[dest-rel-path]</info> from <info>[src-rel-path]</info>"));
return new ScaffoldResult($destination, $this->overwrite);
}
}
Classes
Name |
Description |
ReplaceOp |
Scaffold operation to copy or symlink from source to destination. |