/** * @param FileGenerator $file * @param Type $type * * @return string */ public function generate(FileGenerator $file, $type) { $class = $file->getClass() ?: new ClassGenerator(); $class->setNamespaceName($type->getNamespace()); $class->setName($type->getName()); $this->ruleSet->applyRules(new TypeContext($class, $type)); foreach ($type->getProperties() as $property) { $this->ruleSet->applyRules(new PropertyContext($class, $type, $property)); } $file->setClass($class); return $file->generate(); }
/** * @param Type $type * * @return MethodGenerator * @throws \Zend\Code\Generator\Exception\InvalidArgumentException */ private function assembleConstructor(Type $type) { $body = []; $constructor = MethodGenerator::fromArray(['name' => '__construct', 'visibility' => MethodGenerator::VISIBILITY_PUBLIC]); $docblock = DocBlockGenerator::fromArray(['shortdescription' => 'Constructor']); foreach ($type->getProperties() as $property) { $body[] = sprintf('$this->%1$s = $%1$s;', $property->getName()); $constructor->setParameter(['name' => $property->getName()]); $docblock->setTag(['name' => 'var', 'description' => sprintf('%s $%s', $property->getType(), $property->getName())]); } $constructor->setDocBlock($docblock); $constructor->setBody(implode($constructor::LINE_FEED, $body)); return $constructor; }
function it_generates_types(RuleSetInterface $ruleSet, FileGenerator $file, ClassGenerator $class) { $type = new Type('MyNamespace', 'MyType', ['prop1' => 'string']); $property = $type->getProperties()[0]; $file->generate()->willReturn('code'); $file->getClass()->willReturn($class); $class->setNamespaceName('MyNamespace')->shouldBeCalled(); $class->setName('MyType')->shouldBeCalled(); $file->setClass($class)->shouldBeCalled(); $ruleSet->applyRules(Argument::that(function (ContextInterface $context) use($type) { return $context instanceof TypeContext && $context->getType() === $type; }))->shouldBeCalled(); $ruleSet->applyRules(Argument::that(function (ContextInterface $context) use($type, $property) { return $context instanceof PropertyContext && $context->getType() === $type && $context->getProperty() === $property; }))->shouldBeCalled(); $this->generate($file, $type)->shouldReturn('code'); }
/** * An existing file was found. Try to patch or ask if it can be overwritten. * * @param TypeGenerator $generator * @param Type $type * @param string $path * * @return bool */ protected function handleExistingFile(TypeGenerator $generator, Type $type, $path) { $this->output->write(sprintf('Type %s exists. Trying to patch ...', $type->getName())); $patched = $this->patchExistingFile($generator, $type, $path); if ($patched) { $this->output->writeln('Patched!'); return true; } $this->output->writeln('Could not patch.'); return false; }