nxu/php-nano-class-parser

A fully opinionated, extremely minimal, and very optimistic package to help add custom code to generated PHP classes.

v1.2 2023-08-29 07:52 UTC

This package is auto-updated.

Last update: 2024-04-29 09:06:49 UTC


README

tests phpstan Packagist Version (custom server)

This is a very simple package that helps you parse some information about some PHP files.

Stand With Ukraine

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.