malico/php-sculptor
Composer 安装命令:
composer require malico/php-sculptor
包简介
Programmatically modify PHP code with a fluent, intuitive API
README 文档
README
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 package directly.
Why PHP Sculptor?
- Fluent API: Chain multiple modifications in a readable, expressive way
- Safe AST manipulation: Built on battle-tested
nikic/php-parserfor 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
composer require malico/php-sculptor
Requirements: PHP 8.0+ and nikic/php-parser ^5.0
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
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
// 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
// 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
Core Modification Methods
| Method | Description | Example |
|---|---|---|
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
| Method | Description | Example |
|---|---|---|
extendArrayProperty(string $property, array $additions) |
Safely extend array properties | ->extendArrayProperty('permissions', ['admin']) |
Change Operations
| Method | Description |
|---|---|
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
| Method | Description |
|---|---|
removeProperty(string $name) |
Remove property |
removeMethod(string $name) |
Remove method |
removeTrait(string $trait) |
Remove trait |
removeConstant(string $name) |
Remove constant |
File Operations
| Method | Description |
|---|---|
save(?string $path) |
Save modifications to file (original path if null) |
backup(string $backupPath) |
Create backup of original file |
toString() |
Return modified code as string |
Advanced Usage
Custom Modifiers
Extend PHP Sculptor with your own modification logic:
$sculptor->addModifier('custom_operation', function($modification) { return new MyCustomModifier($modification); });
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
$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
- Use method chaining for related modifications
- Group similar operations together for readability
- Leverage array property extension for configuration arrays and collections
- Create backups before major modifications:
->backup('backup.php') - Test modifications with
toString()before saving
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
MIT License - see LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
malico/php-sculptor 适用场景与选型建议
malico/php-sculptor 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「ast」 「static-analysis」 「code-generation」 「code-modification」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 malico/php-sculptor 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 malico/php-sculptor 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 malico/php-sculptor 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Editable JSON AST with visitor traversal and formatting-preserving printing.
Parse Handlebars templates to a spec-compliant AST with PHP.
Validates PHPDoc @param and @return tags against method signatures
Rules for the bdd-analyser CLI tool
A PHP security linter to detect insecure functions like var_dump, print_r, and other dangerous functions in your codebase
finding mismatch type assignment in function/method scope with psalm
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-09-03