classNaming = $classNaming; $this->propertyManipulator = $propertyManipulator; $this->propertyToAddCollector = $propertyToAddCollector; } public function getRuleDefinition() : RuleDefinition { return new RuleDefinition('Replaces creating object instances with "new" keyword with factory method.', [new ConfiguredCodeSample(<<<'CODE_SAMPLE' class SomeClass { public function example() { new MyClass($argument); } } CODE_SAMPLE , <<<'CODE_SAMPLE' class SomeClass { /** * @var \MyClassFactory */ private $myClassFactory; public function example() { $this->myClassFactory->create($argument); } } CODE_SAMPLE , [new NewToMethodCall('MyClass', 'MyClassFactory', 'create')])]); } /** * @return array> */ public function getNodeTypes() : array { return [New_::class]; } /** * @param New_ $node */ public function refactor(Node $node) : ?Node { $class = $this->betterNodeFinder->findParentType($node, Class_::class); if (!$class instanceof Class_) { return null; } $className = $this->getName($class); if (!\is_string($className)) { return null; } foreach ($this->newsToMethodCalls as $newToMethodCall) { if (!$this->isObjectType($node, $newToMethodCall->getNewObjectType())) { continue; } $serviceObjectType = $newToMethodCall->getServiceObjectType(); if ($className === $serviceObjectType->getClassName()) { continue; } $propertyName = $this->propertyManipulator->resolveExistingClassPropertyNameByType($class, $newToMethodCall->getServiceObjectType()); if ($propertyName === null) { $serviceObjectType = $newToMethodCall->getServiceObjectType(); $propertyName = $this->classNaming->getShortName($serviceObjectType->getClassName()); $propertyName = \lcfirst($propertyName); $propertyMetadata = new PropertyMetadata($propertyName, $newToMethodCall->getServiceObjectType(), Class_::MODIFIER_PRIVATE); $this->propertyToAddCollector->addPropertyToClass($class, $propertyMetadata); } $propertyFetch = new PropertyFetch(new Variable('this'), $propertyName); return new MethodCall($propertyFetch, $newToMethodCall->getServiceMethod(), $node->args); } return $node; } /** * @param mixed[] $configuration */ public function configure(array $configuration) : void { Assert::allIsAOf($configuration, NewToMethodCall::class); $this->newsToMethodCalls = $configuration; } }