### Install Nette PHP Generator Source: https://github.com/nette/php-generator/blob/master/readme.md Instructions for installing the Nette PHP Generator library using Composer. ```shell composer require nette/php-generator ``` -------------------------------- ### Create a Basic Class Source: https://github.com/nette/php-generator/blob/master/readme.md Example of creating a new PHP class named 'Demo' with basic properties like final, extends, and implements, along with comments and property-read annotations. ```php $class = new Nette\PhpGenerator\ClassType('Demo'); $class ->setFinal() ->setExtends(ParentClass::class) ->addImplement(Countable::class) ->addComment("Class description.\nSecond line\n") ->addComment('@property-read Nette\Forms\Form $form'); // generate code simply by typecasting to string or using echo: echo $class; ``` -------------------------------- ### Custom Printer Implementation Source: https://github.com/nette/php-generator/blob/master/readme.md Provides an example of creating a custom printer by extending the base Printer class and overriding properties to customize formatting behavior. ```php class MyPrinter extends Nette\PhpGenerator\Printer { // length of the line after which the line will break public int $wrapLength = 120; // indentation character, can be replaced with a sequence of spaces public string $indentation = "\t"; // number of blank lines between properties public int $linesBetweenProperties = 0; // number of blank lines between methods public int $linesBetweenMethods = 2; // number of blank lines between 'use statements' groups for classes, functions, and constants public int $linesBetweenUseTypes = 0; // position of the opening curly brace for functions and methods public bool $bracesOnNextLine = true; // place one parameter on one line, even if it has an attribute or is supported public bool $singleParameterOnOneLine = false; // omits namespaces that do not contain any class or function public bool $omitEmptyNamespaces = true; // separator between the right parenthesis and return type of functions and methods public string $returnTypeColon = ': '; } ``` -------------------------------- ### PHP Property Hooks Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates the creation of property hooks for 'get' and 'set' operations in PHP 8.4. This includes defining hook bodies, parameters, and setting abstract or final modifiers for hooks. ```php $class = new Nette\PhpGenerator\ClassType('Demo'); $prop = $class->addProperty('firstName') ->setType('string'); $prop->addHook('set', 'strtolower($value)') ->addParameter('value') ->setType('string'); $prop->addHook('get') ->setBody('return ucfirst($this->firstName);'); echo $class; ``` ```php class Demo { public string $firstName { set(string $value) => strtolower($value); get { return ucfirst($this->firstName); } } } ``` ```php $class->addProperty('id') ->setType('int') ->addHook('get') ->setAbstract(); $class->addProperty('role') ->setType('string') ->addHook('set', 'strtolower($value)') ->setFinal(); ``` -------------------------------- ### Configuring Method Parameters Source: https://github.com/nette/php-generator/blob/master/readme.md Explains how to configure individual method parameters using the `Parameter` class, covering default values, references, type hints, and variadic parameters. ```php $method->addParameter('items', []) // $items = [] ->setReference() // & $items = [] ->setType('array'); // array & $items = [] // function count(&$items = []) ``` ```php $method = $class->addMethod('count'); $method->setVariadic(true); $method->addParameter('items'); ``` -------------------------------- ### Creating Interfaces and Traits Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates how to create new interfaces and traits using the `InterfaceType` and `TraitType` classes. It also shows how to add traits to a class and configure their usage, including resolutions and comments. ```php $interface = new Nette\PhpGenerator\InterfaceType('MyInterface'); $trait = new Nette\PhpGenerator\TraitType('MyTrait'); ``` ```php $class = new Nette\PhpGenerator\ClassType('Demo'); $class->addTrait('SmartObject'); $class->addTrait('MyTrait') ->addResolution('sayHello as protected') ->addComment('@use MyTrait'); echo $class; ``` -------------------------------- ### Basic Function Generation Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates the basic creation of a PHP function using the GlobalFunction class and adding a return statement. ```php $function = new Nette\PhpGenerator\GlobalFunction('foo'); $function->addBody('return $a;'); echo $function; ``` -------------------------------- ### Configuring Method Signatures Source: https://github.com/nette/php-generator/blob/master/readme.md Details how to configure method signatures using the `Method` class, including setting visibility, return types, final keywords, comments, and attributes. ```php $method = $class->addMethod('count') ->addComment('Count it.') ->setFinal() ->setProtected() ->setReturnType('?int'); ``` -------------------------------- ### PHP File Generation Source: https://github.com/nette/php-generator/blob/master/readme.md Illustrates creating a PHP file, adding comments, setting strict types, and adding classes and functions. ```php $file = new Nette\PhpGenerator\PhpFile; $file->addComment('This file is auto-generated.'); $file->setStrictTypes(); // adds declare(strict_types=1) $class = $file->addClass('Foo\A'); $function = $file->addFunction('Foo\foo'); echo $file; ``` -------------------------------- ### Type Handling with Strings and Constants Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates how to set types for members or return types using string representations or predefined constants from the Type class. ```php use Nette\PhpGenerator\Type; $member->setType('array'); // or Type::Array; $member->setType('?array'); // or Type::nullable(Type::Array); $member->setType('array|string'); // or Type::union(Type::Array, Type::String) $member->setType('Foo&Bar'); // or Type::intersection(Foo::class, Bar::class) $member->setType(null); // removes the type ``` -------------------------------- ### Outputting Namespaces with PSR Printer Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to use the PsrPrinter to output a namespace in accordance with PSR standards. ```php echo (new Nette\PhpGenerator\PsrPrinter)->printNamespace($namespace); ``` -------------------------------- ### Add Promoted Parameters to Constructor Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates how to add promoted parameters to a class constructor, as introduced in PHP 8.0, including setting visibility. ```php $method = $class->addMethod('__construct'); $method->addPromotedParameter('name'); $method->addPromotedParameter('args', []) ->setPrivate(); ``` -------------------------------- ### Generating Global Functions Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates the creation of global functions using the `GlobalFunction` class. It covers setting the function body, adding parameters, and optionally using `PsrPrinter` for PSR-compliant output. ```php $function = new Nette\PhpGenerator\GlobalFunction('foo'); $function->setBody('return $a + $b;'); $function->addParameter('a'); $function->addParameter('b'); echo $function; // or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER // echo (new Nette\PhpGenerator\PsrPrinter)->printFunction($function); ``` -------------------------------- ### Using NettePhpGeneratorPsrPrinter Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates using the PsrPrinter class to generate PHP code that adheres to PSR-2, PSR-12, or PER coding standards. ```php $printer = new Nette\PhpGenerator\PsrPrinter; echo $printer->printClass($class); ``` -------------------------------- ### Class Manipulator Initialization Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates initializing the ClassManipulator with a ClassType object. ```php $class = new Nette\PhpGenerator\ClassType('Demo'); $manipulator = new Nette\PhpGenerator\ClassManipulator($class); ``` -------------------------------- ### Generating with Method Bodies (Requires nikic/php-parser) Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to load method bodies when generating classes or functions from existing ones, requiring the 'nikic/php-parser' package. ```php $class = Nette\PhpGenerator\ClassType::from(Foo::class, withBodies: true); $function = Nette\PhpGenerator\GlobalFunction::from('foo', withBody: true); ``` -------------------------------- ### Generating Method and Function Bodies Source: https://github.com/nette/php-generator/blob/master/readme.md Illustrates methods for setting the body of functions or methods, either by providing the entire body at once using `setBody()` or line by line using `addBody()`. ```php $function = new Nette\PhpGenerator\GlobalFunction('foo'); $function->addBody('$a = rand(10, 20);'); ``` -------------------------------- ### Add Constants and Properties to a Class Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to add constants and properties to a class, including setting their visibility, type, final status, and initial values or comments. ```php $class->addConstant('ID', 123) ->setProtected() // constant visibility ->setType('int') ->setFinal(); $class->addProperty('items', [1, 2, 3]) ->setPrivate() // or setVisibility('private') ->setStatic() ->addComment('@var int[]'); $class->addProperty('list') ->setType('?array') ->setInitialized(); // outputs '= null' ``` -------------------------------- ### Loading Entire PHP File from Code String (Requires nikic/php-parser) Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to load an entire PhpFile object from a string containing PHP code, including comments and strict types declarations. Requires 'nikic/php-parser'. ```php $file = Nette\PhpGenerator\PhpFile::fromCode(file_get_contents('classes.php')); ``` -------------------------------- ### Function Generation with Simple Placeholders Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to use simple placeholders (?) within the function body for dynamic value insertion, passing values as an array. ```php $str = 'any string'; $num = 3; $function = new Nette\PhpGenerator\GlobalFunction('foo'); $function->addBody('return substr(?, ?);', [$str, $num]); echo $function; ``` -------------------------------- ### Add Methods to a Class Source: https://github.com/nette/php-generator/blob/master/readme.md Illustrates how to add methods to a class, including setting return types, visibility, body, parameters, and parameter types. ```php $method = $class->addMethod('count') ->addComment('Count it.') ->setFinal() ->setProtected() ->setReturnType('?int') // return types for methods ->setBody('return count($items ?: $this->items);'); $method->addParameter('items', []) // $items = [] ->setReference() // & $items = [] ->setType('array'); // array & $items = [] ``` -------------------------------- ### Asymmetric Visibility for PHP Properties Source: https://github.com/nette/php-generator/blob/master/readme.md Explains and demonstrates how to set asymmetric visibility for PHP properties (PHP 8.4), allowing different access levels for reading and writing using `setVisibility` or specific visibility methods. ```php $class = new Nette\PhpGenerator\ClassType('Demo'); $class->addProperty('name') ->setType('string') ->setVisibility('public', 'private'); // public for read, private for write $class->addProperty('id') ->setType('int') ->setProtected('set'); // protected for write echo $class; ``` ```php class Demo { public private(set) string $name; protected(set) int $id; } ``` -------------------------------- ### Outputting PHP Files with PSR Printer Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to use the PsrPrinter to output a PHP file in accordance with PSR standards. ```php echo (new Nette\PhpGenerator\PsrPrinter)->printFile($file); ``` -------------------------------- ### Clone Existing Members Source: https://github.com/nette/php-generator/blob/master/readme.md Explains how to clone existing methods, properties, and constants under a different name within a class using the cloneWithName() method. ```php $methodCount = $class->getMethod('count'); ``` -------------------------------- ### Loading Class from PHP Code String Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates creating a ClassType object by parsing a string containing PHP code. ```php $class = Nette\PhpGenerator\ClassType::fromCode(<<printClass($class); ``` -------------------------------- ### Function Generation with Variadic Placeholders Source: https://github.com/nette/php-generator/blob/master/readme.md Illustrates the use of the variadic placeholder (...) for passing arrays as individual arguments to a function. ```php $items = [1, 2, 3]; $function = new Nette\PhpGenerator\GlobalFunction('foo'); $function->setBody('myfunc(...?);', [$items]); echo $function; ``` -------------------------------- ### Using Literals for Default Values Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to use the Literal class to insert raw PHP code as default values for properties or in other contexts where dynamic code generation is needed. ```php use Nette\PhpGenerator\Literal; $class = new Nette\PhpGenerator\ClassType('Demo'); $class->addProperty('foo', new Literal('Iterator::SELF_FIRST')); $class->addMethod('bar') ``` -------------------------------- ### Generating Function from Existing Function Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates creating a GlobalFunction object based on an existing PHP function (e.g., trim). ```php $function = Nette\PhpGenerator\GlobalFunction::from('trim'); ``` -------------------------------- ### Generating Closure from Existing Closure Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates creating a Closure object based on an existing PHP closure. ```php $closure = Nette\PhpGenerator\Closure::from( function (stdClass $a, $b = null) {}, ); ``` -------------------------------- ### Function Generation with Named Variadic Placeholders (PHP 8+) Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates using named variadic placeholders (...?:) for passing associative arrays as named arguments to a function, specifically for PHP 8 and later. ```php $items = ['foo' => 1, 'bar' => true]; $function->setBody('myfunc(...?:);', [$items]); // myfunc(foo: 1, bar: true); ``` -------------------------------- ### PHP Code Generation with Literals Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates generating PHP code using Literal objects, including passing parameters and creating new object instances. This is useful for embedding dynamic or complex expressions directly into generated code. ```php class Demo{ public $foo = Iterator::SELF_FIRST; public function bar($id = 1 + 2) { } } ``` ```php new Literal('substr(?, ?)', [ $a, $b ]); // generates for example: substr('hello', 5); ``` ```php Literal::new(Demo::class, [ $a, 'foo' => $b ]); // generates for example: new Demo(10, foo: 20) ``` -------------------------------- ### Creating Enums (PHP 8.1+) Source: https://github.com/nette/php-generator/blob/master/readme.md Illustrates the creation of PHP 8.1 enums using the `EnumType` class. It covers adding enum cases and defining scalar equivalents for backed enums, along with adding comments or attributes to cases. ```php $enum = new Nette\PhpGenerator\EnumType('Suit'); $enum->addCase('Clubs'); $enum->addCase('Diamonds'); $enum->addCase('Hearts'); $enum->addCase('Spades'); echo $enum; ``` ```php $enum->addCase('Clubs', '♣'); $enum->addCase('Diamonds', '♦'); ``` -------------------------------- ### Class Generation with Namespace Aliasing Source: https://github.com/nette/php-generator/blob/master/readme.md Illustrates generating a class within a namespace, including aliasing used classes and traits, and simplifying type hints. ```php $namespace = new Nette\PhpGenerator\PhpNamespace('Foo'); $namespace->addUse('Bar\AliasedClass'); $class = $namespace->addClass('Demo'); $class->addImplement('Foo\A') // will be simplified to A ->addTrait('Bar\AliasedClass'); // will be simplified to AliasedClass $method = $class->addMethod('method'); $method->addComment('@return ' . $namespace->simplifyType('Foo\D')); // we manually simplify in comments $method->addParameter('arg') ->setType('Bar\OtherClass'); // will be translated to \Bar\OtherClass echo $namespace; ``` -------------------------------- ### Namespace Name Resolution Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates how to resolve a name within a namespace, showing the resulting fully qualified name. ```php $namespace = new Nette\PhpGenerator\PhpNamespace('iter'); echo $namespace->resolveName('range', $namespace::NameFunction); // 'iter\range' ``` -------------------------------- ### Using NettePhpGeneratorPrinter Source: https://github.com/nette/php-generator/blob/master/readme.md Shows the basic usage of the Printer class to generate PHP code for a ClassType object. The default Printer formats code according to Nette's coding standards. ```php $class = new Nette\PhpGenerator\ClassType('Demo'); // ... $printer = new Nette\PhpGenerator\Printer; echo $printer->printClass($class); // same as: echo $class ``` -------------------------------- ### Generating Class from Existing Class Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates creating a ClassType object based on an existing PHP class (e.g., PDO). ```php $class = Nette\PhpGenerator\ClassType::from(PDO::class); ``` -------------------------------- ### Add Existing Members to a Class Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to add pre-existing Method, Property, or Constant objects to a class using the addMember() method. ```php $method = new Nette\PhpGenerator\Method('getHandle'); $property = new Nette\PhpGenerator\Property('handle'); $const = new Nette\PhpGenerator\Constant('ROLE'); $class = (new Nette\PhpGenerator\ClassType('Demo')) ->addMember($method) ->addMember($property) ->addMember($const); ``` -------------------------------- ### PHP Namespace Management Source: https://github.com/nette/php-generator/blob/master/readme.md Details the usage of the PhpNamespace class for organizing PHP code elements like classes, interfaces, and traits. It covers adding elements, defining use statements, and simplifying/resolving names within namespaces. ```php $namespace = new Nette\PhpGenerator\PhpNamespace('Foo'); // create new classes in the namespace $class = $namespace->addClass('Task'); $interface = $namespace->addInterface('Countable'); $trait = $namespace->addTrait('NameAware'); // or insert an existing class into the namespace $class = new Nette\PhpGenerator\ClassType('Task'); $namespace->add($class); ``` ```php // use Http\Request; $namespace->addUse(Http\Request::class); // use Http\Request as HttpReq; $namespace->addUse(Http\Request::class, 'HttpReq'); // use function iter\range; $namespace->addUseFunction('iter\range'); ``` ```php echo $namespace->simplifyName('Foo\Bar'); // 'Bar', because 'Foo' is the current namespace echo $namespace->simplifyName('iter\range', $namespace::NameFunction); // 'range', due to the defined use-statement ``` ```php echo $namespace->resolveName('Bar'); // 'Foo\Bar' ``` -------------------------------- ### Generating Anonymous Functions (Closures) Source: https://github.com/nette/php-generator/blob/master/readme.md Explains how to generate anonymous functions (closures) using the `Closure` class. This includes setting the body, adding parameters, and using the `use` clause with references. ```php $closure = new Nette\PhpGenerator\Closure; $closure->setBody('return $a + $b;'); $closure->addParameter('a'); $closure->addParameter('b'); $closure->addUse('c') ->setReference(); echo $closure; // or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER // echo (new Nette\PhpGenerator\PsrPrinter)->printClosure($closure); ``` -------------------------------- ### PHP Attributes Generation Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to add PHP 8 attributes to various code elements like classes, methods, properties, and parameters using the Nette PHP Generator. It illustrates using literals within attribute parameters. ```php $class = new Nette\PhpGenerator\ClassType('Demo'); $class->addAttribute('Table', [ 'name' => 'user', 'constraints' => [ Literal::new('UniqueConstraint', ['name' => 'ean', 'columns' => ['ean']]), ], ]); $class->addProperty('list') ->addAttribute('Deprecated'); $method = $class->addMethod('count') ->addAttribute('Foo\Cached', ['mode' => true]); $method->addParameter('items') ->addAttribute('Bar'); echo $class; ``` ```php #[Table(name: 'user', constraints: [new UniqueConstraint(name: 'ean', columns: ['ean'])])] class Demo { #[Deprecated] public $list; #[Foo\Cached(mode: true)] public function count( #[Bar] $items, ) { } } ``` -------------------------------- ### Creating Anonymous Classes Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to generate anonymous classes by passing `null` as the class name to `ClassType`. It includes adding methods to the anonymous class definition. ```php $class = new Nette\PhpGenerator\ClassType(null); $class->addMethod('__construct') ->addParameter('foo'); echo '$obj = new class ($val) ' . $class . ';'; ``` -------------------------------- ### Function Generation with Escaped Placeholders Source: https://github.com/nette/php-generator/blob/master/readme.md Explains how to escape placeholders with a backslash (\?) to treat them as literal characters within the generated code, useful for conditional operators. ```php $num = 3; $function = new Nette\PhpGenerator\GlobalFunction('foo'); $function->addParameter('a'); $function->addBody('return $a \? 10 : ?;', [$num]); echo $function; ``` -------------------------------- ### Dump Variable to PHP Code Source: https://github.com/nette/php-generator/blob/master/readme.md The `Dumper` class converts a PHP variable into a string of parseable PHP code, offering a more readable output than `var_export()`. It's useful for debugging or generating configuration files. ```php $dumper = new Nette\PhpGenerator\Dumper; $var = ['a', 'b', 123]; echo $dumper->dump($var); // outputs ['a', 'b', 123] ``` -------------------------------- ### Generating Short Arrow Functions Source: https://github.com/nette/php-generator/blob/master/readme.md Shows how to generate short anonymous functions (arrow functions) using the `Printer`'s `printArrowFunction` method. ```php $closure = new Nette\PhpGenerator\Closure; $closure->setBody('$a + $b'); $closure->addParameter('a'); $closure->addParameter('b'); echo (new Nette\PhpGenerator\Printer)->printArrowFunction($closure); ``` -------------------------------- ### Implement Interface or Abstract Class Source: https://github.com/nette/php-generator/blob/master/readme.md The `implement()` method automatically adds all methods and properties from a specified interface or abstract class to the current class. This ensures the class adheres to the contract defined by the interface or abstract class. ```php $manipulator->implement(SomeInterface::class); // Now your class implements SomeInterface and includes all its methods ``` -------------------------------- ### Inherit Method from Parent/Interface Source: https://github.com/nette/php-generator/blob/master/readme.md The `inheritMethod()` method copies a method signature from a parent class or interface into the current class. This allows for overriding or extending the method's signature. It returns a `MethodManipulator` object for further modification. ```php $method = $manipulator->inheritMethod('bar'); $method->setBody('...'); ``` -------------------------------- ### Inherit Property from Parent Source: https://github.com/nette/php-generator/blob/master/readme.md The `inheritProperty()` method copies a property from a parent class into the current class. This is useful for maintaining consistency or providing a different default value. It returns a `PropertyManipulator` object for further modification. ```php $property = $manipulator->inheritProperty('foo'); $property->setValue('new value'); ``` -------------------------------- ### Disabling Type Resolving Source: https://github.com/nette/php-generator/blob/master/readme.md Demonstrates how to disable automatic type resolving for class generation. ```php $printer = new Nette\PhpGenerator\Printer; // or PsrPrinter $printer->setTypeResolving(false); echo $printer->printNamespace($namespace); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.