From 63813ec60cdfe966de8577e06aed40cd9a1720d8 Mon Sep 17 00:00:00 2001 From: Arne Blankerts Date: Sat, 3 Oct 2015 17:37:20 +0200 Subject: [PATCH] Use common base directory of given directories as basedir in phar mode This fixes #63 --- src/Config.php | 4 ++++ src/PathComparator.php | 41 +++++++++++++++++++++++++++++++++++ src/autoload.php | 5 ++++- tests/PathComparator.test.php | 35 ++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 src/PathComparator.php create mode 100644 tests/PathComparator.test.php diff --git a/src/Config.php b/src/Config.php index 82284cc..b5f228c 100644 --- a/src/Config.php +++ b/src/Config.php @@ -83,6 +83,10 @@ public function getBaseDirectory() { if ($this->baseDirectory !== NULL) { return realpath($this->baseDirectory); } + if ($this->isPharMode()) { + $comparator = new PathComparator($this->directories); + return $comparator->getCommondBase(); + } if ($this->outputFile != 'STDOUT') { return realpath(dirname($this->outputFile) ?: '.'); } diff --git a/src/PathComparator.php b/src/PathComparator.php new file mode 100644 index 0000000..fc0d791 --- /dev/null +++ b/src/PathComparator.php @@ -0,0 +1,41 @@ +directories[] = realpath($dir); + } + } + + public function getCommondBase() { + if (count($this->directories) == 0) { + return '/'; + } + $result = $this->directories[0]; + foreach($this->directories as $dir) { + $result = substr($dir, 0, $this->commonPrefix($result, $dir)); + } + return rtrim($result,'/'); + } + + + private function commonPrefix( $s1, $s2, $i=0 ) { + return ( + !empty($s1[$i]) && !empty($s2[$i]) && $s1[$i] == $s2[$i] + ) ? $this->commonPrefix( $s1, $s2, ++$i ) : $i; + } + } + +} diff --git a/src/autoload.php b/src/autoload.php index eaa1cd2..37905d0 100644 --- a/src/autoload.php +++ b/src/autoload.php @@ -127,6 +127,7 @@ function($class) { 'theseer\\autoload\\parseresult' => '/ParseResult.php', 'theseer\\autoload\\parserexception' => '/Parser.php', 'theseer\\autoload\\parserinterface' => '/ParserInterface.php', + 'theseer\\autoload\\pathcomparator' => '/PathComparator.php', 'theseer\\autoload\\pharbuilder' => '/PharBuilder.php', 'theseer\\autoload\\sourcefile' => '/SourceFile.php', 'theseer\\autoload\\staticrenderer' => '/StaticRenderer.php', @@ -142,6 +143,8 @@ function($class) { if (isset($classes[$cn])) { require __DIR__ . $classes[$cn]; } - } + }, + true, + false ); // @codeCoverageIgnoreEnd diff --git a/tests/PathComparator.test.php b/tests/PathComparator.test.php new file mode 100644 index 0000000..4d4f15b --- /dev/null +++ b/tests/PathComparator.test.php @@ -0,0 +1,35 @@ +assertEquals($common, $comparator->getCommondBase()); + } + + public function directoriesProvider() { + return [ + 'empty' => [ + [], '/' + ], + 'single' => [ + array(__DIR__), __DIR__ + ], + 'two' => [ + array(__DIR__, dirname(__DIR__)), dirname(__DIR__) + ], + 'partns' => [ + array(__DIR__ . '/../src', __DIR__ . '/../vendor/theseer'), dirname(__DIR__) + ] + ]; + } + } + +}