Rector: [PSR-4] Add PSR-0 to PSR-4

Created on 11 Dec 2018  路  9Comments  路  Source: rectorphp/rector

Most helpful comment

@TomasVotruba I'm working on it right now. I'll send a PR here once I'm done.

All 9 comments

Closing as too vague to automate. This is better done manually, with human decission.

See #1170

It would be nice to have a rule that you can customize with configuration similar to how composer specifies PSR-0 autoloading: "Namespace_Prefix_": "folder/". I have several thousand files to move and I'm not sure that a regex will cut it.

I use composer.json PSR-4 paths, that do the same job. Just setup composer.json to PSR-4 paths with desired namespaces and run Rector.

E.g.

{
    "autoload": {
        "psr-4": {
            "TomasVotruba\\Blog\\": "packages/blog/src"
        }
}


Run the rule in the project root and rector will add TomasVotruba\Blog\ namespace to all files in packages/blog/src.


This one: https://github.com/rectorphp/rector/blob/master/docs/rector_rules_overview.md#normalizenamespacebypsr4composerautoloadfilesystemrector

I'm not sure how that solves the PSR-0 problem. This rector only normalizes the namespaces _if those are already defined_.

In almost all of my legacy projects, I have files organized into folders, no namespaces, and classnames are TomasVotruba_Blog_Post. I need to inject namespaces, then change the classnames and all references to them. That's what I mean by PSR-0 to PSR-4.

I'll just go ahead and write a rector.

This rector only normalizes the namespaces if those are already defined.

Not only, it also adds them.

I have files organized into folders

That's enough. Just setup composer.json and let Rector complete the namespaces.


I'm not sure I understand... maybe call? I'm here for next 30 minutes

Normal/Whatsapp: https://www.tomasvotruba.com/contact/

@afilina Based on our quick call, this is the rule you need.

Could you confirm if and what I missunderstood?

<?php

// src/SomeNamespace/SomeClass.php

+namespace App\SomeNamespace;

-class SomeInconsistentNamespace_SomeClass
+class SomeClass
 {
 }
<?php

// src/SomeNamespace/SomeClassFactory.php

+namespace App\SomeNamespace;

-class SomeNamespace_SomeClassFactory
+class SomeClassFactory
 {
     public function create()
     {
-        return new SomeInconsistentNamespace_SomeClass();
+        return new \App\SomeNamespace\SomeClass();
     }
 }


To define root namespace, the PSR-4 autoload has to be defined in composer.json:

{
    "autoload": {
        "psr-4": {
            "App\\SomeNamespace\\": "src"
        }
    }
}

Yes, that's the rule.

@TomasVotruba I'm working on it right now. I'll send a PR here once I'm done.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

carusogabriel picture carusogabriel  路  5Comments

pavarnos picture pavarnos  路  4Comments

darthf1 picture darthf1  路  3Comments

benr77 picture benr77  路  4Comments

calvera picture calvera  路  4Comments