Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions .github/workflows/test-lang-php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ on:
paths:
- .github/workflows/test-lang-php.yml
- composer.json
- lang/php/**
- lang/php/bin/**
- lang/php/lib/**
- lang/php/test/**
- lang/php/.php-cs-fixer.dist.php
- lang/php/build.sh
- lang/php/phpstan*
- lang/php/phpunit.xml

defaults:
run:
Expand Down Expand Up @@ -55,7 +61,7 @@ jobs:
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:2.9.8
tools: composer:2.10.1

- name: Get Composer Cache Directory
id: composer-cache
Expand Down Expand Up @@ -99,7 +105,7 @@ jobs:
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
tools: composer:2.9.8
tools: composer:2.10.1

- name: Cache Local Maven Repository
uses: actions/cache@v5
Expand Down
8 changes: 7 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
"issues": "https://issues.apache.org/jira/browse/AVRO"
},
"require": {
"php": "^8.1"
"php": "^8.1",
"nikic/php-parser": "^5.7",
"symfony/console": "^6.4"
},
"deps": [
"vendor/phpunit/phpunit"
Expand Down Expand Up @@ -54,6 +56,9 @@
"dev-master": "1.0.x-dev"
}
},
"bin": [
"lang/php/bin/avro"
],
"archive": {
"exclude": [
"*",
Expand All @@ -64,6 +69,7 @@
"!/README.md",
"!/composer.json",
"!/lang/php/README.md",
"!/lang/php/bin",
"!/lang/php/lib"
]
},
Expand Down
2 changes: 1 addition & 1 deletion lang/php/.php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
* ```
*/
$finder = PhpCsFixer\Finder::create()
->in(['lib', 'test'])
->in(['bin', 'lib', 'test'])
->append(['.php-cs-fixer.dist.php']);

return (new PhpCsFixer\Config())
Expand Down
83 changes: 83 additions & 0 deletions lang/php/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,86 @@ If you're pulling from source, put `lib/` in your include path and require `lib/
require_once('lib/autoload.php');

Take a look in `examples/` for usage.

Code Generation
===============

The `avro` CLI tool generates PHP classes from Avro schema files (`.avsc`).

## Usage

```
vendor/bin/avro [options]
```

### Options

| Option | Short | Description |
|--------|-------|-------------|
| `--file` | `-f` | Path to a single `.avsc` schema file |
| `--directory` | `-d` | Path to a directory containing `.avsc` schema files |
| `--output` | `-o` | Output directory for the generated PHP files (created if it does not exist) |
| `--namespace` | `-ns` | PHP namespace for the generated classes |

Exactly one of `--file` or `--directory` must be provided.

## Examples

Generate a PHP class from a single schema file:

```bash
vendor/bin/avro --file path/to/user.avsc --output src/Generated --namespace App\\Avro\\Generated
```

Generate PHP classes from all `.avsc` files in a directory:

```bash
vendor/bin/avro --directory path/to/schemas --output src/Generated --namespace App\\Avro\\Generated
```

## Generated output

Given a record schema:

```json
{
"type": "record",
"name": "User",
"fields": [
{"name": "name", "type": "string"},
{"name": "age", "type": "int"}
]
}
```

The command produces `src/Generated/User.php`:

```php
<?php

declare(strict_types=1);

namespace App\Avro\Generated;

final class User implements \JsonSerializable
{
private string $name;
private int $age;

public function __construct(string $name, int $age)
{
$this->name = $name;
$this->age = $age;
}

public function name(): string { return $this->name; }
public function age(): int { return $this->age; }

public function jsonSerialize(): mixed
{
return ['name' => $this->name, 'age' => $this->age];
}
}
```

Enum schemas generate a PHP backed enum. Nested record and enum types each produce their own file.
52 changes: 52 additions & 0 deletions lang/php/bin/avro
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#!/usr/bin/env php
<?php

/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add some documentation about the purpose of this file.

declare(strict_types=1);

const _AVRO_AUTOLOADER_LOCATIONS = [
__DIR__ . '/../../autoload.php',
__DIR__ . '/../vendor/autoload.php',
__DIR__ . '/../../../vendor/autoload.php',
__DIR__ . '/vendor/autoload.php'
];

foreach (_AVRO_AUTOLOADER_LOCATIONS as $autoloader) {
if (file_exists($autoloader)) {
require $autoloader;
break;
}
}

if (!class_exists(\Apache\Avro\Console\GenerateCommand::class)) {
fwrite(STDERR, "Error: Composer autoloader not found. Run 'composer install' first.\n");
exit(1);
}

use Apache\Avro\Console\GenerateCommand;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should those imports be upper in the file ?

use Composer\InstalledVersions;
use Symfony\Component\Console\Application;

$version = InstalledVersions::getPrettyVersion('apache/avro');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$version = InstalledVersions::getPrettyVersion('apache/avro');
try {
$version = InstalledVersions::getPrettyVersion('apache/avro') ?? 'unknown';
} catch (\Throwable) {
$version = 'unknown';
}


$app = new Application('avro', $version);
$app->addCommand(new GenerateCommand());
$app->setDefaultCommand('generate', true);
$app->run();
149 changes: 149 additions & 0 deletions lang/php/lib/Console/GenerateCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
<?php

/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

declare(strict_types=1);

namespace Apache\Avro\Console;

use Apache\Avro\Generator\AvroCodeGenerator;
use Apache\Avro\Schema\AvroSchema;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
name: 'generate',
description: 'Generate PHP classes from Avro schema files',
)]
class GenerateCommand extends Command
{
protected function configure(): void
{
$this
->addOption('file', 'f', InputOption::VALUE_OPTIONAL, 'One Avro schema file (.avsc)')
->addOption('directory', 'd', InputOption::VALUE_OPTIONAL, 'A directory containing multiple Avro schema files (.avsc)')
->addOption('output', 'o', InputOption::VALUE_REQUIRED, 'Output directory for generated PHP files')
->addOption('namespace', 'ns', InputOption::VALUE_REQUIRED, 'PHP namespace for generated classes');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
->addOption('namespace', 'ns', InputOption::VALUE_REQUIRED, 'PHP namespace for generated classes');
->addOption('namespace', 'n', InputOption::VALUE_REQUIRED, 'PHP namespace for generated classes');

Usually the short options are single character

@mattiabasone mattiabasone Jun 26, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The -n is already taken by the Symfony Console Component

-n, --no-interaction         Do not ask any interactive question

We could use a capital N, wdyt?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);

/** @var string $outputDir */
$outputDir = $input->getOption('output');
/** @var string $namespace */
$namespace = $input->getOption('namespace');

/** @var null|string $file */
$file = $input->getOption('file');
/** @var null|string $directory */
$directory = $input->getOption('directory');

if (
(null === $file && null === $directory)
|| (null !== $file && null !== $directory)
) {
$io->error('You must provide a file path or a directory');

return Command::FAILURE;
}

if (null === $outputDir || '' === $outputDir) {
$io->error('Output directory is required (--output / -o).');

return Command::FAILURE;
}

if (null === $namespace || '' === $namespace) {
$io->error('PHP namespace is required (--namespace / -ns).');

return Command::FAILURE;
}

if (!is_dir($outputDir) && !mkdir($outputDir, 0755, true) && !is_dir($outputDir)) {
$io->error(sprintf('Could not create output directory "%s".', $outputDir));

return Command::FAILURE;
}

$outputDir = rtrim((string) realpath($outputDir), '/');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

realpath() may return false on failure (e.g. permissions issue) and the cast to string will make $outputDir = "", i.e. the root folder.

$files = [];
if (null !== $file) {
$files[] = $file;
} elseif (null !== $directory) {
if (!is_dir($directory)) {
$io->error(sprintf('Directory not found: %s', $directory));

return Command::FAILURE;
}
$files = glob(rtrim($directory, '/').'/*.avsc') ?: [];
}

$generator = new AvroCodeGenerator();
$written = [];
$exitCode = Command::SUCCESS;

foreach ($files as $file) {
if (!file_exists($file)) {
$io->error(sprintf('File not found: %s', $file));
$exitCode = Command::FAILURE;

continue;
}

$json = file_get_contents($file);
if (false === $json) {
$io->error(sprintf('Could not read file: %s', $file));
$exitCode = Command::FAILURE;

continue;
}

try {
$schema = AvroSchema::parse($json);
$generatedFiles = $generator->translate($schema, $outputDir, $namespace);

foreach ($generatedFiles as $path => $content) {
if (false === file_put_contents($path, $content)) {
$io->error(sprintf('Could not write file: %s', $path));
$exitCode = Command::FAILURE;

continue;
}
$written[] = $path;
}
} catch (\Throwable $e) {
$io->error(sprintf('Error processing %s: %s', $file, $e->getMessage()));
$exitCode = Command::FAILURE;
}
}

if ([] !== $written) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty directory (i.e. files == []) will be reported as success. Is this intentional ?
I am not sure how the other SDK generators behave.

$io->listing($written);
$io->success(sprintf('%d file(s) generated in %s.', count($written), $outputDir));
}

return $exitCode;
}
}
Loading
Loading