/** * getContents() * * @return string */ public function getContents() { $filter = new \Zend\Filter\Word\DashToCamelCase(); $className = $filter->filter($this->_forControllerName) . 'ControllerTest'; $codeGenFile = new Php\PhpFile(array('requiredFiles' => array('PHPUnit/Framework/TestCase.php'), 'classes' => array(new Php\PhpClass(array('name' => $className, 'extendedClass' => 'PHPUnit_Framework_TestCase', 'methods' => array(new Php\PhpMethod(array('name' => 'setUp', 'body' => ' /* Setup Routine */')), new Php\PhpMethod(array('name' => 'tearDown', 'body' => ' /* Tear Down Routine */')))))))); return $codeGenFile->generate(); }
/** * getContents() * * @return string */ public function getContents() { $codeGenerator = new PhpFile(array('body' => <<<EOS // Define path to application directory defined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application')); // Define application environment defined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing')); // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), get_include_path(), ))); require_once 'Zend/Loader/StandardAutoloader.php'; \$loader = new Zend\\Loader\\StandardAutoloader(array( 'fallback_autoloader' => true, )) \$loader->register(); EOS )); return $codeGenerator->generate(); }
/** * Construct, configure, and return a PHP classfile code generation object * * Creates a Zend\CodeGenerator\Php\PhpFile object that has * created the specified class and service locator methods. * * @param null|string $filename * @return CodeGen\PhpFile */ public function getCodeGenerator($filename = null) { $injector = $this->injector; $im = $injector->getInstanceManager(); $indent = ' '; $aliases = $this->reduceAliases($im->getAliases()); $caseStatements = array(); $getters = array(); $definition = $injector->getDefinition(); foreach ($definition->getClasses() as $name) { $getter = $this->normalizeAlias($name); $meta = $injector->get($name); $params = $meta->getParams(); // Build parameter list for instantiation foreach ($params as $key => $param) { if (null === $param || is_scalar($param) || is_array($param)) { $string = var_export($param, 1); if (strstr($string, '::__set_state(')) { throw new Exception\RuntimeException('Arguments in definitions may not contain objects'); } $params[$key] = $string; } elseif ($param instanceof GeneratorInstance) { $params[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); } else { $message = sprintf('Unable to use object arguments when building containers. Encountered with "%s", parameter of type "%s"', $name, get_class($param)); throw new Exception\RuntimeException($message); } } // Strip null arguments from the end of the params list $reverseParams = array_reverse($params, true); foreach ($reverseParams as $key => $param) { if ('NULL' === $param) { unset($params[$key]); continue; } break; } // Create instantiation code $creation = ''; $constructor = $meta->getConstructor(); if ('__construct' != $constructor) { // Constructor callback $callback = var_export($constructor, 1); if (strstr($callback, '::__set_state(')) { throw new Exception\RuntimeException('Unable to build containers that use callbacks requiring object instances'); } if (count($params)) { $creation = sprintf('$object = call_user_func(%s, %s);', $callback, implode(', ', $params)); } else { $creation = sprintf('$object = call_user_func(%s);', $callback); } } else { // Normal instantiation $className = '\\' . ltrim($name, '\\'); $creation = sprintf('$object = new %s(%s);', $className, implode(', ', $params)); } // Create method call code $methods = ''; foreach ($meta->getMethods() as $key => $methodData) { if (!isset($methodData['name']) && !isset($methodData['method'])) { continue; } $methodName = isset($methodData['name']) ? $methodData['name'] : $methodData['method']; $methodParams = $methodData['params']; // Create method parameter representation foreach ($methodParams as $key => $param) { if (null === $param || is_scalar($param) || is_array($param)) { $string = var_export($param, 1); if (strstr($string, '::__set_state(')) { throw new Exception\RuntimeException('Arguments in definitions may not contain objects'); } $methodParams[$key] = $string; } elseif ($param instanceof GeneratorInstance) { $methodParams[$key] = sprintf('$this->%s()', $this->normalizeAlias($param->getName())); } else { $message = sprintf('Unable to use object arguments when generating method calls. Encountered with class "%s", method "%s", parameter of type "%s"', $name, $methodName, get_class($param)); throw new Exception\RuntimeException($message); } } // Strip null arguments from the end of the params list $reverseParams = array_reverse($methodParams, true); foreach ($reverseParams as $key => $param) { if ('NULL' === $param) { unset($methodParams[$key]); continue; } break; } $methods .= sprintf("\$object->%s(%s);\n", $methodName, implode(', ', $methodParams)); } // Generate caching statement $storage = ''; if ($im->hasSharedInstance($name, $params)) { $storage = sprintf("\$this->services['%s'] = \$object;\n", $name); } // Start creating getter $getterBody = ''; // Create fetch of stored service if ($im->hasSharedInstance($name, $params)) { $getterBody .= sprintf("if (isset(\$this->services['%s'])) {\n", $name); $getterBody .= sprintf("%sreturn \$this->services['%s'];\n}\n\n", $indent, $name); } // Creation and method calls $getterBody .= sprintf("%s\n", $creation); $getterBody .= $methods; // Stored service $getterBody .= $storage; // End getter body $getterBody .= "return \$object;\n"; $getterDef = new CodeGen\PhpMethod(); $getterDef->setName($getter)->setBody($getterBody); $getters[] = $getterDef; // Get cases for case statements $cases = array($name); if (isset($aliases[$name])) { $cases = array_merge($aliases[$name], $cases); } // Build case statement and store $statement = ''; foreach ($cases as $value) { $statement .= sprintf("%scase '%s':\n", $indent, $value); } $statement .= sprintf("%sreturn \$this->%s();\n", str_repeat($indent, 2), $getter); $caseStatements[] = $statement; } // Build switch statement $switch = sprintf("switch (%s) {\n%s\n", '$name', implode("\n", $caseStatements)); $switch .= sprintf("%sdefault:\n%sreturn parent::get(%s, %s);\n", $indent, str_repeat($indent, 2), '$name', '$params'); $switch .= "}\n\n"; // Build get() method $nameParam = new CodeGen\PhpParameter(); $nameParam->setName('name'); $defaultParams = new CodeGen\PhpParameterDefaultValue(); $defaultParams->setValue(array()); $paramsParam = new CodeGen\PhpParameter(); $paramsParam->setName('params')->setType('array')->setDefaultValue($defaultParams); $get = new CodeGen\PhpMethod(); $get->setName('get'); $get->setParameters(array($nameParam, $paramsParam)); $get->setBody($switch); // Create getters for aliases $aliasMethods = array(); foreach ($aliases as $class => $classAliases) { foreach ($classAliases as $alias) { $aliasMethods[] = $this->getCodeGenMethodFromAlias($alias, $class); } } // Create class code generation object $container = new CodeGen\PhpClass(); $container->setName($this->containerClass)->setExtendedClass('ServiceLocator')->setMethod($get)->setMethods($getters)->setMethods($aliasMethods); // Create PHP file code generation object $classFile = new CodeGen\PhpFile(); $classFile->setUse('Zend\\Di\\ServiceLocator')->setClass($container); if (null !== $this->namespace) { $classFile->setNamespace($this->namespace); } if (null !== $filename) { $classFile->setFilename($filename); } return $classFile; }
/** * getCodeGenerator() * * @return \Zend\CodeGenerator\Php\PhpClass */ public function getCodeGenerator() { $codeGenFile = Php\PhpFile::fromReflectedFileName($this->getPath()); $codeGenFileClasses = $codeGenFile->getClasses(); $class = array_shift($codeGenFileClasses); return $class; }
public function getContents() { $className = $this->getFullClassName($this->_dbTableName, 'Model\\DbTable'); $codeGenFile = new Php\PhpFile(array('fileName' => $this->getPath(), 'classes' => array(new Php\PhpClass(array('name' => $className, 'extendedClass' => '\\Zend\\Db\\Table\\AbstractTable', 'properties' => array(new Php\PhpProperty(array('name' => '_name', 'visibility' => Php\PhpProperty::VISIBILITY_PROTECTED, 'defaultValue' => $this->_actualTableName)))))))); return $codeGenFile->generate(); }
/** * registerFileCodeGnereator() * * A file code generator registry * * @param PhpFile $fileCodeGenerator * @param string $fileName */ public static function registerFileCodeGenerator(PhpFile $fileCodeGenerator, $fileName = null) { if ($fileName == null) { $fileName = $fileCodeGenerator->getFilename(); } if ($fileName == '') { throw new Exception\InvalidArgumentException('FileName does not exist.'); } // cannot use realpath since the file might not exist, but we do need to have the index // in the same DIRECTORY_SEPARATOR that realpath would use: $fileName = str_replace(array('\\', '/'), DIRECTORY_SEPARATOR, $fileName); self::$_fileCodeGenerators[$fileName] = $fileCodeGenerator; }
public function testFromReflectionFile() { //$this->markTestSkipped('Must support namespaces'); $file = __DIR__ . '/TestAsset/TestSampleSingleClass.php'; require_once $file; $codeGenFileFromDisk = Php\PhpFile::fromReflection(new Reflection\ReflectionFile($file)); $codeGenFileFromDisk->getClass()->setMethod(array('name' => 'foobar')); $expectedOutput = <<<EOS <?php /** * File header here * * @author Ralph Schindler <*****@*****.**> * */ /** * @namespace */ namespace ZendTest\\CodeGenerator\\Php\\TestAsset; /** * class docblock * * @package Zend_Reflection_TestSampleSingleClass * */ class TestSampleSingleClass { /** * Enter description here... * * @return bool * */ public function someMethod() { /* test test */ } public function foobar() { } } EOS; $this->assertEquals($expectedOutput, $codeGenFileFromDisk->generate()); }
/** * hasActionMethod() * * @param string $controllerPath * @param string $actionName * @return bool */ public static function hasActionMethod($controllerPath, $actionName) { if (!file_exists($controllerPath)) { return false; } $controllerCodeGenFile = Php\PhpFile::fromReflectedFileName($controllerPath, true, true); return $controllerCodeGenFile->getClass()->hasMethod($actionName . 'Action'); }
public function testGeneratesNamespaceStatements() { $file = new Php\PhpFile(); $file->setNamespace('Foo\Bar'); $generated = $file->generate(); $this->assertContains('namespace Foo\\Bar', $generated, $generated); }