Skip to content

Commit

Permalink
🐎 Refactors relative path logic
Browse files Browse the repository at this point in the history
  • Loading branch information
frenck committed Oct 26, 2018
1 parent ff3bb9c commit 1efacc8
Showing 1 changed file with 12 additions and 43 deletions.
55 changes: 12 additions & 43 deletions src/Plugin.php
Expand Up @@ -20,6 +20,7 @@
use Composer\Script\Event;
use Composer\Script\ScriptEvents;
use Composer\Util\ProcessExecutor;
use Composer\Util\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Process\Exception\LogicException;
use Symfony\Component\Process\Exception\ProcessFailedException;
Expand Down Expand Up @@ -66,6 +67,11 @@ class Plugin implements PluginInterface, EventSubscriberInterface
*/
private $processExecutor;

/**
* @var Filesystem
*/
private $filesystem;

/**
* Triggers the plugin's main functionality.
*
Expand Down Expand Up @@ -120,6 +126,7 @@ private function init()
{
$this->installedPaths = array();
$this->processExecutor = new ProcessExecutor($this->io);
$this->filesystem = new Filesystem($this->processExecutor);
}

/**
Expand Down Expand Up @@ -304,7 +311,11 @@ private function updateInstalledPaths()

// Use relative paths for local project repositories.
if ($this->isRunningGlobally() === false) {
$standardsPath = $this->getRelativePath($standardsPath);
$standardsPath = $this->filesystem->findShortestPath(
$this->getPHPCodeSnifferInstallPath(),
$standardsPath,
true
);
}

// De-duplicate and add when directory is not configured.
Expand Down Expand Up @@ -400,48 +411,6 @@ private function isRunningGlobally()
return ($this->composer->getConfig()->get('home') === getcwd());
}

/**
* Returns the relative path to PHP_CodeSniffer from any other absolute path
*
* @param string $to Absolute path
*
* @return string Relative path
*/
private function getRelativePath($to)
{
$from = $this->getPHPCodeSnifferInstallPath();

// Some compatibility fixes for Windows paths
$from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
$to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
$from = str_replace('\\', '/', $from);
$to = str_replace('\\', '/', $to);

$from = explode('/', $from);
$to = explode('/', $to);
$relPath = $to;

foreach ($from as $depth => $dir) {
// Find first non-matching dir
if ($dir === $to[$depth]) {
// Ignore this directory
array_shift($relPath);
} else {
// Get number of remaining dirs to $from
$remaining = count($from) - $depth;
if ($remaining > 1) {
// Add traversals up to first matching dir
$padLength = (count($relPath) + $remaining - 1) * -1;
$relPath = array_pad($relPath, $padLength, '..');
break;
} else {
$relPath[0] = './' . $relPath[0];
}
}
}
return implode('/', $relPath);
}

/**
* Determines the maximum search depth when searching for Coding Standards.
*
Expand Down

0 comments on commit 1efacc8

Please sign in to comment.