nxu / php-nano-class-parser
A fully opinionated, extremely minimal, and very optimistic package to help add custom code to generated PHP classes.
Installs: 2 287
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 0
Requires
- php: >=8.2
- ext-tokenizer: *
- illuminate/collections: >=10
- nikic/php-parser: ^4.17
Requires (Dev)
- laravel/pint: ^1.11
- pestphp/pest: ^2.14
- phpstan/phpstan: ^1.10
- phpstan/phpstan-strict-rules: ^1.5
- symfony/var-dumper: ^6.3
- thecodingmachine/phpstan-strict-rules: ^1.0
README
This is a very simple package that helps you parse some information about some PHP files.
Philosophy
The intended purpose of this package is to determine the presence and optionally the vertical position of some statements in a PHP file. This is useful in situations like programmatically adding extra boilerplate to generated files.
Provided analyses:
- Imports (
use <FQN>;
) - Class definition (
class Someting {}
) - Trait uses (
use <Trait>;
) - First function of a class (
public static function Something {}
)
My use case
I am maintaining a CMS that is based on Laravel and Filament. Part of the CMS are commands that generate PHP files (such as Laravel Models and Filament Resources). During generation, my goals are:
- Use the built-in generators
- Append some custom PHP boilerplate to it
This package helps me determine where to add custom namespace uses, member properties and member functions as crude strings.
Main features / restrictions
- Extremely mimimal
- The package only provides what I need, nothing more.
- Fully opinionated
- The package provides its functionality exactly how I need it.
- Very optimistic
- This is a very nice way of saying "I don't really care about edge cases".
How?
Install
composer require nxu/php-nano-class-parser --dev
Use
TLDR
$class = PhpClass::parse( <<<'PHP' <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class LaravelModel extends Model { use HasFactory; } PHP ); $imports = $class->analyze()->imports(); $imports->firstLine; // 5 $imports->lastLine; // 6 $imports->imports; // [ // 'Illuminate\Database\Eloquent\Factories\HasFactory', // 'Illuminate\Database\Eloquent\Model', // ]
Available analyses
$class = \Nxu\PhpNanoClassParser\PhpClass::parse('...PHP source code...'); $class->analyze()->classDefinition(); $class->analyze()->classOutline(); $class->analyze()->firstFunction(); $class->analyze()->traits(); $class->analyze()->imports();
License
This package is licensed under the MIT license.