PHPackages                             malico/php-sculptor - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. malico/php-sculptor

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

malico/php-sculptor
===================

Programmatically modify PHP code with a fluent, intuitive API

0.1.1(8mo ago)01MITPHPPHP ^8.0

Since Sep 3Pushed 8mo agoCompare

[ Source](https://github.com/yondifon/php-sculptor)[ Packagist](https://packagist.org/packages/malico/php-sculptor)[ RSS](/packages/malico-php-sculptor/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

PHP Sculptor
============

[](#php-sculptor)

**Programmatically modify PHP code with a fluent, intuitive API.** Built on `nikic/php-parser` for reliable AST manipulation, PHP Sculptor makes it easy to automate code modifications, refactoring, and generation tasks.

**Important:** PHP Sculptor is primarily intended for personal use and small-scale automation tasks. For comprehensive AST manipulation needs or production-scale applications, consider using the underlying [nikic/php-parser](https://github.com/nikic/PHP-Parser) package directly.

Why PHP Sculptor?
-----------------

[](#why-php-sculptor)

- **Fluent API**: Chain multiple modifications in a readable, expressive way
- **Safe AST manipulation**: Built on battle-tested `nikic/php-parser` for reliable code parsing
- **Duplicate detection**: Automatically prevents duplicate traits, methods, and properties
- **Smart positioning**: Maintains proper code structure (traits → properties → methods)
- **Extensible**: Add custom modifiers for specialized use cases
- **Framework-agnostic**: Works with any PHP class structure

Installation
------------

[](#installation)

```
composer require malico/php-sculptor
```

**Requirements:** PHP 8.0+ and `nikic/php-parser ^5.0`

Quick Start
-----------

[](#quick-start)

Transform any PHP class with a simple, chainable API:

```
use Malico\PhpSculptor\Sculptor;

$sculptor = Sculptor::make('src/User.php')
    ->addUseStatement('App\Traits\Timestamped')
    ->addTrait('Timestamped')
    ->extendArrayProperty('config', ['cache_enabled' => true, 'timeout' => 30])
    ->addProperty('status', 'active', 'protected', 'string')
    ->addMethod('isActive', [], 'return $this->status === "active";')
    ->save();
```

Core Features
-------------

[](#core-features)

### Class Structure Modifications

[](#class-structure-modifications)

```
// Add traits and use statements
$sculptor->addUseStatement('App\Traits\Loggable')
         ->addTrait('Loggable');

// Add properties with types and defaults
$sculptor->addProperty('status', 'pending', 'protected', 'string')
         ->addProperty('config', [], 'private', 'array');

// Add methods with parameters
$sculptor->addMethod('activate', [], '$this->status = "active";', 'public')
         ->addMethod('setConfig', [
             ['name' => 'key', 'type' => 'string'],
             ['name' => 'value', 'type' => 'mixed']
         ], '$this->config[$key] = $value;');

// Add constants
$sculptor->addConstant('DEFAULT_STATUS', 'pending', 'public');
```

### Array Property Extensions

[](#array-property-extensions)

```
// Extend array properties safely
$sculptor->extendArrayProperty('permissions', ['read', 'write'])
         ->extendArrayProperty('config', ['debug' => true, 'cache' => false])
         ->extendArrayProperty('validationRules', ['email' => 'required']);

// Works with any array property
$sculptor->extendArrayProperty('features', ['notifications', 'logging']);
```

### Advanced Modifications

[](#advanced-modifications)

```
// Modify existing elements
$sculptor->changeProperty('name', 'DefaultName', 'public', 'string')
         ->changeMethodBody('getName', 'return $this->name ?? "Anonymous";')
         ->changeMethodVisibility('getId', 'public');

// Remove elements
$sculptor->removeProperty('deprecatedField')
         ->removeMethod('oldMethod')
         ->removeTrait('ObsoleteTrait');

// Namespace operations
$sculptor->addNamespace('App\Services\Advanced')
         ->changeClassName('AdvancedProcessor');
```

API Reference
-------------

[](#api-reference)

### Core Modification Methods

[](#core-modification-methods)

MethodDescriptionExample`addTrait(string $trait)`Add trait to class`->addTrait('HasTeams')``addMethod(string $name, array $params, string $body, string $visibility)`Add method with parameters`->addMethod('getName', [], 'return $this->name;')``addProperty(string $name, mixed $default, string $visibility, ?string $type)`Add typed property`->addProperty('status', 'active', 'protected', 'string')``addUseStatement(string $class, ?string $alias)`Add use statement`->addUseStatement('App\Services\Logger', 'ServiceLogger')``addConstant(string $name, mixed $value, string $visibility)`Add class constant`->addConstant('VERSION', '1.0', 'public')`### Array Property Operations

[](#array-property-operations)

MethodDescriptionExample`extendArrayProperty(string $property, array $additions)`Safely extend array properties`->extendArrayProperty('permissions', ['admin'])`### Change Operations

[](#change-operations)

MethodDescription`changeProperty(string $name, mixed $default, ?string $visibility, ?string $type)`Modify existing property`changeMethod(string $name, ?array $params, ?string $body, ?string $visibility)`Modify existing method`changeClassName(string $newName)`Change class name`changeNamespace(string $newNamespace)`Change namespace### Removal Operations

[](#removal-operations)

MethodDescription`removeProperty(string $name)`Remove property`removeMethod(string $name)`Remove method`removeTrait(string $trait)`Remove trait`removeConstant(string $name)`Remove constant### File Operations

[](#file-operations)

MethodDescription`save(?string $path)`Save modifications to file (original path if null)`backup(string $backupPath)`Create backup of original file`toString()`Return modified code as stringAdvanced Usage
--------------

[](#advanced-usage)

### Custom Modifiers

[](#custom-modifiers)

Extend PHP Sculptor with your own modification logic:

```
$sculptor->addModifier('custom_operation', function($modification) {
    return new MyCustomModifier($modification);
});
```

### Method Override Protection

[](#method-override-protection)

Methods are protected from accidental duplication by default:

```
// This will safely skip if 'getName' already exists
$sculptor->addMethod('getName', [], 'return $this->name;', 'public', false);

// This will override existing method
$sculptor->addMethod('getName', [], 'return $this->fullName;', 'public', true);
```

### Chaining Complex Modifications

[](#chaining-complex-modifications)

```
$result = Sculptor::make('src/Document.php')
    // Add logging functionality
    ->addUseStatement('App\Traits\Auditable')
    ->addTrait('Auditable')

    // Update class configuration
    ->extendArrayProperty('validationRules', ['title' => 'required', 'content' => 'string'])
    ->extendArrayProperty('config', ['auto_save' => true, 'version_control' => true])
    ->extendArrayProperty('observers', ['DocumentObserver', 'AuditObserver'])

    // Add business logic
    ->addMethod('publish', [], '$this->status = "published"; $this->save();', 'public')
    ->addMethod('isPublished', [], 'return $this->status === "published";', 'public')

    // Add utility methods
    ->addMethod('findByCategory', [
        ['name' => 'category', 'type' => 'string'],
        ['name' => 'limit', 'type' => 'int', 'default' => 10]
    ], 'return static::where("category", $category)->limit($limit)->get();', 'public static')

    ->save();
```

Best Practices
--------------

[](#best-practices)

1. **Use method chaining** for related modifications
2. **Group similar operations** together for readability
3. **Leverage array property extension** for configuration arrays and collections
4. **Create backups** before major modifications: `->backup('backup.php')`
5. **Test modifications** with `toString()` before saving

Error Handling
--------------

[](#error-handling)

PHP Sculptor includes built-in safety features:

- **File validation**: Ensures target files exist and are readable
- **Duplicate detection**: Prevents adding existing traits, methods, or properties
- **AST validation**: Ensures code remains syntactically valid
- **Override protection**: Methods require explicit override flag to replace existing implementations

License
-------

[](#license)

MIT License - see LICENSE file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance59

Moderate activity, may be stable

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

257d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/96448e93b82dd289db790940e0c854f656068fd999375d6f309b4af8c2850a4e?d=identicon)[malico](/maintainers/malico)

---

Top Contributors

[![yondifon](https://avatars.githubusercontent.com/u/35140079?v=4)](https://github.com/yondifon "yondifon (4 commits)")

---

Tags

phpstatic analysisastcode-generationcode-modification

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/malico-php-sculptor/health.svg)

```
[![Health](https://phpackages.com/badges/malico-php-sculptor/health.svg)](https://phpackages.com/packages/malico-php-sculptor)
```

###  Alternatives

[vimeo/psalm

A static analysis tool for finding errors in PHP applications

5.8k77.5M6.7k](/packages/vimeo-psalm)[ajthinking/archetype

Programmatically edit PHP and Laravel files.

2723.4M12](/packages/ajthinking-archetype)[atanamo/php-codeshift

A PHP code transformation toolkit based on 'PHP-Parser'

32158.4k1](/packages/atanamo-php-codeshift)[corveda/php-sandbox

A PHP library that can be used to run PHP code in a sandboxed environment

23483.5k2](/packages/corveda-php-sandbox)[psx/sandbox

PHP sandbox to execute a safe subset of the PHP programming language

1745.8k1](/packages/psx-sandbox)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
