Rector upgrades rules for Doctrine

Overview

Rector Rules for Doctrine

See available Doctrine rules

Install

This package is already part of rector/rector package, so it works out of the box.

All you need to do is install the main package, and you're good to go:

composer require rector/rector --dev

Use Sets

To add a set to your config, use Rector\Doctrine\Set\DoctrineSetList class and pick one of constants:

use Rector\Doctrine\Set\DoctrineSetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import(DoctrineSetList::DOCTRINE_CODE_QUALITY);
};

Read a First Book About Rector

Are you curious, how Rector works internally, how to create your own rules and test them and why Rector was born? In May 2021 we've released the very first book: Rector - The Power of Automated Refactoring.

By buying a book you directly support maintainers who are working on Rector.


Support

Rector is a tool that we develop and share for free, so anyone can automate their refactoring. But not everyone has dozens of hours to understand complexity of abstract-syntax-tree in their own time. That's why we provide commercial support - to save your time.

Would you like to apply Rector on your code base but don't have time for the struggle with your project? Hire us to get there faster.

Comments
  • Update test for MakeEntitySetterNullabilityInSyncWithPropertyRector

    Update test for MakeEntitySetterNullabilityInSyncWithPropertyRector

    Reproducer the MakeEntitySetterNullabilityInSyncWithPropertyRector currently is implemented uncorrectly. By default a ManyToOne is nullable="true" see https://github.com/doctrine/orm/blob/5283e1441cc020d526d4842c6bfa21c1a500886d/lib/Doctrine/ORM/Mapping/JoinColumn.php#L28 and so currently this rules accidently removes ? from a setter where it should not do it.

    PS: This error does not happening when using Attributes but maybe not a equal rule for attributes does exist?


    EDIT @TomasVotruba : Fixes https://github.com/rectorphp/rector/issues/7353, closes https://github.com/rectorphp/rector-doctrine/pull/123

    opened by alexander-schranz 13
  • [Set] Add doctrine orm 2.9 set

    [Set] Add doctrine orm 2.9 set

    Fixes https://github.com/rectorphp/rector-doctrine/issues/4 .

    ~~This is for starter. It may need more examples for usage, eg: join table, etc.~~ implemented 🎉

    opened by samsonasik 9
  • [Doctrine] Skip pointed to constant value on CorrectDefaultTypesOnEntityPropertyRector

    [Doctrine] Skip pointed to constant value on CorrectDefaultTypesOnEntityPropertyRector

    Given the following code:

    /**
     * @ORM\Entity()
     */
    class PointedToConstantValue
    {
        public const ONE = 1;
    
        /**
         * @ORM\Column(type="integer")
         */
        private $stav = self::ONE;
    
        /**
         * @ORM\Column(type="integer")
         */
        private $stav2 = SOME_CONSTANT_VALUE;
    }
    

    It currently make crash:

    There was 1 error:
    
    1) Rector\Doctrine\Tests\Rector\Property\CorrectDefaultTypesOnEntityPropertyRector\CorrectDefaultTypesOnEntityPropertyRectorTest::test with data set #0 (Symplify\SmartFileSystem\SmartFileInfo Object (...))
    Rector\Core\Exception\NotImplementedYetException: 
    

    This PR fix it. Fixes https://github.com/rectorphp/rector/issues/7227

    opened by samsonasik 8
  • ORM 2.9 Set doesn't properly convert `@UniqueConstraint` and `@Index` annotations to attributes

    ORM 2.9 Set doesn't properly convert `@UniqueConstraint` and `@Index` annotations to attributes

    I'm trying out the new ORM 2.9 upgrade set to convert Annotations to Attributes and I found a problem.

    Given I have the following entity:

    /** 
     * @ORM\Table(
     *     name="table",
     *     options={"charset": "utf8mb4", "collate": "utf8mb4_bin"},
     *     uniqueConstraints={
     *         @ORM\UniqueConstraint(name="unique_review", columns={"type", "relationship_id", "user_id"})
     *     },
     *     indexes={
     *         @ORM\Index(name="index_name", columns={"user_id", "type", "relationship_id", "created_at", "is_deleted"}),
     *     },
     * )
     */
    class SomeEntity
    

    Rector changes this to:

    #[Table(name: 'table', options: ['charset' => 'utf8mb4', 'collate' => 'utf8mb4_bin'], uniqueConstraints: ['(name="unique_review", columns={"type", "relationship_id", "user_id"})'], indexes: ['(name="index_name", columns={"user_id", "type", "relationship_id", "created_at", "is_deleted"})'], ')')]
    class SomeEntity
    

    As you can see, it completely trips on the nested annotations. And just dumps them in as strings.

    Turns out that nested attributes are not supported.

    The solution would be, to move the nested annotations to attributes on a new line, like this:

    #[Table(name: 'table', options: ['charset' => 'utf8mb4', 'collate' => 'utf8mb4_bin'])]
    #[UniqueConstraint(name: 'unique_review', columns=['type', 'relationship_id', 'user_id']]
    #[Index(name: 'index_name', columns=['user_id', 'type', 'relationship_id', 'created_at', 'is_deleted'])]
    class SomeEntity
    

    To mitigate this bug, I tried to first manually convert the nested Annotations to Class Annotations. But Doctrine doesn't allow that:

    /** 
     * @ORM\Table(name="table", options={"charset": "utf8mb4", "collate": "utf8mb4_bin"})
     * @ORM\UniqueConstraint(name="unique_review", columns={"type", "relationship_id", "user_id"})
     * @ORM\Index(name="index_name", columns={"user_id", "type", "relationship_id", "created_at", "is_deleted"})
     */
    class SomeEntity
    
    [Semantical Error] Annotation @ORM\UniqueConstraint is not allowed to be declared on class SomeEntity. 
    You may only use this annotation on these code elements: ANNOTATION.
    

    That also means that these examples are impossible/invalid: https://github.com/rectorphp/rector-doctrine/blob/main/tests/Set/DoctrineORM29Set/Fixture/unique_constraint.php.inc https://github.com/rectorphp/rector-doctrine/blob/main/tests/Set/DoctrineORM29Set/Fixture/index.php.inc

    opened by ruudk 8
  • ManyToOne relations with JoinColumns are not being replaced with an array of JoinColumn

    ManyToOne relations with JoinColumns are not being replaced with an array of JoinColumn

    Looks like there's a bug on the ManyToOne relation with the JoinColumns annotation which ends out with the following error.

    [Syntax Error] Expected PlainValue, got '(' at position 166 in property App\Entity\Product::$inventoryPosition.

    The documentation says the @JoinColumns needs an array of JoinColumn:

    An array of @JoinColumn annotations for a @ManyToOne or @OneToOne relation with an entity that has multiple identifiers.

    Take a look the code below removing the @ORM\JoinColumn annotation.

         /**
          * @var InventoryPosition
          *
          * @ORM\ManyToOne(targetEntity="App\Entity\InventoryPosition", inversedBy="products", cascade={"persist"})
    -     * @ORM\JoinColumns({
    -     *   @ORM\JoinColumn(name="inventory_position_id", referencedColumnName="id")
    -     * })
    +     * @ORM\JoinColumns({(name="inventory_position_id")})
          */
    -    private $inventoryPosition;
    +    private ?\App\Entity\InventoryPosition $inventoryPosition = null;
    

    I'm using the DoctrineSetList::DOCTRINE_CODE_QUALITY setlist

    opened by pedrocasado 7
  • Failing tests for #16

    Failing tests for #16

    See https://github.com/rectorphp/rector-doctrine/issues/16

    @UniqueConstraint and @Index cannot be used on a class but must be used inside an annotation.

    For attributes, that's the opposite, they must be declared on the class instead.

    See docs https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/attributes-reference.html#attrref_joincolumn

    opened by ruudk 6
  • Fix TypedPropertyFromToManyRelationTypeRector with no property

    Fix TypedPropertyFromToManyRelationTypeRector with no property

    Fixes https://github.com/rectorphp/rector-doctrine/pull/76

    • Dont Touch Unrelated Code by TypedPropertyFromToManyRelationTypeRector unit test
    • Fix empty typed property in TypedPropertyFromToManyRelationTypeRector
    opened by TomasVotruba 5
  • Fix resolving doctrine target entities with omitted leading backslash

    Fix resolving doctrine target entities with omitted leading backslash

    In the past doctrine recommended using class strings with omitted leading backslash. Hence, we have to check again for that class with added backslash. See https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#entity for an example.

    I think when configured a while back ago, class-strings without leading backslash is very common.

    opened by dritter 4
  • RemoveRedundantDefaultPropertyAnnotationValuesRector with JoinColumn

    RemoveRedundantDefaultPropertyAnnotationValuesRector with JoinColumn

    This rule is removing JoinColumn annotation

    -     * @ORM\JoinTable(name="vouchers_subscriptions",
    -     *     joinColumns={@ORM\JoinColumn(name="voucher_id", referencedColumnName="id")},
    -     *     inverseJoinColumns={@ORM\JoinColumn(name="subscription_id", referencedColumnName="id")}
    -     *     )
    +     * @ORM\JoinTable(name="vouchers_subscriptions", joinColumns={(name="voucher_id")}, inverseJoinColumns={(name="subscription_id", referencedColumnName="id")})
    

    But in the doc it needs of JoinColumn

    https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/association-mapping.html#many-to-many-unidirectional

    opened by eerison 4
  • Nested annotation to attribute support

    Nested annotation to attribute support

    PHP 8.1 introduced a way to handle nested attributes, something missing from the 8.0 implementation and needed for some Doctrine annotations.

    Doctrine has the annotation, @ORM\JoinColumns, used like so:

    @ORM\JoinColumns({
        @ORM\JoinColumn(name="thing_id", referencedColumnName="id", nullable=false)
    })
    

    Currently, the DoctrineAnnotationClassToAttributeRector skips over this annotation, presumably due to PHP 8.0's lack of nested attribute support. Is there an update on supporting this or a plan in place?

    opened by oojacoboo 4
  • Unexpected refractoring of nullable datetime field

    Unexpected refractoring of nullable datetime field

    When running rector with the doctrine exension:

        $containerConfigurator->import(DoctrineSetList::DOCTRINE_CODE_QUALITY);
    
    1) src/Cashback/Domain/Model/CashbackClaim.php:57
    
        ---------- begin diff ----------
    @@ @@
         /**
          * @ORM\Column(type="datetime", nullable=true)
          */
    -    private ?DateTimeInterface $orderDetailsOrderDate = null;
    +    private ?DateTimeInterface $orderDetailsOrderDate;
    
         /**
          * @ORM\Column(length="256")
    @@ @@
    
    @@ @@
         {
             $uuid = Uuid::uuid4();
             $this->entityId = $uuid->toString();
    +        $this->orderDetailsOrderDate = new \DateTime(null);
         }
    

    The result is unexpected as it did add:

    $this->orderDetailsOrderDate = new \DateTime(null);
    

    Which should just stay as:

    private ?DateTimeInterface $orderDetailsOrderDate = null;
    
    opened by alexander-schranz 4
  • Add rule to update string events with constants

    Add rule to update string events with constants

    Lets add a rule to replace event strings with the corresponding class constants (Just like the Criteria constants)

    <?php
    
    declare(strict_types=1);
    
    namespace App\Subscriber\Doctrine;
    
    use Doctrine\Common\EventSubscriber;
    use Doctrine\ORM\Event\LifecycleEventArgs;
    use Doctrine\ORM\Event\PreUpdateEventArgs;
    +use Doctrine\ORM\Events;
    
    class DoctrineSubscriber implements EventSubscriber
    {
    
        public function getSubscribedEvents(): array
        {
            return [   
    -            'prePersist',
    -            'preUpdate',
    +            Events::prePersist,
    +            Events::preUpdate,
            ];
        }
    
        public function prePersist(LifecycleEventArgs $args) {
            //...
        }
        public function preUpdate(PreUpdateEventArgs $eventArgs) {
            //...
        }
    }
    

    I'll see if I can implement this in the future

    opened by stefantalen 4
  • Add DoctrinePHPDocInfoRector to fix Entity PHPDoc by Doctrine Metadata

    Add DoctrinePHPDocInfoRector to fix Entity PHPDoc by Doctrine Metadata

    Similar to https://github.com/rectorphp/rector-phpunit/pull/114, https://github.com/rectorphp/rector-phpunit/pull/114 / https://github.com/rectorphp/rector-phpunit/pull/115

    I would like to set the PHPDocInfo @var based on doctrine metadata. Via phpstan-doctrine phpstan already knows the correct type from the Doctrine Metadata () which should be set to the property and getter of that property.

    I'm not yet sure how I can access the expected PHPStan type. Any hints how to achieve this would be welcome.

    opened by alexander-schranz 1
Phpcs-magento-rules - A set of PHPCS rules used by made.com when hacking Magento

Made.com PHPCS Magento Rules A set of PHPCS rules used by made.com when hacking Magento. Pre-Requisites PHPCS Installation Short Version Clone this re

Made.com Tech Team 26 Jun 3, 2020
A Pocketmine-MP (PMMP) plugin to help staff members enforce the rules of the server.

StaffMode is an all-in-one Pocketmine-MP (PMMP) moderation plugin made to simplify the life of staff members.

ItsMax123 9 Sep 17, 2022
Rules to detect game engines and other technologies based on Steam depot file lists

SteamDB File Detection Rule Sets This is a set of scripts that are used by SteamDB to make educated guesses about the engine(s) & technology used to b

Steam Database 103 Dec 14, 2022
Custom PHPStan rules

phpstan-rules Provides additional rules for phpstan/phpstan. Installation Run $ composer require --dev alister/phpstan-rules Usage All of the rules pr

Alister Bulman 1 Nov 4, 2021
Validated properties in PHP8.1 and above using attribute rules

PHP Validated Properties Add Rule attributes to your model properties to make sure they are valid. Why this package? When validating external data com

null 23 Oct 18, 2022
Set of rules for PHP_CodeSniffer and PHP-CS-Fixer used by Symplify projects.

20+ Coding Standard checkers for PHP projects with focus on Clean Architecture

null 281 Dec 30, 2022
ExtDN PHP_CodeSniffer rules for Magento 2

ExtDN PHP_CodeSniffer rules for Magento 2 Introduction There are already many PHP CodeSniffer rules out there to aid in Magento 2 development: Magento

ExtDN 81 Dec 16, 2022
Various PHPStan rules we found useful in ShipMonk.

ShipMonk PHPStan rules Various rules we found useful in ShipMonk. You may found some of them opinionated, so we recommend picking only those fitting y

ShipMonk R&D 31 Dec 22, 2022
Repository containing all the PHPStan rules from the book "Recipes for Decoupling"

PHPStan rules from the book "Recipes for Decoupling" by Matthias Noback In the book "Recipes for Decoupling" we discuss how to decouple from web and C

Matthias Noback 19 Sep 21, 2022
Test and enforce architectural rules in your Laravel applications. Keep your app's architecture clean and consistent!

Laravel Arkitect Laravel Arkitect lets you test and enforce your architectural rules in your Laravel applications, and it's a PHPArkitect wrapper for

SMorteza Ebadi 55 Dec 17, 2022
Dedicated plugin for PocketMine-API 4, this will help staff members to make players follow the rules to the letter

StaffMode Dedicated plugin for PocketMine-API 4, this will help staff members to make players follow the rules to the letter Annotation This plugin is

Kurth 3 Aug 12, 2022
Support for PHP 8.1 enums in Doctrine.

Doctrine Native Enums This library provides first-class support to PHP Enums, introduced in PHP 8.1, within your Doctrine entities. Installation compo

Beno!t POLASZEK 14 Dec 15, 2022
Pageon Doctrine Data Grid Bundle

Pageon Doctrine Data Grid Bundle A bundle that wraps around the knp paginator bundle and doctrine to generate a data grid from your entity Documentati

null 1 Dec 14, 2021
Immutable value object for IPv4 and IPv6 addresses, including helper methods and Doctrine support.

IP is an immutable value object for (both version 4 and 6) IP addresses. Several helper methods are provided for ranges, broadcast and network address

Darsyn 224 Dec 28, 2022
Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer

Spot DataMapper ORM v2.0 Spot v2.x is built on the Doctrine DBAL, and targets PHP 5.4+. The aim of Spot is to be a lightweight DataMapper alternative

Spot ORM 602 Dec 27, 2022
A bundle to handle encoding and decoding of parameters using OpenSSL and Doctrine lifecycle events.

SpecShaper Encrypt Bundle A bundle to handle encoding and decoding of parameters using OpenSSL and Doctrine lifecycle events. Features include: Master

Mark Ogilvie 48 Nov 4, 2022
Doctrine extensions for PHPStan

Doctrine extensions for PHPStan PHPStan Doctrine This extension provides following features: DQL validation for parse errors, unknown entity classes a

PHPStan 478 Jan 3, 2023
This package provides a set of factories to be used with containers using the PSR-11 standard for an easy Doctrine integration in a project

psr-container-doctrine: Doctrine Factories for PSR-11 Containers Doctrine factories for PSR-11 containers. This package provides a set of factories to

Roave, LLC 84 Dec 14, 2022
Doctrine ORM Module for Laminas

Doctrine ORM Module for Laminas The DoctrineORMModule leverages DoctrineModule and integrates Doctrine ORM with Laminas quickly and easily. The follow

Doctrine 418 Dec 25, 2022