Example #1
0
 public function testMultiLevelIndentation()
 {
     $block = new Block();
     $block->increaseIndentLevel();
     $block[] = '$a = 1;';
     $block[] = '$b = 2;';
     $block[] = '$c = 3;';
     $block[] = '{';
     $subBlock = new Block();
     $subBlock->increaseIndentLevel();
     $subBlock[] = '$f = $a + $b;';
     $subBlock[] = '$g = $b + $c;';
     $block[] = $subBlock;
     $block[] = '}';
     $this->assertCodeEqualsFile('tests/data/multi_level_block.fixture', $block);
 }
Example #2
0
 public function render(array $args = array())
 {
     $this->else->setIndentLevel($this->indentLevel + 1);
     $this[] = ' else {';
     $this[] = $this->else;
     $this[] = '}';
     return parent::render($args);
 }
Example #3
0
 public function render(array $args = array())
 {
     $tab = Indenter::indent($this->indentLevel);
     $this->increaseIndentLevel();
     // increaseIndentLevel to indent the inner block.
     $body = '';
     $body .= $tab . "{\n";
     $body .= parent::render($args);
     $body .= $tab . "}\n";
     return $body;
 }
Example #4
0
 public function render(array $args = array())
 {
     $this->if->setIndentLevel($this->indentLevel + 1);
     $this[] = 'if (' . VariableDeflator::deflate($this->condition) . ') {';
     $this[] = $this->if;
     if ($this->else) {
         $this[] = '} else {';
         $this->else->setIndentLevel($this->indentLevel + 1);
         $this[] = $this->else;
         $this[] = '}';
     } else {
         $this[] = '}';
     }
     return Block::render($args);
 }
Example #5
0
 public function render(array $args = array())
 {
     $this->if->setIndentLevel($this->indentLevel + 1);
     $this[] = 'if (' . VariableDeflator::deflate($this->condition) . ') {';
     $this[] = $this->if;
     $trailingBlocks = array();
     if (!empty($this->elseifs)) {
         foreach ($this->elseifs as $elseIf) {
             $trailingBlocks[] = rtrim($elseIf->render($args));
         }
     }
     if ($this->else) {
         $trailingBlocks[] = rtrim($this->else->render($args));
     }
     $this[] = '}' . join('', $trailingBlocks);
     return parent::render($args);
 }
Example #6
0
 public function execute($pharFile = 'output.phar')
 {
     if (!extension_loaded('json')) {
         throw new RuntimeException('json extension is required.');
     }
     // $composerConfigFile is a SplFileInfo object since wuse ->isa('file')
     $composerConfigFile = $this->options->{'composer'} ?: 'composer.json';
     if (!file_exists($composerConfigFile)) {
         throw new Exception("composer config '{$composerConfigFile}' doesn't exist.");
     }
     $composerConfigFile = new SplFileInfo(realpath($composerConfigFile));
     $this->logger->debug("Found composer config at {$composerConfigFile}");
     // workingDir is a SplFileInfo object since we use ->isa('Dir')
     $workingDir = $this->options->{'working-dir'} ?: new SplFileInfo($composerConfigFile->getPath());
     if (!file_exists($workingDir)) {
         throw new Exception("working directory '{$workingDir}' doesn't exist.");
     }
     $this->logger->debug('Working directory: ' . $workingDir->getPathname());
     $vendorDirName = $this->options->vendor ?: 'vendor';
     $pharGenerator = new PharGenerator($this->logger, $this->options, $pharFile);
     $phar = $pharGenerator->getPhar();
     ini_set('phar.readonly', 0);
     $this->logger->info("Creating phar file {$pharFile}...");
     $phar->startBuffering();
     $stubs = new Block();
     if ($this->options->executable) {
         $this->logger->debug('Adding shell bang...');
         $stubs[] = '#!/usr/bin/env php';
     }
     // prepend open tag
     $stubs[] = '<?php';
     $this->logger->info('Setting up stub...');
     $stubs[] = "Phar::mapPhar('{$pharFile}');";
     // $workingDir = dirname(realpath($composerConfigFile));
     // Get class paths by ReflectionClass, they should be relative path.
     // However the class path might be in another directory because the
     // classes are loaded from vendor/autoload.php
     $classPaths = array(Utils::getClassPath('Universal\\ClassLoader\\ClassLoader'), Utils::getClassPath('Universal\\ClassLoader\\Psr0ClassLoader'), Utils::getClassPath('Universal\\ClassLoader\\Psr4ClassLoader'), Utils::getClassPath('Universal\\ClassLoader\\MapClassLoader'));
     // Generate class loader stub
     $this->logger->debug('Adding class loader files...');
     foreach ($classPaths as $classPath) {
         $phar->addFile($classPath, basename($classPath));
     }
     /*
             $classDir = dirname($classPaths[0]);
             $phar->buildFromIterator(
        new RecursiveIteratorIterator(new RecursiveDirectoryIterator($classDir)),
        $workingDir
             );
     */
     foreach ($classPaths as $classPath) {
         $this->logger->debug('Adding require statment for class loader: ' . basename($classPath));
         $stubs[] = new RequireStatement(new PharURI($pharFile, basename($classPath)));
     }
     if (!$this->options->{'no-classloader'}) {
         $this->logger->info('Generating classLoader stubs');
         $autoloadGenerator = new ComposerAutoloadGenerator($this->logger);
         $autoloadGenerator->setVendorDir('vendor');
         $autoloadGenerator->setWorkingDir($workingDir->getPathname());
         $autoloadGenerator->scanComposerJsonFiles($workingDir . DIRECTORY_SEPARATOR . $vendorDirName);
         $autoloads = $autoloadGenerator->traceAutoloadsWithComposerJson($composerConfigFile, $workingDir . DIRECTORY_SEPARATOR . $vendorDirName, true);
         foreach ($autoloads as $packageName => $config) {
             if (!isset($config['autoload'])) {
                 continue;
             }
             $autoload = $config['autoload'];
             if (!isset($config['root'])) {
                 $autoload = $autoloadGenerator->prependAutoloadPathPrefix($autoload, $vendorDirName . DIRECTORY_SEPARATOR . $packageName . DIRECTORY_SEPARATOR);
             }
             foreach ($autoload as $type => $map) {
                 foreach ($map as $mapPaths) {
                     $paths = (array) $mapPaths;
                     foreach ($paths as $path) {
                         $absolutePath = $workingDir . DIRECTORY_SEPARATOR . $path;
                         if (is_dir($absolutePath)) {
                             $this->logger->debug("Add files from directory {$absolutePath} under {$workingDir}");
                             $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($absolutePath, FilesystemIterator::SKIP_DOTS));
                             foreach ($it as $fileinfo) {
                                 $pathName = $fileinfo->getPathname();
                                 if (preg_match('/(\\.(?:git|svn|hg)|Tests|Test\\.php)/', $pathName)) {
                                     continue;
                                 }
                                 $localPath = str_replace($workingDir . DIRECTORY_SEPARATOR, '', $pathName);
                                 $this->logger->debug("Adding {$localPath}");
                                 $phar->addFile($pathName, $localPath);
                             }
                             /*
                             $builtFiles = $phar->buildFromIterator(
                                 new RecursiveIteratorIterator(
                                     new RecursiveDirectoryIterator($absolutePath, FilesystemIterator::SKIP_DOTS)
                                 ),
                                 $workingDir
                             );
                             */
                         } elseif (is_file($absolutePath)) {
                             $this->logger->debug("Add file {$absolutePath} under {$path}");
                             $phar->addFile($absolutePath, $path);
                         } else {
                             $this->logger->error("File '{$absolutePath}' is not found.");
                         }
                     }
                 }
             }
         }
         $classloaderStub = $autoloadGenerator->generate($composerConfigFile, $pharFile);
         $this->logger->debug('ClassLoader stub:');
         $this->logger->debug($classloaderStub);
         $stubs[] = $autoloadGenerator->generate($composerConfigFile, $pharFile);
     }
     if ($bootstraps = $this->options->bootstrap) {
         foreach ($bootstraps as $bootstrap) {
             $this->logger->info("Adding bootstrap: {$bootstrap}");
             $content = php_strip_whitespace($bootstrap);
             $content = preg_replace('{^#!/usr/bin/env\\s+php\\s*}', '', $content);
             $localPath = str_replace($workingDir->getPathname(), '', $bootstrap->getRealPath());
             $phar->addFromString($localPath, $content);
             $stubs[] = new RequireStatement(new PharURI($pharFile, $localPath));
         }
     }
     if ($this->options->{'app-bootstrap'}) {
         $app = $this->getApplication();
         $refObject = new ReflectionObject($app);
         $appClassName = $refObject->getName();
         $block = new Block();
         $block[] = new AssignStatement('$app', new NewObjectExpr($appClassName));
         $block[] = new MethodCallStatement('$app', 'run', array('$argv'));
         $stubs[] = $block;
     }
     $stubs[] = '__HALT_COMPILER();';
     $stubstr = $stubs->render();
     $this->logger->debug($stubstr);
     $phar->setStub($stubstr);
     // Add some extra files in phar's root
     if ($adds = $this->options->add) {
         foreach ($adds as $add) {
             $phar->buildFromIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($add)), $workingDir);
         }
     }
     $pharGenerator->generate();
     $this->logger->info('Done');
 }
Example #7
0
 public function execute()
 {
     $psr4Map = (require "vendor/composer/autoload_psr4.php");
     $psr4ClassLoader = new Psr4ClassLoader();
     // XXX: connect to differnt config by using environment variable (PHIFTY_ENV)
     $this->logger->info("===> Building config files...");
     $configPaths = array_filter(array('config/application.yml', 'config/framework.yml', 'config/database.yml', 'config/testing.yml'), 'file_exists');
     foreach ($configPaths as $configPath) {
         $this->logger->info("Building {$configPath}");
         ConfigCompiler::compile($configPath);
     }
     $appDirectory = 'app';
     $outputFile = $this->options->output;
     defined('PH_APP_ROOT') || define('PH_APP_ROOT', getcwd());
     // PH_ROOT is deprecated, but kept for backward compatibility
     defined('PH_ROOT') || define('PH_ROOT', getcwd());
     $this->logger->info('Using PH_APP_ROOT:' . PH_APP_ROOT);
     if ($this->options->clean) {
         $this->logger->info("Removing genereated files");
         $cleanFiles = [$outputFile, PH_APP_ROOT . $appDirectory . 'AppKernel.php', PH_APP_ROOT . $appDirectory . 'AppConfigLoader.php'];
         foreach ($cleanFiles as $cleanFile) {
             $this->logger->debug("Checking {$cleanFile}");
             if (file_exists($cleanFile)) {
                 $this->logger->debug("Removing {$cleanFile}");
                 unlink($cleanFile);
             }
         }
         $this->logger->info('Cached files are cleaned up');
         return;
     }
     $this->logger->info("===> Generating bootstrap file: {$outputFile}");
     $block = new Block();
     $block[] = '<?php';
     $block[] = new CommentBlock(["This file is auto-generated through 'bin/phifty bootstrap' command.", "Don't modify this file directly", "", "For more information, please visit https://github.com/c9s/Phifty"]);
     if (extension_loaded('mbstring')) {
         $block[] = "mb_internal_encoding('UTF-8');";
     }
     $xhprof = extension_loaded('xhprof') && $this->options->xhprof;
     if ($xhprof) {
         $block[] = 'xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);';
     }
     // autoload script from composer
     $block[] = new ConstStatement('PH_ROOT', PH_ROOT);
     $block[] = new ConstStatement('PH_APP_ROOT', PH_ROOT);
     $block[] = new ConstStatement('DS', DIRECTORY_SEPARATOR);
     $env = $this->options->env ?: getenv('PHIFTY_ENV') ?: 'development';
     $block[] = new ConstStatement('PH_ENV', $env);
     // $block[] = sprintf("define('PH_ROOT', %s);", var_export(PH_ROOT, true));
     // $block[] = sprintf("define('PH_APP_ROOT', %s);", var_export(PH_APP_ROOT, true));
     // $block[] = "defined('DS') || define('DS', DIRECTORY_SEPARATOR);";
     // CLI mode should be dynamic
     $block[] = new DefineStatement('CLI', new Raw("isset(\$_SERVER['argc']) && !isset(\$_SERVER['HTTP_HOST'])"));
     $block[] = new DefineStatement('CLI_MODE', new Raw("CLI"));
     $block[] = 'global $kernel, $composerClassLoader, $psr4ClassLoader, $splClassLoader;';
     $block[] = new AssignStatement('$composerClassLoader', new RequireComposerAutoloadStatement());
     $block[] = new RequireClassStatement('Universal\\ClassLoader\\Psr4ClassLoader');
     $block[] = '$psr4ClassLoader = new \\Universal\\ClassLoader\\Psr4ClassLoader();';
     $block[] = '$psr4ClassLoader->register(false);';
     $block[] = new Statement(new MethodCall('$psr4ClassLoader', 'addPrefix', ['App\\', PH_APP_ROOT . DIRECTORY_SEPARATOR . $appDirectory . DIRECTORY_SEPARATOR]));
     $block[] = new RequireClassStatement('Universal\\ClassLoader\\SplClassLoader');
     $block[] = '$splClassLoader = new \\Universal\\ClassLoader\\SplClassLoader();';
     $block[] = '$splClassLoader->useIncludePath(false);';
     $block[] = '$splClassLoader->register(false);';
     $block[] = new RequireClassStatement('Universal\\Container\\ObjectContainer');
     $block[] = new RequireClassStatement('Phifty\\Kernel');
     $this->logger->info("Generating config loader...");
     // generating the config loader
     $configLoader = $this->createConfigLoader(PH_APP_ROOT);
     $configClassGenerator = new AppClassGenerator(['namespace' => 'App', 'prefix' => 'App']);
     $configClass = $configClassGenerator->generate($configLoader);
     $classPath = $configClass->generatePsr4ClassUnder($appDirectory);
     $block[] = new RequireStatement(PH_APP_ROOT . DIRECTORY_SEPARATOR . $classPath);
     require_once $classPath;
     $kernelClassGenerator = new AppClassGenerator(['namespace' => 'App', 'prefix' => 'App', 'property_filter' => function ($property) {
         return !preg_match('/^(applications|services|environment|isDev|_.*)$/i', $property->getName());
     }]);
     // The runtime kernel will only contains "configLoader" and "classLoader" services
     $runtimeKernel = new \Phifty\Kernel();
     $runtimeKernel->prepare($configLoader);
     $runtimeKernel->config = function () use($configLoader) {
         return $configLoader;
     };
     // TODO: load services here?
     // Load the bundle list config
     // The config structure:
     //     BundleLoader:
     //       Paths:
     //       - app_bundles
     //       - bundles
     $bundleLoaderConfig = $configLoader->get('framework', 'BundleLoader') ?: ['Paths' => ['app_bundles', 'bundles']];
     // Load bundle objects into the runtimeKernel
     $bundleLoader = new BundleLoader($runtimeKernel, [PH_ROOT . DIRECTORY_SEPARATOR . 'app_bundles', PH_ROOT . DIRECTORY_SEPARATOR . 'bundles']);
     $bundleList = $configLoader->get('framework', 'Bundles');
     $bundleService = new BundleServiceProvider();
     $bundleService->register($runtimeKernel, $bundleLoaderConfig);
     // Generating registering code for bundle classes
     if ($bundleList) {
         foreach ($bundleList as $bundleName => $bundleConfig) {
             $autoload = $bundleLoader->getAutoloadConfig($bundleName);
             if ($autoload == false) {
                 continue;
             }
             foreach ($autoload as $prefix => $autoloadPath) {
                 if ($psr4Map && isset($psr4Map[$prefix])) {
                     continue;
                 }
                 $realAutoloadPath = realpath($autoloadPath) . DIRECTORY_SEPARATOR;
                 $this->logger->info("Adding psr4 {$prefix} to {$realAutoloadPath}");
                 $psr4ClassLoader->addPrefix($prefix, $realAutoloadPath);
                 $block[] = new Statement(new MethodCall('$psr4ClassLoader', 'addPrefix', [$prefix, $realAutoloadPath]));
             }
         }
         foreach ($bundleList as $bundleName => $bundleConfig) {
             $bundleClass = "{$bundleName}\\{$bundleName}";
             if (!class_exists($bundleClass, true)) {
                 $bundleClassFile = $bundleLoader->findBundleClass($bundleName);
                 if (!$bundleClassFile) {
                     throw new Exception("Bundle {$bundleName} class file '{$bundleClassFile}' doesn't exist.");
                 }
                 require $bundleClassFile;
             }
             $runtimeKernel->bundles[$bundleName] = $bundleClass::getInstance($runtimeKernel, $bundleConfig);
         }
     }
     $appKernelClass = $kernelClassGenerator->generate($runtimeKernel);
     $classPath = $appKernelClass->generatePsr4ClassUnder($appDirectory);
     require_once $classPath;
     $block[] = new RequireStatement(PH_APP_ROOT . DIRECTORY_SEPARATOR . $classPath);
     // $block[] = '';
     // Generates: $kernel = new \App\AppKernel;
     $block[] = new AssignStatement('$kernel', new NewObject('App\\AppKernel'));
     // Generates: $kernel->registerService(new \Phifty\ServiceProvider\ClassLoaderServiceProvider($splClassLoader));
     $block[] = new Statement(new MethodCall('$kernel', 'registerService', [new NewObject('\\Phifty\\ServiceProvider\\ClassLoaderServiceProvider', [new Variable('$splClassLoader')])]));
     // Generates: $configLoader = new \App\AppConfigLoader;
     $block[] = new AssignStatement('$configLoader', new NewObject('App\\AppConfigLoader'));
     // Generates: $kernel->registerService(new \Phifty\ServiceProvider\ConfigServiceProvider($configLoader));
     $block[] = new RequireClassStatement('Phifty\\ServiceProvider\\ConfigServiceProvider');
     $block[] = new Statement(new MethodCall('$kernel', 'registerService', [new NewObject('\\Phifty\\ServiceProvider\\ConfigServiceProvider', [new Variable('$configLoader')])]));
     // load event service, so that we can bind events in Phifty
     // Generates: $kernel->registerService(new \Phifty\ServiceProvider\EventServiceProvider());
     $block[] = new Comment('The event service is required for every component.');
     $block[] = new RequireClassStatement('Phifty\\ServiceProvider\\EventServiceProvider');
     $block[] = new Statement(new MethodCall('$kernel', 'registerService', [new NewObject('\\Phifty\\ServiceProvider\\EventServiceProvider')]));
     // Include bootstrap class
     $block[] = new Comment('Bootstrap.php nows only contains kernel() function.');
     $block[] = new RequireStatement(dirname(__DIR__) . DIRECTORY_SEPARATOR . 'Bootstrap.php');
     // Kernel initialization after bootstrap script
     if ($configLoader->isLoaded('framework')) {
         if ($configLoader->isLoaded('database')) {
             $dbConfig = $configLoader->getSection('database');
             $block[] = '$kernel->registerService(new \\Phifty\\ServiceProvider\\DatabaseServiceProvider(' . var_export($dbConfig, true) . '));';
         }
         // Require application classes directly, we need applications to be registered before services
         if ($appConfigs = $configLoader->get('framework', 'Applications')) {
             $appDir = PH_APP_ROOT . DIRECTORY_SEPARATOR . 'applications';
             foreach ($appConfigs as $appName => $appconfig) {
                 $appClassDir = PH_APP_ROOT . DIRECTORY_SEPARATOR . 'applications' . DIRECTORY_SEPARATOR . $appName;
                 $appClassPath = PH_APP_ROOT . DIRECTORY_SEPARATOR . 'applications' . DIRECTORY_SEPARATOR . $appName . DIRECTORY_SEPARATOR . 'Application.php';
                 if (file_exists($appClassPath)) {
                     $block[] = new RequireStatement($appClassPath);
                 }
                 if (file_exists($appClassDir)) {
                     /*
                                             $block[] = new Statement(new MethodCall('$splClassLoader', 'addNamespace', [
                        [ $appName => $appDir ],
                                             ]));
                     */
                 }
             }
         } else {
             // TODO: load "App\App" by default
             $appDir = PH_APP_ROOT . DIRECTORY_SEPARATOR . 'app';
             $appClassPath = PH_APP_ROOT . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'App.php';
             if (file_exists($appClassPath)) {
                 $block[] = new RequireStatement($appClassPath);
             }
             if (is_dir($appDir)) {
                 $block[] = new Statement(new MethodCall('$psr4ClassLoader', 'addPrefix', ['App\\', [$appDir . DIRECTORY_SEPARATOR]]));
             }
         }
         if ($services = $configLoader->get('framework', 'ServiceProviders')) {
             foreach ($services as $name => $options) {
                 if (!$options) {
                     $options = array();
                 }
                 // Not full qualified classname
                 $class = false === strpos($name, '\\') ? 'Phifty\\ServiceProvider\\' . $name : $name;
                 if (!class_exists($class, true)) {
                     throw new LogicException("{$class} does not exist.");
                 }
                 $block[] = new RequireClassStatement($class);
                 $this->logger->info("Generating {$class} ...");
                 $options = $class::canonicalizeConfig($runtimeKernel, $options);
                 if ($options === null) {
                     throw new LogicException("{$class}::canonicalizeConfig should return an array for service config.");
                 }
                 if (is_subclass_of($class, 'Phifty\\ServiceProvider\\BaseServiceProvider') && $class::isGeneratable($runtimeKernel, $options)) {
                     if ($prepareStm = $class::generatePrepare($runtimeKernel, $options)) {
                         $block[] = $prepareStm;
                     }
                     $block[] = new Statement(new MethodCall('$kernel', 'registerService', [$class::generateNew($runtimeKernel, $options), $options]));
                 } else {
                     $block[] = new Statement(new MethodCall('$kernel', 'registerService', [new NewObject($class, []), $options]));
                 }
             }
         }
     }
     // Generate environment setup
     switch ($env) {
         case "production":
             $block[] = new Statement(new StaticMethodCall('Phifty\\Environment\\Production', 'init', [new Variable('$kernel')]));
             break;
         case "development":
         default:
             $block[] = new Statement(new StaticMethodCall('Phifty\\Environment\\Development', 'init', [new Variable('$kernel')]));
             break;
     }
     // BundleServiceProvider
     // Init bundle objects in the bootstrap.php script
     if ($bundleList) {
         foreach ($bundleList as $bundleName => $bundleConfig) {
             $bundleClass = "{$bundleName}\\{$bundleName}";
             if (class_exists($bundleClass, true)) {
                 $reflection = new ReflectionClass($bundleClass);
                 $bundleClassFile = $reflection->getFileName();
             } else {
                 $bundleClassFile = $bundleLoader->findBundleClass($bundleName);
             }
             if ($bundleClassFile) {
                 $block[] = new RequireStatement($bundleClassFile);
             }
         }
         foreach ($bundleList as $bundleName => $bundleConfig) {
             $bundleClass = "{$bundleName}\\{$bundleName}";
             $block[] = "\$kernel->bundles['{$bundleName}'] = {$bundleClass}::getInstance(\$kernel, " . var_export($bundleConfig, true) . ");";
         }
     }
     // $block[] = new Statement(new MethodCall('$kernel->bundles', 'init'));
     $block[] = new Statement(new MethodCall('$kernel', 'init'));
     if ($xhprof) {
         $block[] = '$xhprofNamespace = "phifty-bootstrap";';
         $block[] = '$xhprofData = xhprof_disable();';
         $block[] = '$xhprofRuns = new XHProfRuns_Default();';
         $block[] = '$runId = $xhprofRuns->save_run($xhprofData,$xhprofNamespace);';
         $block[] = 'header("X-XHPROF-RUN: $runId");';
         $block[] = 'header("X-XHPROF-NS: $xhprofNamespace");';
     }
     $this->logger->info("===> Compiling code to {$outputFile}");
     $code = $block->render();
     $this->logger->debug($code);
     return file_put_contents($outputFile, $code);
 }
 public function execute($user, $repo)
 {
     $ns = '';
     if ($appNs = $this->options->ns) {
         $ns = rtrim(str_replace(':', '\\', $appNs), '\\') . '\\';
     } elseif ($appNs = $this->getApplication()->getCurrentAppNamespace()) {
         $ns = $appNs . '\\Topic\\';
     } else {
         $this->logger->notice('Namespace is defined.');
     }
     // Use git to clone the wiki
     $wikiGitURI = "https://github.com/{$user}/{$repo}.wiki.git";
     $wikiBaseUrl = "https://github.com/{$user}/{$repo}/wiki";
     $localRepoPath = "tmp/{$repo}.wiki";
     $currentDir = getcwd();
     if (is_dir($localRepoPath)) {
         if ($this->options->update) {
             $this->logger->info("Fetching {$wikiGitURI}...");
             system("git -C {$localRepoPath} pull origin", $retval);
             if ($retval != 0) {
                 return $this->logger->error("Can't clone wiki repository");
             }
         }
     } else {
         $dirname = dirname($localRepoPath);
         if (!file_exists($dirname)) {
             mkdir($dirname, 0755, true);
         }
         $this->logger->info("Cloning {$wikiGitURI}...");
         system("git clone {$wikiGitURI} {$localRepoPath}", $retval);
         if ($retval != 0) {
             return $this->logger->error("Can't clone wiki repository");
         }
     }
     // Build classes
     $this->logger->info('Building topic classes from GitHub pages...');
     $outputDir = $this->options->dir ?: '.';
     $directory = new RecursiveDirectoryIterator($localRepoPath);
     $iterator = new RecursiveIteratorIterator($directory);
     $topics = array();
     foreach ($iterator as $file) {
         if (preg_match('/\\.git/', $file->getPathName())) {
             continue;
         }
         if (preg_match('/\\.md$/', $file->getPathName())) {
             $topicRemoteUrl = $wikiBaseUrl . '/' . $file->getFileName();
             // Used from command-line, to invoke the topic
             // $topicId = strtolower(preg_replace(array('/.md$/'),array(''),$file->getFileName()));
             // The readable topic title
             // TODO: Support non-ascii characters
             $entryName = preg_replace('/.md$/', '', $file->getFileName());
             $entryNameNonEnChars = trim(preg_replace('/[^a-zA-Z0-9-\\s]/', '', $entryName));
             $topicClassName = implode('', array_map('ucfirst', explode('-', str_replace(' ', '', $entryNameNonEnChars)))) . 'Topic';
             $topicId = strtolower(preg_replace('/\\s+/', '-', $entryNameNonEnChars));
             $topicTitle = preg_replace('/-/', ' ', $entryName);
             $topicFullClassName = $ns . $topicClassName;
             $topics[$topicId] = $topicFullClassName;
             $classFile = $outputDir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $topicFullClassName) . '.php';
             $cTemplate = new TemplateClassFile($topicFullClassName, array('template' => 'Class.php.twig'));
             $cTemplate->addProperty('id', $topicId);
             $cTemplate->addProperty('url', $topicRemoteUrl);
             $cTemplate->addProperty('title', $topicTitle);
             $cTemplate->extendClass('\\CLIFramework\\Topic\\GitHubTopic');
             $cTemplate->addMethod('public', 'getRemoteUrl', array(), 'return $this->remoteUrl;');
             $cTemplate->addMethod('public', 'getId', array(), 'return $this->id;');
             $content = file_get_contents($file);
             $cTemplate->addMethod('public', 'getContent', array(), 'return ' . var_export($content, true) . ';', array(), false);
             $classDir = dirname($classFile);
             if (!file_exists($classDir)) {
                 mkdir($classDir, 0755, true);
             }
             $this->logger->info("Creating {$classFile}");
             if (false === file_put_contents($classFile, $cTemplate->render())) {
                 throw new Exception("Can't write file {$classFile}.");
             }
         }
     }
     $this->logger->info(wordwrap("You may now copy the below content to the 'init' method in your application class:"));
     $this->logger->writeln('-------');
     $block = new Block();
     $block->appendLine('$this->topics(' . var_export($topics, true) . ');');
     $this->logger->write($block->render());
     $this->logger->writeln('-------');
     chdir($currentDir);
     $this->logger->info('Done');
 }
 public function generate($composerConfigFile, $pharFile = 'output.phar')
 {
     $pharMap = 'phar://' . $pharFile . '/';
     $autoloads = $this->traceAutoloadsWithComposerJson($composerConfigFile, $this->vendorDir, true);
     $psr0 = array();
     $psr4 = array();
     $files = array();
     $map = array();
     foreach ($autoloads as $packageName => $config) {
         $autoload = $config['autoload'];
         // The returned autoload paths are relative paths in their packages
         // We need to prepend the package base dir path
         if (!isset($config['root'])) {
             $autoload = $this->prependAutoloadPathPrefix($autoload, $pharMap . $this->vendorDir . DIRECTORY_SEPARATOR . $packageName . DIRECTORY_SEPARATOR);
         } else {
             $autoload = $this->prependAutoloadPathPrefix($autoload, $pharMap);
         }
         if (isset($autoload['psr-4'])) {
             $psr4 = array_merge($psr4, $autoload['psr-4']);
         }
         if (isset($autoload['psr-0'])) {
             $psr0 = array_merge($psr0, $autoload['psr-0']);
         }
         if (isset($autoload['files'])) {
             $files = array_merge($files, $autoload['files']);
         }
         if (isset($autoload['classmap'])) {
             // the classmap here is an expanded classmap associative array
             $map = array_merge($map, $autoload['classmap']);
         }
     }
     $this->logger->debug('Generating class loader code...');
     // Generate classloader initialization code
     $block = new Block();
     $block[] = new UseStatement('Universal\\ClassLoader\\Psr0ClassLoader');
     $block[] = new UseStatement('Universal\\ClassLoader\\Psr4ClassLoader');
     $block[] = new UseStatement('Universal\\ClassLoader\\MapClassLoader');
     if (!empty($files)) {
         foreach ($files as $file) {
             $block[] = new RequireStatement($file);
         }
     }
     if (!empty($map)) {
         $this->logger->debug('Found classmap autoload, adding MapClassLoader...');
         $block[] = new AssignStatement('$map', new NewObjectExpr('MapClassLoader', array($map)));
         $block[] = new MethodCallStatement('$map', 'register', array(false));
     }
     if (!empty($psr4)) {
         $this->logger->debug('Found PSR-4 autoload, adding Psr4ClassLoader...');
         $block[] = new AssignStatement('$psr4', new NewObjectExpr('Psr4ClassLoader', array($psr4)));
         $block[] = new MethodCallStatement('$psr4', 'register', array(false));
     }
     if (!empty($psr0)) {
         $this->logger->debug('Found PSR-0 autoload, adding Psr0ClassLoader...');
         $block[] = new AssignStatement('$psr0', new NewObjectExpr('Psr0ClassLoader', array($psr0)));
         $block[] = new MethodCallStatement('$psr0', 'register', array(false));
     }
     $this->logger->debug('Rendering code using CodeGen...');
     return $block->render();
 }
Example #10
0
 public function render(array $args = array())
 {
     return 'function ' . $this->name . '(' . $this->renderArguments() . ")\n" . $this->block->render($args);
 }
Example #11
0
 private static function createRowOptionTest(DataTable $dt, ActionOption $action, Block $codeBlock)
 {
     $x = 1;
     $options = ['session' => '$session', 'xpath' => $action->getXpath()];
     if ($action->isModalAction()) {
         $codeBlock->appendRenderable(new Comment('dt modal: ' . $action->getTitle()));
         $codeBlock->appendRenderable(new Statement(new StaticMethodCall('parent', 'dtModalTest', $options)));
     } elseif ($action->hasAttribute('href')) {
         $codeBlock->appendRenderable(new Comment('dt href: ' . $action->getTitle()));
         $codeBlock->appendRenderable(new Statement(new StaticMethodCall('parent', 'dtOptionActionTest', $options)));
     } else {
         $x = 1;
     }
 }