assets icon indicating copy to clipboard operation
assets copied to clipboard

[Feature Request]: Find Composer's /vendor/ path

Open szepeviktor opened this issue 3 years ago • 3 comments

Is your feature request related to a problem?

AssetPathResolver may improve with this method.

use Composer\Autoload\ClassLoader;
use ReflectionClass;

    /**
     * @throws \RuntimeException
     */
    public static function getVendorPath(): string
    {
        $reflector = new ReflectionClass(ClassLoader::class);
        $classLoaderPath = $reflector->getFileName();
        if ($classLoaderPath === false) {
            throw new \RuntimeException('Unable to find Composer ClassLoader file.');
        }

        $vendorPath = dirname($classLoaderPath, 2);
        if (!is_dir($vendorPath)) {
            throw new \RuntimeException('Unable to detect vendor path.');
        }

        return $vendorPath;
    }

Describe the desired solution

Use the above method.

Describe the alternatives that you have considered

https://github.com/szepeviktor/package-path/blob/master/src/PackagePath.php#L38

Additional context

No response

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

szepeviktor avatar Jun 30 '22 12:06 szepeviktor

I'll add @gmazzap to that as well because he was the one who build the logic for resolving the vendor-path. :)

Chrico avatar Feb 08 '23 09:02 Chrico

If I understood correctly, you're saying that here instead of:

$fullVendorPath = realpath(__DIR__ . '/../../../');

we could do:

$fullVendorPath = static::getVendorPath();

But why use reflections for something we know already?

I mean, the package will always be placed inside the vendor path (this is always assumed to be used as a library), and reflections are not needed for a file to know which is the parent directory of a directory it belongs to. And yes, the hardcoded '/../../../' isn't very elegant, but it works.

Besides, and this is something very specific to us, there are occasions in which, working with some hostings, we are forced to use custom autoloaders instead of the default Composer autoloader. See https://github.com/inpsyde/vip-composer-plugin/blob/master/src/Task/GenerateProductionAutoload.php

In those cases your method would not work.

That said, @szepeviktor, you wrote that the method can be improved with your code, did you find any occurrence in which the current method failed? If so, it would be nice to know more about it.

gmazzap avatar Feb 09 '23 15:02 gmazzap

Thank you for your response.

isn't very elegant, but it works

Path traversal is something I never consider to use. It does not specify the target but instead it looks like a symlink.

In WP VIP you can get the reflection of Inpsyde\VipComposerAutoloader.

In one sentence I'm not a profit oriented guy but someone from the lab 🧪 :)

szepeviktor avatar Feb 09 '23 16:02 szepeviktor