Skip to content

Add StrictInArrayRector rector #9681

@acbramley

Description

@acbramley

Feature Request

I was searching for a rector rule to add the strict parameter to in_array calls but couldn't find one. I noticed we have Rector\CodingStyle\Rector\FuncCall\StrictArraySearchRector which is very similar, so can we add the same but for in_array?

Diff

+<?php
+
+declare (strict_types=1);
+namespace Rector\CodingStyle\Rector\FuncCall;
+
+use PhpParser\Node;
+use PhpParser\Node\Expr\FuncCall;
+use Rector\Rector\AbstractRector;
+use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
+use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
+/**
+ * @see \Rector\Tests\CodingStyle\Rector\FuncCall\StrictInArrayhRector\StrictInArrayhRectorTest
+ */
+final class StrictInArrayRector extends AbstractRector
+{
+    public function getRuleDefinition(): RuleDefinition
+    {
+        return new RuleDefinition('Makes in_array search for identical elements', [new CodeSample('in_array($value, $items);', 'in_array($value, $items, true);')]);
+    }
+    /**
+     * @return array<class-string<Node>>
+     */
+    public function getNodeTypes(): array
+    {
+        return [FuncCall::class];
+    }
+    /**
+     * @param FuncCall $node
+     */
+    public function refactor(Node $node): ?Node
+    {
+        if (!$this->isName($node, 'in_array')) {
+            return null;
+        }
+        if (count($node->args) === 2) {
+            $node->args[2] = $this->nodeFactory->createArg($this->nodeFactory->createTrue());
+            return $node;
+        }
+        return null;
+    }
+}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions