Skip to content

Instantly share code, notes, and snippets.

@fgm
Last active January 29, 2021 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgm/070835b5b878471fa11d882f12d881e6 to your computer and use it in GitHub Desktop.
Save fgm/070835b5b878471fa11d882f12d881e6 to your computer and use it in GitHub Desktop.
Finding vendor-dir from Drupal using Composer
<?php
declare(strict_types=1);
namespace Drupal\upgrade_status;
/**
* CheckedResult provides a format to return both a result and an error.
*
* When the error is not NULL, the result is to be ignored
*/
class CheckedResult {
protected $result;
protected ?\Exception $exception;
public function __construct($result, ?\Exception $exception = NULL) {
$this->result = $result;
$this->exception = $exception;
}
public function __toString(): string {
if (!$this->isValid()) {
return $this->exception->getMessage();
}
return (string) $this->result;
}
public function result(): mixed {
if (!$this->isValid()) {
return NULL;
}
return $this->result;
}
public function isValid(): bool {
return $this->exception === NULL;
}
}
<?php
declare(strict_types=1);
namespace Drupal\upgrade_status;
use Composer\Autoload\ClassLoader;
use Symfony\Component\ClassLoader\ApcClassLoader;
/**
* PhpStanFinder provides identification of the path to PHPstan.
*/
class PhpstanFinder {
protected $classLoader;
public function __construct($class_loader) {
$this->classLoader = $class_loader;
}
/**
* Strip deprecated ApcClassLoader if found.
*/
protected function stripApc() {
$apcLoader = $this->classLoader;
if (!($apcLoader instanceof ApcClassLoader)) {
return;
}
$rc = new \ReflectionClass($apcLoader);
$rp = $rc->getProperty('decorated');
$rp->setAccessible(true);
$decorated = $rp->getValue($apcLoader);
$this->classLoader = $decorated;
}
/**
* @return \Drupal\upgrade_status\CheckedResult
* The vendor dir and/or an error.
*/
public function getVendorDir(): CheckedResult {
$this->stripApc();
if (!($this->classLoader instanceof ClassLoader)) {
return new CheckedResult('', new \Exception("autoloader is not Composer"));
}
$rc = new \ReflectionClass($this->classLoader);
$file = $rc->getFileName();
$vendorDir = dirname($file, 2);
return new CheckedResult($vendorDir);
}
}
# ...snip...
upgrade_status.phpstan_finder:
class: Drupal\upgrade_status\PhpstanFinder
arguments:
- '@class_loader'
$f = Drupal::service('upgrade_status.phpstan_finder');
echo $f->getVendorDir()->__toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment