Esempio n. 1
0
 /**
  * Load specified class name and generate it if necessary
  *
  * @param string $className
  * @return bool True if class was loaded
  */
 public function load($className)
 {
     if (!class_exists($className)) {
         return Generator::GENERATION_ERROR != $this->_generator->generateClass($className);
     }
     return true;
 }
Esempio n. 2
0
 /**
  * @expectedException \Magento\Framework\Exception
  */
 public function testGenerateClassWithError()
 {
     $this->model = new \Magento\Framework\Code\Generator($this->ioObjectMock, ['factory' => '\\Magento\\Framework\\ObjectManager\\Code\\Generator\\Factory', 'proxy' => '\\Magento\\Framework\\ObjectManager\\Code\\Generator\\Proxy', 'interceptor' => '\\Magento\\Framework\\Interception\\Code\\Generator\\Interceptor']);
     $expectedEntities = array_values($this->expectedEntities);
     $resultClassName = self::SOURCE_CLASS . ucfirst(array_shift($expectedEntities));
     $this->model->generateClass($resultClassName);
 }
Esempio n. 3
0
 /**
  * Load specified class name and generate it if necessary
  *
  * @param string $className
  * @return void
  */
 public function load($className)
 {
     if (!class_exists($className)) {
         if (\Magento\Framework\Code\Generator::GENERATION_SUCCESS === $this->_generator->generateClass($className)) {
             (new \Magento\Framework\Autoload\IncludePath())->load($className);
         }
     }
 }
Esempio n. 4
0
 /**
  * @expectedException \Magento\Framework\Exception\LocalizedException
  */
 public function testGenerateClassWithError()
 {
     $this->model = new \Magento\Framework\Code\Generator($this->ioObjectMock, ['factory' => '\\Magento\\Framework\\ObjectManager\\Code\\Generator\\Factory', 'proxy' => '\\Magento\\Framework\\ObjectManager\\Code\\Generator\\Proxy', 'interceptor' => '\\Magento\\Framework\\Interception\\Code\\Generator\\Interceptor']);
     $expectedEntities = array_values($this->expectedEntities);
     $resultClassName = self::SOURCE_CLASS . ucfirst(array_shift($expectedEntities));
     $objectManagerMock = $this->getMock('Magento\\Framework\\ObjectManagerInterface');
     $entityGeneratorMock = $this->getMockBuilder('\\Magento\\Framework\\Code\\Generator\\EntityAbstract')->disableOriginalConstructor()->getMock();
     $objectManagerMock->expects($this->once())->method('create')->willReturn($entityGeneratorMock);
     $this->model->setObjectManager($objectManagerMock);
     $this->model->generateClass($resultClassName);
 }
Esempio n. 5
0
 /**
  * @expectedException \Magento\Framework\Exception
  */
 public function testGenerateClassWithError()
 {
     $this->autoloader->expects($this->once())->method('getFile')->will($this->returnValue(false));
     $this->model = new \Magento\Framework\Code\Generator($this->autoloader, $this->ioObjectMock, array('factory' => '\\Magento\\Framework\\ObjectManager\\Code\\Generator\\Factory', 'proxy' => '\\Magento\\Framework\\ObjectManager\\Code\\Generator\\Proxy', 'interceptor' => '\\Magento\\Framework\\Interception\\Code\\Generator\\Interceptor'));
     $expectedEntities = array_values($this->expectedEntities);
     $resultClassName = self::SOURCE_CLASS . ucfirst(array_shift($expectedEntities));
     $this->model->generateClass($resultClassName);
 }
Esempio n. 6
0
 /**
  * @dataProvider trueFalseDataProvider
  */
 public function testGenerateClassWithExistName($fileExists)
 {
     $this->definedClassesMock->expects($this->any())->method('isClassLoadableFromDisc')->willReturn(true);
     $resultClassFileName = '/Magento/Path/To/Class.php';
     $this->ioObjectMock->expects($this->once())->method('generateResultFileName')->willReturn($resultClassFileName);
     $this->ioObjectMock->expects($this->once())->method('fileExists')->willReturn($fileExists);
     $includeFileInvokeCount = $fileExists ? 1 : 0;
     $this->ioObjectMock->expects($this->exactly($includeFileInvokeCount))->method('includeFile');
     $this->assertEquals(\Magento\Framework\Code\Generator::GENERATION_SKIP, $this->model->generateClass('Magento\\GeneratedClass\\Factory'));
 }
Esempio n. 7
0
 public function testGenerateClassInterceptorWithNamespace()
 {
     $interceptorClassName = self::CLASS_NAME_WITH_NAMESPACE . '\\Interceptor';
     $result = false;
     $generatorResult = $this->_generator->generateClass($interceptorClassName);
     if (\Magento\Framework\Code\Generator::GENERATION_ERROR !== $generatorResult) {
         $result = true;
     }
     $this->assertTrue($result, 'Failed asserting that \'' . (string) $generatorResult . '\' equals \'success\'.');
     if (\Magento\Framework\Code\Generator::GENERATION_SUCCESS == $generatorResult) {
         $content = $this->_clearDocBlock(file_get_contents($this->_ioObject->getResultFileName(self::CLASS_NAME_WITH_NAMESPACE . '\\Interceptor')));
         $expectedContent = $this->_clearDocBlock(file_get_contents(__DIR__ . '/_expected/SourceClassWithNamespaceInterceptor.php.sample'));
         $this->assertEquals($expectedContent, $content);
     }
 }
 /**
  * Compile Code
  *
  * @param string $generationDir
  * @param array $fileExcludePatterns
  * @param InputInterface $input
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 private function compileCode($generationDir, $fileExcludePatterns, $input)
 {
     $diDir = $input->getOption(self::INPUT_KEY_DI) ? $input->getOption(self::INPUT_KEY_DI) : $this->directoryList->getPath(DirectoryList::DI);
     $relationsFile = $diDir . '/relations.ser';
     $pluginDefFile = $diDir . '/plugins.ser';
     $compilationDirs = [$this->directoryList->getPath(DirectoryList::SETUP) . '/Magento/Setup/Module', $this->directoryList->getRoot() . '/dev/tools/Magento/Tools'];
     $compilationDirs = array_merge($compilationDirs, $this->componentRegistrar->getPaths(ComponentRegistrar::MODULE), $this->componentRegistrar->getPaths(ComponentRegistrar::LIBRARY));
     $serializer = $input->getOption(self::INPUT_KEY_SERIALIZER) == Igbinary::NAME ? new Igbinary() : new Standard();
     // 2.1 Code scan
     $validator = new \Magento\Framework\Code\Validator();
     $validator->add(new \Magento\Framework\Code\Validator\ConstructorIntegrity());
     $validator->add(new \Magento\Framework\Code\Validator\ContextAggregation());
     $classesScanner = new \Magento\Setup\Module\Di\Code\Reader\ClassesScanner();
     $classesScanner->addExcludePatterns($fileExcludePatterns);
     $directoryInstancesNamesList = new \Magento\Setup\Module\Di\Code\Reader\Decorator\Directory($this->log, new \Magento\Framework\Code\Reader\ClassReader(), $classesScanner, $validator, $generationDir);
     foreach ($compilationDirs as $path) {
         if (is_readable($path)) {
             $directoryInstancesNamesList->getList($path);
         }
     }
     $inheritanceScanner = new Scanner\InheritanceInterceptorScanner();
     $this->entities['interceptors'] = $inheritanceScanner->collectEntities(get_declared_classes(), $this->entities['interceptors']);
     // 2.1.1 Generation of Proxy and Interceptor Classes
     foreach (['interceptors', 'di'] as $type) {
         foreach ($this->entities[$type] as $entityName) {
             switch ($this->generator->generateClass($entityName)) {
                 case \Magento\Framework\Code\Generator::GENERATION_SUCCESS:
                     $this->log->add(Log::GENERATION_SUCCESS, $entityName);
                     break;
                 case \Magento\Framework\Code\Generator::GENERATION_ERROR:
                     $this->log->add(Log::GENERATION_ERROR, $entityName);
                     break;
                 case \Magento\Framework\Code\Generator::GENERATION_SKIP:
                 default:
                     //no log
                     break;
             }
         }
     }
     //2.1.2 Compile relations for Proxy/Interceptor classes
     $directoryInstancesNamesList->getList($generationDir);
     $relations = $directoryInstancesNamesList->getRelations();
     // 2.2 Compression
     $relationsFileDir = dirname($relationsFile);
     if (!file_exists($relationsFileDir)) {
         mkdir($relationsFileDir, DriverInterface::WRITEABLE_DIRECTORY_MODE, true);
     }
     $relations = array_filter($relations);
     file_put_contents($relationsFile, $serializer->serialize($relations));
     // 3. Plugin Definition Compilation
     $pluginScanner = new Scanner\CompositeScanner();
     $pluginScanner->addChild(new Scanner\PluginScanner(), 'di');
     $pluginDefinitions = [];
     $pluginList = $pluginScanner->collectEntities($this->files);
     $pluginDefinitionList = new \Magento\Framework\Interception\Definition\Runtime();
     foreach ($pluginList as $type => $entityList) {
         foreach ($entityList as $entity) {
             $pluginDefinitions[ltrim($entity, '\\')] = $pluginDefinitionList->getMethodList($entity);
         }
     }
     $outputContent = $serializer->serialize($pluginDefinitions);
     $pluginDefFileDir = dirname($pluginDefFile);
     if (!file_exists($pluginDefFileDir)) {
         mkdir($pluginDefFileDir, DriverInterface::WRITEABLE_DIRECTORY_MODE, true);
     }
     file_put_contents($pluginDefFile, $outputContent);
 }
    if ($opt->getOption('g')) {
        $generationDir = $opt->getOption('g');
    }
    AutoloaderRegistry::getAutoloader()->addPsr4('Magento\\', $generationDir . '/Magento/');
} catch (\Zend_Console_Getopt_Exception $e) {
    $generator = new Generator();
    $entities = $generator->getGeneratedEntities();
    $allowedTypes = 'Allowed entity types are: ' . implode(', ', $entities) . '.';
    $example = 'Example: php -f entity_generator.php -- -t factory -c \\Magento\\Framework\\Event\\Observer ' . '-g /var/mage/m2ee/generation' . ' - will generate file /var/mage/m2ee/generation/Magento/Framework/Event/ObserverFactory.php';
    echo $e->getMessage() . "\n";
    echo $e->getUsageMessage() . "\n";
    echo $allowedTypes . "\n";
    echo 'Default generation dir is ' . $generationDir . "\n";
    exit($example);
}
//reinit generator with correct generation path
$io = new Io(new File(), $generationDir);
$generator = new Generator($io, [Proxy::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Proxy', Factory::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Factory', Interceptor::ENTITY_TYPE => 'Magento\\Framework\\Interception\\Code\\Generator\\Interceptor', Mapper::ENTITY_TYPE => 'Magento\\Framework\\Api\\Code\\Generator\\Mapper', Repository::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Repository', Converter::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Converter', SearchResults::ENTITY_TYPE => 'Magento\\Framework\\Api\\Code\\Generator\\SearchResults', ExtensionAttributesInterfaceGenerator::ENTITY_TYPE => 'Magento\\Framework\\Api\\Code\\Generator\\ExtensionAttributesInterfaceGenerator', ExtensionAttributesGenerator::ENTITY_TYPE => 'Magento\\Framework\\Api\\Code\\Generator\\ExtensionAttributesGenerator']);
/** Initialize object manager for code generation based on configs */
$magentoObjectManagerFactory = \Magento\Framework\App\Bootstrap::createObjectManagerFactory(BP, $_SERVER);
$objectManager = $magentoObjectManagerFactory->create($_SERVER);
$generator->setObjectManager($objectManager);
try {
    if (Generator::GENERATION_SUCCESS == $generator->generateClass($className)) {
        print "Class {$className} was successfully generated.\n";
    } else {
        print "Can't generate class {$className}. This class either not generated entity, or it already exists.\n";
    }
} catch (Exception $e) {
    print "Error! {$e->getMessage()}\n";
}
Esempio n. 10
0
    if (!in_array($entityType, array_keys($substitutions))) {
        throw new \Zend_Console_Getopt_Exception('unrecognized type: ' . $entityType);
    }
    $className .= $substitutions[$entityType];
    if ($opt->getOption('g')) {
        $generationDir = $opt->getOption('g');
    }
} catch (\Zend_Console_Getopt_Exception $e) {
    $generator = new Generator();
    $entities = $generator->getGeneratedEntities();
    $allowedTypes = 'Allowed entity types are: ' . implode(', ', $entities) . '.';
    $example = 'Example: php -f entity_generator.php -- -t factory -c \\Magento\\Framework\\Event\\Observer ' . '-g /var/mage/m2ee/generation' . ' - will generate file /var/mage/m2ee/generation/Magento/Framework/Event/ObserverFactory.php';
    echo $e->getMessage() . "\n";
    echo $e->getUsageMessage() . "\n";
    echo $allowedTypes . "\n";
    echo 'Default generation dir is ' . $generationDir . "\n";
    exit($example);
}
(new \Magento\Framework\Autoload\IncludePath())->addIncludePath($generationDir);
//reinit generator with correct generation path
$io = new Io(new File(), null, $generationDir);
$generator = new Generator(null, $io, [SearchResultsBuilder::ENTITY_TYPE => 'Magento\\Framework\\Service\\Code\\Generator\\SearchResultsBuilder', Proxy::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Proxy', Factory::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Factory', Interceptor::ENTITY_TYPE => 'Magento\\Framework\\Interception\\Code\\Generator\\Interceptor', Builder::ENTITY_TYPE => 'Magento\\Framework\\Service\\Code\\Generator\\Builder', Mapper::ENTITY_TYPE => 'Magento\\Framework\\Service\\Code\\Generator\\Mapper', Repository::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Repository', Converter::ENTITY_TYPE => 'Magento\\Framework\\ObjectManager\\Code\\Generator\\Converter', SearchResults::ENTITY_TYPE => 'Magento\\Framework\\Service\\Code\\Generator\\SearchResults']);
try {
    if (Generator::GENERATION_SUCCESS == $generator->generateClass($className)) {
        print "Class {$className} was successfully generated.\n";
    } else {
        print "Can't generate class {$className}. This class either not generated entity, or it already exists.\n";
    }
} catch (Exception $e) {
    print "Error! {$e->getMessage()}\n";
}
Esempio n. 11
0
 /**
  * Create entity generator
  *
  * @param string $generatorClass
  * @param string $entityName
  * @param string $className
  * @return \Magento\Framework\Code\Generator\EntityAbstract
  */
 protected function createGeneratorInstance($generatorClass, $entityName, $className)
 {
     $generatorClass = parent::createGeneratorInstance($generatorClass, $entityName, $className);
     $generatorClass->setInterceptedMethods($this->classMethods);
     return $generatorClass;
 }