GithubHelp home page GithubHelp logo

phpowermove / php-code-generator Goto Github PK

View Code? Open in Web Editor NEW
146.0 146.0 43.0 1.86 MB

PHP code generator library

Home Page: https://php-code-generator.readthedocs.org

License: Apache License 2.0

PHP 99.72% Shell 0.23% Hack 0.05%
code-generation code-generator php

php-code-generator's People

Contributors

gossi avatar hhashimoto avatar marcj avatar matak avatar moufmouf avatar nmpolo avatar ocramius avatar pulzarraider avatar robingeuze avatar schmittjoh avatar scrutinizer-auto-fixer avatar seldaek avatar sidux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-code-generator's Issues

Looking for a way to read global functions

Hello,

My team has been using this library while writing a refactoring tool and we came across an issue.

We have several legacy code files which contain global functions and/or global scope code (I know...I know....we're working on fixing it). The tool we're writing needs to ingest these files and break them up into model objects that represent a given code file.

We've tried using this libraries PhpClass::FromFile method, but this doesn't appear to capture global functions/code.

Is there any way to do so using the tools in this library? Something like a PhpFile::FromFile method?

PhpParameter::fromReflection() doesn't take default parameter values

Ill try to explain. When creating a method from reflection default parameter gets messed up.

When I have a class with a default

class SomeClass {

    public function someMethod($someOptionalParameter = null) {
    return true;
    }

}

use gossi\codegen\model\PhpClass;
use gossi\codegen\generator\CodeFileGenerator;

$phpClass = PhpClass::fromReflection(new ReflectionClass("SomeClass"));
$gen = new CodeFileGenerator();

echo $gen->generate($phpClass);

Will produce:

class SomeClass {

    /**
     * @param mixed $someOptionalParameter
     */
    public function someMethod($someOptionalParameter = ) {
        return true;
    }
}

Where as you can notice the default value is missing.

Hope this helps.

Guess the problematic area is PhpParameter::fromReflection() line 64

Comment out method

Is there anyway to set a method so that it's commented out at creation? So like:

class myClass extends otherClass
{
    //private function _actionGet(CommandContext $context)
    //{
    //
    //}
}

I want to generate some code with default functions that I might not end up using and can just uncomment them if I need to.

SetBody - How to write multiple line in a class/function.

I don't know if it's issue or not. But I don't how to add multiple line my class function.

I have tried :
->setBody('$this->driver = $driver') ->setBody('$this->driver2 = $driver2');

But it didn't work, it only takes the last one. Sure more would be great, but so far it a pretty system.

Bug: Can't read boolean values

The code parser isn't able to detect boolean (true/false) values and set them properly via setExpression() as a result the output code will be empty and generates a parse error.

Post Processing?

Implement a post-processing pipeline where several tasks can be plugged in (configurable via CodeGeneratorConfig).

Possible tasks:

  • Code formatting (#23)
  • ?

Please share your thoughts.

Some suggestions

Just used your library to generate some of my doctrine entities. Overall I was very pleased with how things worked. A few suggestions though:

1.) Need a way to insert a blank line in a docblock. Some of my docblocks are really cluttered since there isn't any spacing between various sections.

2.) Took me a while to figure out that the setType method for PhpMethod was the return type. Better documentation or better naming (like setReturnType) would be work.

3.) Need a way to disable non-scalar type hints as well. The work around was to not declare a type for the parameters, and then add a param tag to the docblock.

4.) Not sure why, but, phpstorm thinks the getDocBlock methods are protected, and complains.

5.) Since you have concrete classes for different docblock tags (ParamTag, PropertyTag, etc), you should tailor their create methods to the standards for those types. For example, the ParamTag::create would take in a variable name, and, optionally, a type. Otherwise, there really isn't an advantage to using those instead of the TagFactory.

Drop fromReflection() methods

Parsing via fromFile() and PhpParser is much more reliable, needs less clutter, less "extra" code and will take place over fromReflection().

Library requires abandoned packages

Hi,

First of all, I'd like to thank the author of this library. Not only does this seem to support traits and interfaces, which is exactly what I'm looking for, but from what I can see, many if not all private properties have been refactored to protected. This is much better, and is really in line with my own philosophy: why deny the user of your code the ability to change things in their extension of your code? In the light of these and many other things, this library is superior to the once great schmittjoh/cg-library.

Now, to the problem. When running composer install with this package required, I get the following message:

Package gossi/common is abandoned, you should avoid using it. Use phootwork/lang instead.
Package gossi/collection is abandoned, you should avoid using it. Use phootwork/collection instead.

This is the first time I got something like this, so 2 questions:

  1. Are these packages really abandoned, and the phootwork packages are superior?
  2. If abandoned, will this problem be resolved? If it won't, I assume I cannot just switch to using the phootwork packages; am I right?

set unescaped property default value

I'd like to be able to generate a property that is an array that uses constants for keys, like

    public static $fooBar = [
        Foo::FOO => 'foo',
        Foo::BAR => 'bar',
    ];

it would be nice to be able to pass in something that is not automatically escaped via var_export

How to preserve new lines in method body?

Hi, wonderfull library, but after several hours, i realize that i cant use it.

I would like to use this library to scaffolding my code. With help of AutoIt I want to replace the whole code in text window with scaffolded dependency injection of use statements etc.

But the problem is, that it is not possible to preserve the new lines and whitespaces in the body of methods, is it true? Am I right?

So when i want to update this code

public function renderDefault()
{
	$stockinRow = $this->stockinRepositoryService->findById($this->stockin_id);
		
	$pageHeader = $this['pageHeader'];
	$pageHeader->setTitle("Naskladnění [" . $stockinRow->id . "] " . $stockinRow->dateArrival->format("d.m.Y") . " , profil dodavatele: " . $stockinRow->supplierProfile->name);

	$template = $this->template;
	$template->dataStockinItems = $this->stockinItemRepositoryService->selectAll()->where("stockin_id = ?", $this->stockin_id)->order("EAN ASC")->fetchAll();
}

I get this code,

public function renderDefault() {
	$stockinRow = $this->stockinRepositoryService->findById($this->stockin_id);
	$pageHeader = $this['pageHeader'];
	$pageHeader->setTitle("Naskladnění [" . $stockinRow->id . "] " . $stockinRow->dateArrival->format("d.m.Y") . " , profil dodavatele: " . $stockinRow->supplierProfile->name);
	$template = $this->template;
	$template->dataStockinItems = $this->stockinItemRepositoryService->selectAll()->where("stockin_id = ?", $this->stockin_id)->order("EAN ASC")->fetchAll();
}

so quite messy. Can I somehow prevent it?

As i searched in code, it seems that builder knows that originally the row was on line 31 and next row was on line 33, so there should be new line string.

Update descriptions when calling fromFile()

When code is read through fromFile() method. The description for params, properties, etc. is in the docblock. When visiting these, they should read their descriptions from the already parsed docblock.

No way to set function/method body?

Would there be any interest in allowing a body to be set?

PhpMethod::create('__construct')->setBody(function($property) { ?>
    $this->get('<?= $property ?>');
<?php });

Consider tagging a release

Hi @gossi !

Two packages are dependent on php-code-generator (list here).
There is no release tagged and that means that users using those packages must add

"minimum-stability": "dev",
"prefer-stable": true,

to their composer.json file.

This can be an issue for several users (see here: Wabel/zoho-crm-orm#7)

Would you consider tagging a release (maybe a 0.1.0 or even 0.0.1 if you don't consider your package fully stable yet?) That would help users of your package a lot!

Best regards,
David.

// cc @WizMik

Value vs. Expression

In every case, where values are possible (e.g. constant, parameter and property values) there can also be expressions, which are valid, some examples:

// value:
const FOO = 'bar';

// expr:
const FOO = self::BAR;

yet, this isn't realizable with the current API, as the API only works with values (though var_export() is used). This is very tricky. The following is absolutely legal:

$const->setValue('self::BAR');

// will turn into:

const FOO = 'self::BAR';

Would make sense to differentiate between them by adding a new method setExpression():

$const->setExpression('self::BAR');

// will turn into:

const FOO = self::BAR;

This would work pretty easy for simple statements, what about complex ones (e.g. nested arrays?, see also #10).

Ideas?

Fully qualified interface name changed to relative name

The following code leads to the fully qualified interface name used in the class being converted into a relative name.

// TestClass.php -----------------------------------------
<?php

namespace Test;

class TestClass implements \Test\TestInterface
{

}

// TestInterface.php -----------------------------------------
<?php

namespace Test;

interface TestInterface
{

}

// Run.php -----------------------------------------
<?php

require_once '../vendor/autoload.php';

use gossi\codegen\generator\CodeGenerator;
use gossi\codegen\model\PhpClass;

$class = PhpClass::fromFile('TestClass.php');

$generator = new CodeGenerator();
$code = $generator->generate($class);

echo $code;

// Output -----------------------------------------
namespace Test;

/**
 */
class TestClass implements Test\TestInterface {
}

If you need any further info please let me know.

Cheers

Indentation (Tab and Space)

Hi there!
Just started using it, and it's awesome for what i'm doing.

However, the indentation is done with tabs, any chance of adding a config that will allow me (and others) to switch it to spaces? :)

Empty Comments are automaticly added (PHPDoc)

No matter if I load a Class from a file or create a complete new one like in the example from the documentation, if a method/class does not have a comment, it will always get an empty one /** */

More API docs

Code needs more docblocks for better API docs, since they are available now.

More consistent API

The API for most php structs works like this (method as example, but also for properties, constants, etc... you name it):

  • setMethod($method)
  • getMethod($nameOrMethod)
  • removeMethod($nameOrMethod)
  • getMethods()
  • setMethods()

while setMethod() is technically the correct name, adding is the action we have in mind. Although, sometimes getMethods() returns different value types. Sometimes that is ok (depending on the type we want to fetch) but most times there should be better method names for such tasks, e.g. getMethodNames().

There is time to work through this API, identify similar patterns and make the API consistent.

Simplify CodeGenerator / Strategy / Navigator / Visitor

This is still code from the old cg-library. Yet I added CodeGenerator in front of it and gave it a nice API to work with. While the Visitor Pattern still seems very good in that situation, it still looks too complex in total. Should be simplified by any means.

Ref #23

Updated dependencies, specifically nikic/php-parser

Using this library along with other things that use php-parser, we are now at the stage where php-parser has gone to version 4, but this library maxes out at version 3

For this library to continue to be useful, the dependencies need to be kept up to date

addSimpleParameter and addSimpleDescParameter functions

In gossi\codegen\model\parts\ParameterParts trait, addSimpleParameterand addSimpleDescParameter functions don't accept anymore arrays as default value.

<?php

$function = new PhpFunction();
$function->addSimpleDescParameter('param1', 'array', 'desc', array());

This use case throws an Exception, because at https://github.com/gossi/php-code-generator/blob/master/src/model/parts/ParametersPart.php#L82 and at https://github.com/gossi/php-code-generator/blob/master/src/model/parts/ParametersPart.php#L105 the instructions accept only primitive values.

Is it a desired behavior?
If yes, I'll refactor some Propel classes, otherwise I can submit a fix.

incompatible with php-parser v2.*

Please add support for php-parser v2.*

Problem 1
    - Installation request for gossi/php-code-generator ^0.3.2 -> satisfiable by gossi/php-code-generator[v0.3.2].
    - Conclusion: remove nikic/php-parser v2.1.1
    - Conclusion: don't install nikic/php-parser v2.1.1
    - gossi/php-code-generator v0.3.2 requires nikic/php-parser ~1 -> satisfiable by nikic/php-parser[v1.0.0, v1.0.1, v1.0.2, v1.1.0, v1.2.0, v1.2.1, v1.2.2, v1.3.0, v1.4.0, v1.4.1].
    - Can only install one of: nikic/php-parser[v1.2.1, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.2.2, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.3.0, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.4.0, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.4.1, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.0.0, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.0.1, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.0.2, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.1.0, v2.1.1].
    - Can only install one of: nikic/php-parser[v1.2.0, v2.1.1].
    - Installation request for nikic/php-parser (locked at v2.1.1) -> satisfiable by nikic/php-parser[v2.1.1].

[0.6-beta] Profiles and Code Formatter (psr-2)

Hello PSR-2 Lemmings,

I've got something for you. With v0.6-beta you will be able to use the profile configuration option to select a code style profile from gossi/php-code-profiles. Set it to psr-2. That said, I have no idea whether I configured this stupid space-oriented code style correctly, send PR to the referenced repo if something is wrong.

Second did I implemented the gossi/php-code-formatter as post processing after code generation. Activate it by setting the new enableFormatting option to true. It will use the given profile and run the formatting based on that. I started the php-code-formatter as an experiment back in time and it basically never went past that. Though I think this is still one of the best options today. Given that, the formatter is still very experimental and if you encounter something wrong, open an issue over there. If you want it fixed, send a PR (the wiki contains a good amount of documentation). Chances I will work on this are very, very low. Just you are aware of this.

Please share your experience using these two options and if there aren't any critical use-cases, I can turn this beta into stable.

Integrate with php-code-formatter

When generating code, the holy code-style (mine - of course!) is applied to the generated code, which is the most awesome default we can get. Yet, there are some other flavors around (especially brainless psr2-lemmings) which prefer different styles.

Interesstingly enough there is no good php code formatter around and that's why I created my php-code-formatter. It basically startet as an experiment, yet has grown but still lacks a good chunk of functionality to be considered usable.
There are many code styles around and they all have different options, that's why I implemented profiles to combine different options under one name.

So, here are some ideas how to integrate with the php-code-formatter:

  • Generators are given a code-style profile name (or path to one) and pass this on to code-generation
  • Light-weight-code-generation-and-formatting: The generator-visitor (which dumps the initially generated code from the generator) uses this options from the profile and applies them on writing (which doesn't affect method bodies).
  • Full-code-generation-and-formatting: The generated code is run through the code-formatter in the post-processing.

Technically spoken: code-formatter and code-generator would share some code, which could be extracted into it's own package to avoid duplication, which seems good and doable.

I'm wondering what you think?

Fix travis API deploy

Actually, travis should - after running tests - generate the API and push it to gh-pages branch. For some reasons, this does not work and I am unable to explain it myself.

Features adding suggestion

Hi,

I have some ideas if you approve of i will create a PR for it :

  • handle types by adding a PhpType interface that will be implemented by PhpClass and PhpInterface classes to be able to automatically add use statements
  • PhpMethod and PhpParameter type will be list of types merged from typehint and docblock (if we set multiple types we will use only doc block)
  • PhpClass getInterfaces return collection of PhpInterface objects
  • Auto add use statement when adding an interface to PhpClass

What do you think of this ?

Cheers,

PhpInterface::fromReflection requires custom code

I wanted to use PhpInterface::fromReflection on the SPL Interface Iterator, however I get an error.

Code:

$pInterface = PhpInterface::fromReflection(new \ReflectionClass(\Iterator::class));

Error:

file(): Filename cannot be empty

vendor/gossi/php-code-generator/src/utils/ReflectionUtils.php:78
vendor/gossi/php-code-generator/src/model/PhpInterface.php:31

I see that actually the Reflection Class is only used to retrieve the file in order to parse the file content.
Might want to update the documentation to warn devs about this behaviour :)

Share code between reflection and code parser

Both parts use similar code that is fragmented and duplicated across the multiple namespaces and classes at the moment, which is a bit ugly. Time to find these similar parts and refactor them. Also can help to fix #19 (as it may be required to parse class code). Also scrutinizer can be helpful to find similar parts.

Drop PhpFunction or add PhpFile

The question is how much is PhpFunction used at all? Basically, this library assumes, every code follows PSR-4 (1 file = 1 class/interface/trait). The only use case for functions would be to expect a function library anywhere, which would either require a PhpFile class, which itself would be capable of retrieving all classes, traits, interfaces, functions and constants from a file (as such no real php code block from such files) or drop the PhpFunction class, which is more likely to happen.

Feature Request: ReflectionLoader

Loading php structs through reflection can be tricky, because every dependency that a struct needs must be in classpath, too anyway php wil throw an error. A ReflectionLoader may be useful here, to support this. It would scan the desired file, parse all dependencies, sees which of them are already in classpath and returns a list of those who aren't. At best, it would also load them by itself, if possible.

Writer is not configurable enough

All Builders depend on the writer which just has 2 options (indentation) to configure the coding style with which the class/method/function etc. is build. Best example from ClassBuilder $this->writer->writeln(" {\n")->indent(); the written line should definitely be configurable in the writer e.g. if you want to have the bracket in a new line: "\n{".

Apart from this, very nice generator, like it!

Put function's start accolade on new line

Hi guys,

thanks for that lib, pretty usefull.

Is it possible to generate function like that ?

public function setEmail($email)
{
	$this->email = $email;
	return $this;
}

instead of that

public function setEmail($email) {
	$this->email = $email;
	return $this;
}

I 'd like the first accolade be on new line.

Is that possible ? I didn't find any parameter. Maybe overriding something ?

I got the same issue on the accolade of my class.

class User {

instead of

Class User
{

PhpProperty doesn't support expressions

In https://github.com/gossi/php-code-generator/blob/master/src/generator/builder/PropertyBuilder.php#L18 it only checks for a set value.

PhpProperty::create('myProp')
    ->setExpression('[0, 1]');

does not work in terms of it just doesn't write a default property value. I changed the code at line 18 to if ($model->hasValue() || $model->isExpression()) { and that fixed it.

Code Cleanup Version 0.5

Things to clean up for Version 0.5:

  • Remove parser\ValueParser
  • Remove fromReflection() methods in models package
  • Remove fromReflection() methods in test suite
  • Remove setUp() methods from test suite necessary for loading code from reflection

Remove attributes from AbstractModel

As attributes are there for more custom user attributes, I wonder if they really have a right to exist, since every attribute can also be carried in a users code and doesn't need to be attached to the model code. They will be marked deprecated for version 0.3 and removed the version after unless there are complaints in this issue.

Read use-statements

At the moment, the PhpParser from doctrine/annotations is used to read use statements from a given reflection class. This has a problem, because aliases are lowercased.

Ideas to fix this:

  1. Change doctrine-annotations parser: doctrine/common#341
  2. Search for other parsers
  3. Create a tokenizer package phpowermove/php-code-formatter#18 and include this logic at this package itself

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.