Skip to content

ForeachToInArrayRector should take into account Doctrine's Collection #1533

@Aerendir

Description

@Aerendir
     /**
@@ -141,12 +135,6 @@
      */
     private function isConsignee(RemoteOrder $order, User $user): bool
     {
-        foreach ($user->getEmails() as $email) {
-            if ($email === $order->getSrcShippingEmail()) {
-                return true;
-            }
-        }
-
-        return false;
+        return in_array($order->getSrcShippingEmail(), $user->getEmails(), true);
     }
 }
    ----------- end diff -----------

Applied rectors:

 * Rector\CodeQuality\Rector\Foreach_\ForeachToInArrayRector
/**
 * @ORM\Entity
 * @ORM\Table(name="users")
 */
class User extends BaseUser
{
    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Email", mappedBy="forUser")
     */
    protected $emails;

    /**
     * @return Collection|Email[]
     */
    public function getEmails(): Collection
    {
        return $this->emails;
    }

As you can see, and as pointed out in phpstan/phpstan#2176, Collection cannot be passed to in_array().

Here there are two problems:

  1. Rector changes the code to use in_array();
  2. In case of Doctrine's Collection, it should be better to use Collection::contains().

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions