OrenIshShalom
OrenIshShalom

Reputation: 7172

Composer on docker: Uncaught Error: Class not found

I'm trying to build a minimal docker image to use packagist.org/packages/nikic/php-parser:

FROM php
RUN apt-get update
RUN apt-get install zip -y
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
COPY . .

Installing the (single) dependency goes smooth (done outside Dockerfile for exposition):

root@e1aa9cdb4e13:/# composer install
< ... omitted for brevity ... >
Package operations: 1 install, 0 updates, 0 removals
  - Downloading nikic/php-parser (v5.0.2)
  - Installing nikic/php-parser (v5.0.2): Extracting archive
Generating autoload files

When I try to run the example in the docs, I crash:

root@e1aa9cdb4e13:/# php main.php
Fatal error: Uncaught Error: Class "PhpParser\ParserFactory" not found in /main.php:15

Here is the example I use (taken "as-is" from the docs):

<?php
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;

$code = <<<'CODE'
<?php

function test($foo)
{
    var_dump($foo);
}
CODE;

$parser = (new ParserFactory())->createForNewestSupportedVersion();
try {
    $ast = $parser->parse($code);
} catch (Error $error) {
    echo "Parse error: {$error->getMessage()}\n";
    return;
}

$dumper = new NodeDumper;
echo $dumper->dump($ast) . "\n";

EDIT

Adding an explicit include from vendor directory, I seem to get one (tiny ?) step farther:

include "/vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php";

new error message:

Fatal error: Uncaught Error: Class "PhpParser\PhpVersion" not found in /vendor/nikic/php-parser/lib/PhpParser/ParserFactory.php:32

Upvotes: 0

Views: 223

Answers (1)

OrenIshShalom
OrenIshShalom

Reputation: 7172

It turns out I was missing a single statement:

<?php
require '/vendor/autoload.php';

When I added this line it worked perfectly:

root@e1aa9cdb4e13:/# php main.php
array(
    0: Stmt_Function(
        attrGroups: array(
        )
        byRef: false
        name: Identifier(
            name: test
        )
< ... omitted for brevity ... >

* I found the reference here

Upvotes: 0

Related Questions