Added addUse method in ClassGenerator #2702

Closed
wants to merge 5 commits into
from
@@ -68,6 +68,11 @@ class ClassGenerator extends AbstractGenerator
protected $methods = array();
/**
+ * @var array Array of string names
+ */
+ protected $uses = array();
+
+ /**
* fromReflection() - build a Code Generation Php Object from a Class Reflection
*
* @param ClassReflection $classReflection
@@ -480,6 +485,19 @@ public function addPropertyFromGenerator(PropertyGenerator $property)
}
/**
+ * Add a class to "use" classes
+ *
+ * @param string $useClass
+ */
+ public function addUse($use, $useAlias = null)
+ {
+ if (!empty($useAlias)) {
+ $use .= ' as ' . $useAlias;
+ }
+ $this->uses[] = $use;
+ }
+
+ /**
* getProperties()
*
* @return PropertyGenerator[]
@@ -506,6 +524,16 @@ public function getProperty($propertyName)
}
/**
+ * Returns the "use" classes
+ *
+ * @return array
+ */
+ public function getUses()
+ {
+ return $this->uses;
+ }
+
+ /**
* hasProperty()
*
* @param string $propertyName
@@ -664,6 +692,14 @@ public function generate()
$output .= 'namespace ' . $namespace . ';' . self::LINE_FEED . self::LINE_FEED;
}
+ $uses = $this->getUses();
+ if (!empty($uses)) {
+ foreach ($uses as $use) {
+ $output .= 'use ' . $use . ';' . self::LINE_FEED;
+ }
+ $output .= self::LINE_FEED;
+ }
+
if (null !== ($docBlock = $this->getDocBlock())) {
$docBlock->setIndentation('');
$output .= $docBlock->generate();
@@ -362,4 +362,19 @@ public function testPassingANamespacedClassnameShouldGenerateAClassnameWithoutIt
$received = $classGeneratorClass->generate();
$this->assertContains('class FunClass', $received, $received);
}
+
+ /**
+ * @group ZF2-151
+ */
+ public function testAddUses()
+ {
+ $classGenerator = new ClassGenerator();
+ $classGenerator->setName('My\Class');
+ $classGenerator->addUse('My\First\Use\Class');
+ $classGenerator->addUse('My\Second\Use\Class', 'MyAlias');
+ $generated = $classGenerator->generate();
+
+ $this->assertContains('use My\First\Use\Class;', $generated);
+ $this->assertContains('use My\Second\Use\Class as MyAlias;', $generated);
+ }
}