Example #1
0
 public static function make($class, $params = array())
 {
     if (!class_exists($class)) {
         throw new \RuntimeException("Stubbed class {$class} doesn't exist. Use Stub::factory instead");
     }
     $reflection = new \ReflectionClass($class);
     $callables = array_filter($params, function ($a) {
         return is_callable($a);
     });
     if (!empty($callables)) {
         if ($reflection->isAbstract()) {
             $mock = \PHPUnit_Framework_MockObject_Generator::getMockForAbstractClass($class, array_keys($callables), '', false);
         } else {
             $mock = \PHPUnit_Framework_MockObject_Generator::getMock($class, array_keys($callables), array(), '', false);
         }
     } else {
         if ($reflection->isAbstract()) {
             $mock = \PHPUnit_Framework_MockObject_Generator::getMockForAbstractClass($class, null, '', false);
         } else {
             $mock = \PHPUnit_Framework_MockObject_Generator::getMock($class, null, array(), '', false);
         }
     }
     self::bindParameters($mock, $params);
     $mock->__mocked = $class;
     return $mock;
 }
Example #2
0
 public function load()
 {
     $files = $this->_getFiles();
     $manifestRegistry = ZendL_Tool_Rpc_Manifest_Registry::getInstance();
     $providerRegistry = ZendL_Tool_Rpc_Provider_Registry::getInstance();
     $classesLoadedBefore = get_declared_classes();
     $oldLevel = error_reporting(E_ALL | ~E_STRICT);
     // remove strict so that other packages wont throw warnings
     foreach ($files as $file) {
         require_once $file;
     }
     error_reporting($oldLevel);
     // restore old error level
     $classesLoadedAfter = get_declared_classes();
     $loadedClasses = array_diff($classesLoadedAfter, $classesLoadedBefore);
     foreach ($loadedClasses as $loadedClass) {
         $reflectionClass = new ReflectionClass($loadedClass);
         if ($reflectionClass->implementsInterface('ZendL_Tool_Rpc_Manifest_Interface') && !$reflectionClass->isAbstract()) {
             $manifestRegistry->addManifest($reflectionClass->newInstance());
         }
         if ($reflectionClass->implementsInterface('ZendL_Tool_Rpc_Provider_Interface') && !$reflectionClass->isAbstract()) {
             $providerRegistry->addProvider($reflectionClass->newInstance());
         }
     }
 }
Example #3
0
 public function testContracts()
 {
     $this->assertTrue($this->reflectedObject->isAbstract());
     $this->assertTrue($this->reflectedObject->hasMethod('cleanVar'));
     $this->assertTrue($this->reflectedObject->hasMethod('getVar'));
     $this->assertInstanceOf('\\Xoops\\Core\\Text\\Sanitizer', \PHPUnit_Framework_Assert::readAttribute($this->object, 'ts'));
 }
Example #4
0
 /**
  * Exports the PHP code
  *
  * @return string
  */
 public function exportCode()
 {
     $code_lines = array();
     $code_lines[] = '<?php';
     // Export the namespace
     if ($this->_reflection_class->getNamespaceName()) {
         $code_lines[] = '';
         $code_lines[] = 'namespace ' . $this->_reflection_class->getNamespaceName() . ';';
         $code_lines[] = '';
     }
     // Export the class' signature
     $code_lines[] = sprintf('%s%s%s %s%s%s', $this->_reflection_class->isAbstract() ? 'abstract ' : '', $this->_reflection_class->isFinal() ? 'final ' : '', $this->_reflection_class->isInterface() ? 'interface' : ($this->_reflection_class->isTrait() ? 'trait' : 'class'), $this->getClassName(), $this->_getParentClassName() ? " extends {$this->_getParentClassName()}" : '', $this->_getInterfaceNames() ? " implements " . join(', ', $this->_getInterfaceNames()) : '');
     $code_lines[] = '{';
     $code_lines[] = '';
     // Export constants
     foreach ($this->_reflection_class->getConstants() as $name => $value) {
         $reflection_constant = new ReflectionConstant($name, $value);
         $code_lines[] = "\t" . $reflection_constant->exportCode();
         $code_lines[] = '';
     }
     // Export properties
     foreach ($this->_reflection_class->getProperties() as $property) {
         $reflection_property = new ReflectionProperty($property);
         $code_lines[] = "\t" . $reflection_property->exportCode();
         $code_lines[] = '';
     }
     // Export methods
     foreach ($this->_reflection_class->getMethods() as $method) {
         $reflection_method = new ReflectionMethod($method);
         $code_lines[] = "\t" . $reflection_method->exportCode();
         $code_lines[] = '';
     }
     $code_lines[] = '}';
     return join("\n", $code_lines);
 }
 public function testContracts()
 {
     $this->assertTrue($this->reflectedObject->isAbstract());
     $this->assertTrue($this->reflectedObject->hasMethod('getDhtmlEditorSupport'));
     $this->assertTrue($this->reflectedObject->hasMethod('registerExtensionProcessing'));
     $this->assertTrue($this->reflectedObject->hasMethod('getEditorButtonHtml'));
 }
 public function testContracts()
 {
     $this->assertTrue($this->reflectedObject->isAbstract());
     $this->assertTrue($this->reflectedObject->hasMethod('getDefaultConfig'));
     $this->assertTrue($this->reflectedObject->hasProperty('ts'));
     $this->assertTrue($this->reflectedObject->hasProperty('shortcodes'));
     $this->assertTrue($this->reflectedObject->hasProperty('config'));
 }
Example #7
0
 /**
  * Loads the metadata for the specified class into the provided container.
  *
  * @param string        $className
  * @param ClassMetadata $metadata
  *
  * @throws \Exception
  * @return void
  */
 public function loadMetadataForClass($className, ClassMetadata $metadata)
 {
     if (!$metadata instanceof \Doctrine\ORM\Mapping\ClassMetadata) {
         throw new \Exception('Error: class metadata object is the wrong type');
     }
     $refClass = new \ReflectionClass($className);
     $classDocBlock = $refClass->getDocComment();
     if (!$classDocBlock || strpos($classDocBlock, '@Table') === false) {
         $metadata->setPrimaryTable(['name' => $this->_getTableName($className)]);
     }
     $needAutoGenerator = false;
     foreach ($refClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $prop) {
         $propName = $prop->getName();
         try {
             $mapping = $metadata->getFieldMapping($propName);
         } catch (MappingException $e) {
             $mapping = null;
         }
         if (!$mapping) {
             if ($propName == 'createdAt') {
                 if (!$this->isTransient($className) && !$refClass->isAbstract() && call_user_func($className . '::useAutoTimestamp')) {
                     $metadata->mapField(['fieldName' => 'createdAt', 'columnName' => call_user_func($className . '::getCreatedAtColumn'), 'type' => 'datetime']);
                 }
             } else {
                 if ($propName == 'updatedAt') {
                     if (!$this->isTransient($className) && !$refClass->isAbstract() && call_user_func($className . '::useAutoTimestamp')) {
                         $metadata->mapField(['fieldName' => 'updatedAt', 'columnName' => call_user_func($className . '::getUpdatedAtColumn'), 'type' => 'datetime']);
                     }
                 } else {
                     $columnName = Inflector::tableize($propName);
                     $fieldMap = ['fieldName' => $propName, 'columnName' => $columnName, 'type' => $this->_getDefaultDataType($columnName)];
                     if ($columnName == 'id') {
                         $fieldMap['id'] = true;
                         $fieldMap['autoincrement'] = true;
                         $fieldMap['unsigned'] = true;
                         $needAutoGenerator = true;
                     } else {
                         if (in_array($columnName, ['price', 'tax', 'amount', 'cost', 'total'])) {
                             // DECIMAL(10,2)
                             $fieldMap['precision'] = 10;
                             $fieldMap['scale'] = 2;
                         }
                     }
                     $metadata->mapField($fieldMap);
                 }
             }
         }
     }
     if ($needAutoGenerator && !$metadata->usesIdGenerator()) {
         $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_AUTO);
     }
 }
 public function testContracts()
 {
     $this->assertTrue($this->reflectedObject->isAbstract());
     $this->assertTrue($this->reflectedObject->hasMethod('get'));
     $this->assertTrue($this->reflectedObject->hasMethod('set'));
     $this->assertTrue($this->reflectedObject->hasMethod('getAll'));
     $this->assertTrue($this->reflectedObject->hasMethod('getNames'));
     $this->assertTrue($this->reflectedObject->hasMethod('has'));
     $this->assertTrue($this->reflectedObject->hasMethod('remove'));
     $this->assertTrue($this->reflectedObject->hasMethod('clear'));
     $this->assertTrue($this->reflectedObject->hasMethod('setAll'));
     $this->assertTrue($this->reflectedObject->hasMethod('setMerge'));
     $this->assertTrue($this->reflectedObject->hasMethod('setArrayItem'));
     $this->assertTrue($this->reflectedObject->hasMethod('getAllLike'));
 }
 /**
  * @param \Donquixote\HastyReflectionCommon\Canvas\ClassIndex\ClassIndexInterface $classIndex
  * @param string $class
  *
  * @dataProvider provideClassIndexArgs()
  */
 function testClassIndex(ClassIndexInterface $classIndex, $class)
 {
     $classReflection = $classIndex->classGetReflection($class);
     $reflectionClass = new \ReflectionClass($class);
     // Test identity.
     $this->assertTrue($classReflection === $classIndex->classGetReflection($class));
     // Test class type/info.
     $expectedIsClass = !$reflectionClass->isInterface() && !$reflectionClass->isTrait();
     $this->assertEquals($reflectionClass->getName(), $classReflection->getName());
     $this->assertEquals($reflectionClass->getShortName(), $classReflection->getShortName());
     $this->assertEquals($reflectionClass->getDocComment(), $classReflection->getDocComment());
     $this->assertEquals($reflectionClass->isInterface(), $classReflection->isInterface());
     $this->assertEquals($reflectionClass->isTrait(), $classReflection->isTrait());
     $this->assertEquals($expectedIsClass, $classReflection->isClass());
     $this->assertEquals($reflectionClass->isAbstract() && $expectedIsClass, $classReflection->isAbstractClass());
     // Test context.
     $this->assertEquals($reflectionClass->getNamespaceName(), $classReflection->getNamespaceUseContext()->getNamespaceName());
     // Test interfaces
     foreach ($classReflection->getOwnInterfaces() as $interfaceName => $interfaceReflection) {
         $this->assertTrue($reflectionClass->implementsInterface($interfaceName));
     }
     foreach ($reflectionClass->getInterfaceNames() as $interfaceName) {
         $this->assertTrue($classReflection->extendsOrImplementsInterface($interfaceName, FALSE));
     }
     $expectedAllInterfaceNames = $expectedAllAndSelfInterfaceNames = $reflectionClass->getInterfaceNames();
     if ($reflectionClass->isInterface()) {
         array_unshift($expectedAllAndSelfInterfaceNames, $class);
     }
     $this->assertEqualSorted($expectedAllAndSelfInterfaceNames, array_keys($classReflection->getAllInterfaces(TRUE)));
     $this->assertEqualSorted($expectedAllInterfaceNames, array_keys($classReflection->getAllInterfaces(FALSE)));
     $expectedMethodNames = array();
     $expectedOwnMethodNames = array();
     foreach ($reflectionClass->getMethods() as $method) {
         $expectedMethodNames[] = $method->getName();
         if ($method->getDeclaringClass()->getName() === $reflectionClass->getName()) {
             $expectedOwnMethodNames[] = $method->getName();
         }
     }
     $this->assertEquals($expectedOwnMethodNames, array_keys($classReflection->getOwnMethods()));
     $this->assertEqualSorted($expectedMethodNames, array_keys($classReflection->getMethods()));
     $methodReflections = $classReflection->getMethods();
     foreach ($reflectionClass->getMethods() as $reflectionMethod) {
         $methodReflection = $methodReflections[$reflectionMethod->getShortName()];
         $this->assertEqualMethods($reflectionMethod, $methodReflection);
     }
     // isAbstract() is a beast, so we test it least.
     $this->assertEquals($reflectionClass->isAbstract(), $classReflection->isAbstract());
 }
 /**
  * @return array
  */
 public function allBlocksDataProvider()
 {
     $blockClass = '';
     try {
         /** @var $website \Magento\Store\Model\Website */
         \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->setWebsiteId(0);
         $enabledModules = $this->_getEnabledModules();
         $skipBlocks = $this->_getBlocksToSkip();
         $templateBlocks = [];
         $blockMods = \Magento\Framework\App\Utility\Classes::collectModuleClasses('Block');
         foreach ($blockMods as $blockClass => $module) {
             if (!isset($enabledModules[$module]) || isset($skipBlocks[$blockClass])) {
                 continue;
             }
             $class = new \ReflectionClass($blockClass);
             if ($class->isAbstract() || !$class->isSubclassOf('Magento\\Framework\\View\\Element\\Template')) {
                 continue;
             }
             $templateBlocks = $this->_addBlock($module, $blockClass, $class, $templateBlocks);
         }
         return $templateBlocks;
     } catch (\Exception $e) {
         trigger_error("Corrupted data provider. Last known block instantiation attempt: '{$blockClass}'." . " Exception: {$e}", E_USER_ERROR);
     }
 }
Example #11
0
 /**
  * Constructor
  *
  * @param string|object $base_class Class name of the base class, or an instance
  * @param array $constructor_args (Optional) Arguments to pass to the constructor of the base class
  * @param array $constants (Optional) Constants to override
  */
 public function __construct($base_class, array $constructor_args = array(), array $constants = array())
 {
     // @codeCoverageIgnoreStart
     if (PHP_VERSION_ID < 50300) {
         trigger_error(get_class() . ': This class requires PHP version 5.3 or higher.', E_USER_ERROR);
     }
     // @codeCoverageIgnoreEnd
     if (is_object($base_class) && count($constructor_args)) {
         throw new Mollie_Testing_Exception('Unused constructor arguments for passed instance of "' . get_class($base_class) . '".');
     }
     // If it's an instance, just accept it
     if (is_object($base_class)) {
         $this->_base_class = $base_class;
     } elseif (!class_exists($base_class)) {
         throw new Mollie_Testing_Exception("Base class '{$base_class}' does not exist.");
     } else {
         $ref = new ReflectionClass($base_class);
         if ($ref->isAbstract()) {
             $ref = new ReflectionClass($this->createDerivedClass($base_class));
         }
         if ($ref->getConstructor() && count($constructor_args) < $ref->getConstructor()->getNumberOfRequiredParameters()) {
             throw new Mollie_Testing_Exception($ref->getConstructor()->getNumberOfRequiredParameters() . " constructor arguments required for '{$base_class}::__construct(...)'.");
         }
         $this->_base_class = sizeof($constructor_args) ? $ref->newInstanceArgs($constructor_args) : $ref->newInstance();
     }
 }
 protected function renderContent()
 {
     $placedViewTypes = $this->getPlacedViewTypes();
     $modules = Module::getModuleObjects();
     foreach ($modules as $module) {
         if ($module->isEnabled()) {
             $p = $module->getParentModule();
             $viewClassNames = $module::getViewClassNames();
             foreach ($viewClassNames as $className) {
                 $viewReflectionClass = new ReflectionClass($className);
                 if (!$viewReflectionClass->isAbstract()) {
                     $portletRules = PortletRulesFactory::createPortletRulesByView($className);
                     if ($portletRules != null && $portletRules->allowOnDashboard()) {
                         if ($portletRules->allowMultiplePlacementOnDashboard() && PortletsSecurityUtil::doesCurrentUserHavePermissionToAddPortlet($portletRules) === true || !$portletRules->allowMultiplePlacementOnDashboard() && !in_array($portletRules->getType(), $placedViewTypes) && PortletsSecurityUtil::doesCurrentUserHavePermissionToAddPortlet($portletRules) === true) {
                             $metadata = $className::getMetadata();
                             $url = Yii::app()->createUrl($this->moduleId . '/defaultPortlet/add', array('uniqueLayoutId' => $this->uniqueLayoutId, 'dashboardId' => $this->dashboardId, 'portletType' => $portletRules->getType()));
                             if (isset($metadata['perUser']['title'])) {
                                 $title = $metadata['perUser']['title'];
                             } else {
                                 continue;
                             }
                             MetadataUtil::resolveEvaluateSubString($title);
                             $sortablePortlets[$title] = array('url' => $url, 'title' => $title, 'portletRules' => $portletRules);
                         }
                     }
                 }
             }
         }
     }
     return PortletUtil::renderAddPortletsContent($sortablePortlets);
 }
Example #13
0
 /**
  * Generates and checks presenter class name.
  * @param  string  presenter name
  * @return string  class name
  * @throws InvalidPresenterException
  */
 public function getPresenterClass(&$name)
 {
     if (isset($this->cache[$name])) {
         return $this->cache[$name];
     }
     if (!is_string($name) || !Nette\Utils\Strings::match($name, '#^[a-zA-Z\\x7f-\\xff][a-zA-Z0-9\\x7f-\\xff:]*\\z#')) {
         throw new InvalidPresenterException("Presenter name must be alphanumeric string, '{$name}' is invalid.");
     }
     $class = $this->formatPresenterClass($name);
     if (!class_exists($class)) {
         throw new InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' was not found.");
     }
     $reflection = new \ReflectionClass($class);
     $class = $reflection->getName();
     if (!$reflection->implementsInterface('Nette\\Application\\IPresenter')) {
         throw new InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' is not Nette\\Application\\IPresenter implementor.");
     } elseif ($reflection->isAbstract()) {
         throw new InvalidPresenterException("Cannot load presenter '{$name}', class '{$class}' is abstract.");
     }
     $this->cache[$name] = $class;
     if ($name !== ($realName = $this->unformatPresenterClass($class))) {
         trigger_error("Case mismatch on presenter name '{$name}', correct name is '{$realName}'.", E_USER_WARNING);
         $name = $realName;
     }
     return $class;
 }
 private function makeInstanceFromClassName($className, array $alreadySeen)
 {
     $className = $this->resolveClassName($className);
     try {
         $refl = new ReflectionClass($className);
     } catch (ReflectionException $re) {
         throw new Core_Foundation_IoC_Exception(sprintf('This doesn\'t seem to be a class name: `%s`.', $className));
     }
     $args = array();
     if ($refl->isAbstract()) {
         throw new Core_Foundation_IoC_Exception(sprintf('Cannot build abstract class: `%s`.', $className));
     }
     $classConstructor = $refl->getConstructor();
     if ($classConstructor) {
         foreach ($classConstructor->getParameters() as $param) {
             $paramClass = $param->getClass();
             if ($paramClass) {
                 $args[] = $this->doMake($param->getClass()->getName(), $alreadySeen);
             } elseif ($param->isDefaultValueAvailable()) {
                 $args[] = $param->getDefaultValue();
             } else {
                 throw new Core_Foundation_IoC_Exception(sprintf('Cannot build a `%s`.', $className));
             }
         }
     }
     if (count($args) > 0) {
         return $refl->newInstanceArgs($args);
     } else {
         // newInstanceArgs with empty array fails in PHP 5.3 when the class
         // doesn't have an explicitly defined constructor
         return $refl->newInstance();
     }
 }
Example #15
0
function __autoload($className)
{
    if (function_exists('smartyAutoload') and smartyAutoload($className)) {
        return true;
    }
    $className = str_replace(chr(0), '', $className);
    $classDir = dirname(__FILE__) . '/../classes/';
    $overrideDir = dirname(__FILE__) . '/../override/classes/';
    $file_in_override = file_exists($overrideDir . $className . '.php');
    $file_in_classes = file_exists($classDir . $className . '.php');
    // This is a Core class and its name is the same as its declared name
    if (substr($className, -4) == 'Core') {
        require_once $classDir . substr($className, 0, -4) . '.php';
    } else {
        if ($file_in_override && $file_in_classes) {
            require_once $classDir . str_replace(chr(0), '', $className) . '.php';
            require_once $overrideDir . $className . '.php';
        } elseif (!$file_in_override && $file_in_classes) {
            require_once $classDir . str_replace(chr(0), '', $className) . '.php';
            $classInfos = new ReflectionClass($className . ((interface_exists($className, false) or class_exists($className, false)) ? '' : 'Core'));
            if (!$classInfos->isInterface() && substr($classInfos->name, -4) == 'Core') {
                eval(($classInfos->isAbstract() ? 'abstract ' : '') . 'class ' . $className . ' extends ' . $className . 'Core {}');
            }
        } elseif ($file_in_override && !$file_in_classes) {
            require_once $overrideDir . $className . '.php';
        }
    }
}
 /**
  * Get controller to use, either plugin controller or application controller
  *
  * @param \Cake\Network\Request $request Request object
  * @param \Cake\Network\Response $response Response for the controller.
  * @return mixed name of controller if not loaded, or object if loaded
  */
 protected function _getController($request, $response)
 {
     $pluginPath = $controller = null;
     $namespace = 'Controller';
     if (!empty($request->params['plugin'])) {
         $pluginPath = $request->params['plugin'] . '.';
     }
     if (!empty($request->params['controller'])) {
         $controller = $request->params['controller'];
     }
     if (!empty($request->params['prefix'])) {
         $prefixes = array_map('Cake\\Utility\\Inflector::camelize', explode('/', $request->params['prefix']));
         $namespace .= '/' . implode('/', $prefixes);
     }
     $className = false;
     if ($pluginPath . $controller) {
         $className = App::classname($pluginPath . $controller, $namespace, 'Controller');
     }
     if (!$className) {
         return false;
     }
     $reflection = new \ReflectionClass($className);
     if ($reflection->isAbstract() || $reflection->isInterface()) {
         return false;
     }
     return $reflection->newInstance($request, $response, $controller);
 }
Example #17
0
 protected function _checkProtection($protectionType)
 {
     // Check type
     if (!is_string($protectionType) || $protectionType != self::PROTECTION_CSRF && $protectionType != self::PROTECTION_CAPTCHA && $protectionType != self::PROTECTION_BRUTEFORCE && $protectionType != self::PROTECTION_XSS) {
         throw new \Exception('Invalid protection type : "' . $protectionType . '"');
     }
     // Check class
     if (class_exists('framework\\security\\form\\' . ucfirst($protectionType))) {
         $className = 'framework\\security\\form\\' . ucfirst($protectionType);
     } else {
         $className = $protectionType;
     }
     $class = new \ReflectionClass($className);
     if (!in_array('framework\\security\\IForm', $class->getInterfaceNames())) {
         throw new \Exception('Form protection drivers must be implement framework\\security\\IForm');
     }
     if ($class->isAbstract()) {
         throw new \Exception('Form protection drivers must be not abstract class');
     }
     if ($class->isInterface()) {
         throw new \Exception('Form protection drivers must be not interface');
     }
     $classInstance = $class->newInstanceWithoutConstructor();
     $constuctor = new \ReflectionMethod($classInstance, '__construct');
     if ($constuctor->isPrivate() || $constuctor->isProtected()) {
         throw new \Exception('Protection constructor must be public');
     }
     return $className;
 }
Example #18
0
 private function findRepositories($config)
 {
     $classes = [];
     if ($config['scanDirs']) {
         $robot = new RobotLoader();
         $robot->setCacheStorage(new Nette\Caching\Storages\DevNullStorage());
         $robot->addDirectory($config['scanDirs']);
         $robot->acceptFiles = '*.php';
         $robot->rebuild();
         $classes = array_keys($robot->getIndexedClasses());
     }
     $repositories = [];
     foreach (array_unique($classes) as $class) {
         if (class_exists($class) && ($rc = new \ReflectionClass($class)) && $rc->isSubclassOf('Joseki\\LeanMapper\\Repository') && !$rc->isAbstract()) {
             $repositoryClass = $rc->getName();
             $entityClass = Strings::endsWith($repositoryClass, 'Repository') ? substr($repositoryClass, 0, strlen($repositoryClass) - 10) : $repositoryClass;
             $table = Utils::camelToUnderscore(Utils::trimNamespace($entityClass));
             if (array_key_exists($table, $repositories)) {
                 throw new \Exception(sprintf('Multiple repositories for table %s found.', $table));
             }
             $repositories[$table] = $repositoryClass;
         }
     }
     return $repositories;
 }
Example #19
0
 /**
  * Creates a PHP class from reflection
  * 
  * @param \ReflectionClass $ref
  * @return PhpClass
  */
 public static function fromReflection(\ReflectionClass $ref)
 {
     $class = new static();
     $class->setQualifiedName($ref->name)->setAbstract($ref->isAbstract())->setFinal($ref->isFinal())->setUseStatements(ReflectionUtils::getUseStatements($ref));
     if ($ref->getDocComment()) {
         $docblock = new Docblock($ref);
         $class->setDocblock($docblock);
         $class->setDescription($docblock->getShortDescription());
         $class->setLongDescription($docblock->getLongDescription());
     }
     // methods
     foreach ($ref->getMethods() as $method) {
         $class->setMethod(static::createMethod($method));
     }
     // properties
     foreach ($ref->getProperties() as $property) {
         $class->setProperty(static::createProperty($property));
     }
     // traits
     foreach ($ref->getTraits() as $trait) {
         $class->addTrait(PhpTrait::fromReflection($trait));
     }
     // constants
     // TODO: https://github.com/gossi/php-code-generator/issues/19
     $class->setConstants($ref->getConstants());
     return $class;
 }
Example #20
0
 /**
  * @param string $class
  * @return bool
  */
 private function getEntryName($class)
 {
     $rc = new \ReflectionClass($class);
     if (!$rc->isAbstract() && ($annotation = $this->reader->getClassAnnotation($rc, static::ENTRY_ANNOTATION))) {
         return $annotation->value;
     }
 }
 /**
  * Finds installable records from the models folder.
  *
  * @return array
  */
 public function findInstallableRecords()
 {
     $records = array();
     $recordsFolder = craft()->path->getAppPath() . 'records/';
     $recordFiles = IOHelper::getFolderContents($recordsFolder, false, ".*Record\\.php\$");
     foreach ($recordFiles as $file) {
         if (IOHelper::fileExists($file)) {
             $fileName = IOHelper::getFileName($file, false);
             $class = __NAMESPACE__ . '\\' . $fileName;
             // Ignore abstract classes and interfaces
             $ref = new \ReflectionClass($class);
             if ($ref->isAbstract() || $ref->isInterface()) {
                 Craft::log("Skipping record {$file} because it’s abstract or an interface.", LogLevel::Warning);
                 continue;
             }
             $obj = new $class('install');
             if (method_exists($obj, 'createTable')) {
                 $records[] = $obj;
             } else {
                 Craft::log("Skipping record {$file} because it doesn’t have a createTable() method.", LogLevel::Warning);
             }
         } else {
             Craft::log("Skipping record {$file} because it doesn’t exist.", LogLevel::Warning);
         }
     }
     return $records;
 }
Example #22
0
 public static function resolve($type, $constructorArguments = [])
 {
     $resolvedClass = self::getResolvedClassName($type);
     if ($resolvedClass === null) {
         throw new exceptions\ResolutionException("Could not resolve dependency {$type}");
     }
     $reflection = new \ReflectionClass($resolvedClass);
     if ($reflection->isAbstract()) {
         throw new exceptions\ResolutionException("Abstract class {$reflection->getName()} cannot be instantiated. " . "Please provide a binding to an implementation.");
     }
     $constructor = $reflection->getConstructor();
     $instanceParameters = [];
     if ($constructor != null) {
         $parameters = $constructor->getParameters();
         foreach ($parameters as $parameter) {
             $class = $parameter->getClass();
             if (isset($constructorArguments[$parameter->getName()])) {
                 $instanceParameters[] = $constructorArguments[$parameter->getName()];
             } else {
                 $instanceParameters[] = $class ? self::resolve($class->getName()) : null;
             }
         }
     }
     return $reflection->newInstanceArgs($instanceParameters);
 }
Example #23
0
function classData(ReflectionClass $class)
{
    $details = "";
    $name = $class->getName();
    if ($class->isUserDefined()) {
        $details .= "{$name} is user defined\n";
    }
    if ($class->isInternal()) {
        $details .= "{$name} is built-in\n";
    }
    if ($class->isInterface()) {
        $details .= "{$name} is interface\n";
    }
    if ($class->isAbstract()) {
        $details .= "{$name} is an abstract class\n";
    }
    if ($class->isFinal()) {
        $details .= "{$name} is a final class\n";
    }
    if ($class->isInstantiable()) {
        $details .= "{$name} can be instantiated\n";
    } else {
        $details .= "{$name} can not be instantiated\n";
    }
    return $details;
}
 protected function renderContent()
 {
     $placedViewTypes = Portlet::getPlacedViewTypesByLayoutIdAndUser($this->uniqueLayoutId, Yii::app()->user->userModel->id);
     $modules = Module::getModuleObjects();
     $sortablePortlets = array();
     foreach ($modules as $module) {
         if ($module->isEnabled()) {
             $p = $module->getParentModule();
             $viewClassNames = $module::getViewClassNames();
             foreach ($viewClassNames as $className) {
                 $viewReflectionClass = new ReflectionClass($className);
                 if (!$viewReflectionClass->isAbstract()) {
                     $portletRules = PortletRulesFactory::createPortletRulesByView($className);
                     if ($viewReflectionClass->implementsInterface('RelatedPortletViewInterface')) {
                         if ($this->resolveLayoutIdInAllowedOnPortletViewClassNames($className) && $className::allowMultiplePlacement() == false && !in_array($portletRules->getType(), $placedViewTypes) && PortletsSecurityUtil::doesCurrentUserHavePermissionToAddPortlet($portletRules) === true) {
                             $metadata = $className::getMetadata();
                             $url = Yii::app()->createUrl($this->moduleId . '/defaultPortlet/add', array('uniqueLayoutId' => $this->uniqueLayoutId, 'modelId' => $this->modelId, 'portletType' => $portletRules->getType()));
                             $title = $metadata['perUser']['title'];
                             MetadataUtil::resolveEvaluateSubString($title);
                             $sortablePortlets[$title] = array('url' => $url, 'title' => $title, 'portletRules' => $portletRules);
                         }
                     }
                 }
             }
         }
     }
     if (empty($sortablePortlets)) {
         $messageView = new NoPortletsToPlaceView();
         return $messageView->render();
     }
     //Sort by title
     ksort($sortablePortlets);
     return PortletUtil::renderAddPortletsContent($sortablePortlets);
 }
Example #25
0
 /**
  * Creates an object instance of the requested class, optionally passing additional constructor arguments
  *
  * @param $requestedClass
  * @param ...$arguments
  * @return mixed|object
  */
 public final function getInstance($requestedClass, ...$arguments)
 {
     if (isset($this->singletons[$requestedClass])) {
         return $this->singletons[$requestedClass];
     }
     $useSingleton = false;
     // Check for singletons first as they should trump previous registrations of non
     // singleton mappings.
     if (isset($this->concreteClassMappings['_' . $requestedClass])) {
         $class = $this->concreteClassMappings['_' . $requestedClass];
         $useSingleton = true;
     } elseif (isset($this->concreteClassMappings[$requestedClass])) {
         $class = $this->concreteClassMappings[$requestedClass];
     } else {
         $class = $requestedClass;
     }
     $reflection = new \ReflectionClass($class);
     if ($reflection->isAbstract()) {
         throw new ClassMappingException($class);
     }
     $constructor = $reflection->getConstructor();
     if ($constructor == null) {
         // No defined constructor so exit simply with a new instance.
         $instance = $reflection->newInstanceArgs($arguments);
     } else {
         $instance = $this->generateInstanceFromConstructor($reflection, $constructor, $arguments);
     }
     if ($useSingleton) {
         $this->singletons[$requestedClass] = $instance;
     }
     return $instance;
 }
Example #26
0
 public static function fromReflection(\ReflectionClass $ref)
 {
     $class = new static();
     $class->setName($ref->name)->setAbstract($ref->isAbstract())->setFinal($ref->isFinal())->setConstants($ref->getConstants());
     if (null === self::$phpParser) {
         if (!class_exists('Doctrine\\Common\\Annotations\\PhpParser')) {
             self::$phpParser = false;
         } else {
             self::$phpParser = new PhpParser();
         }
     }
     if (false !== self::$phpParser) {
         $class->setUseStatements(self::$phpParser->parseClass($ref));
     }
     if ($docComment = $ref->getDocComment()) {
         $class->setDocblock(ReflectionUtils::getUnindentedDocComment($docComment));
     }
     foreach ($ref->getMethods() as $method) {
         $class->setMethod(static::createMethod($method));
     }
     foreach ($ref->getProperties() as $property) {
         $class->setProperty(static::createProperty($property));
     }
     return $class;
 }
Example #27
0
 /**
  * @param  \ReflectionClass|string
  * @return self
  */
 public static function from($from)
 {
     $from = new \ReflectionClass($from instanceof \ReflectionClass ? $from->getName() : $from);
     if (PHP_VERSION_ID >= 70000 && $from->isAnonymous()) {
         $class = new static('anonymous');
     } else {
         $class = new static($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
     }
     $class->type = $from->isInterface() ? 'interface' : (PHP_VERSION_ID >= 50400 && $from->isTrait() ? 'trait' : 'class');
     $class->final = $from->isFinal() && $class->type === 'class';
     $class->abstract = $from->isAbstract() && $class->type === 'class';
     $class->implements = $from->getInterfaceNames();
     $class->documents = $from->getDocComment() ? array(preg_replace('#^\\s*\\* ?#m', '', trim($from->getDocComment(), "/* \r\n\t"))) : array();
     if ($from->getParentClass()) {
         $class->extends = $from->getParentClass()->getName();
         $class->implements = array_diff($class->implements, $from->getParentClass()->getInterfaceNames());
     }
     foreach ($from->getProperties() as $prop) {
         if ($prop->getDeclaringClass()->getName() === $from->getName()) {
             $class->properties[$prop->getName()] = Property::from($prop);
         }
     }
     foreach ($from->getMethods() as $method) {
         if ($method->getDeclaringClass()->getName() === $from->getName()) {
             $class->methods[$method->getName()] = Method::from($method)->setNamespace($class->namespace);
         }
     }
     return $class;
 }
 /**
  * Based on the current user, return the importRules types and their display labels.  Only include import rules
  * that the user has a right to access its corresponding module.
  * @return array of import rules types and display labels.
  */
 public static function getImportRulesTypesForCurrentUser()
 {
     //todo: cache results to improve performance if needed.
     $importRulesTypes = array();
     $modules = Module::getModuleObjects();
     foreach ($modules as $module) {
         $rulesClassNames = $module::getAllClassNamesByPathFolder('rules');
         foreach ($rulesClassNames as $ruleClassName) {
             $classToEvaluate = new ReflectionClass($ruleClassName);
             if (is_subclass_of($ruleClassName, 'ImportRules') && !$classToEvaluate->isAbstract()) {
                 $moduleClassNames = $ruleClassName::getModuleClassNames();
                 $addToArray = true;
                 foreach ($moduleClassNames as $moduleClassNameToCheckAccess) {
                     if (!RightsUtil::canUserAccessModule($moduleClassNameToCheckAccess, Yii::app()->user->userModel) || !RightsUtil::doesUserHaveAllowByRightName($moduleClassNameToCheckAccess, $moduleClassNameToCheckAccess::getCreateRight(), Yii::app()->user->userModel)) {
                         $addToArray = false;
                     }
                 }
                 if ($addToArray) {
                     $importRulesTypes[$ruleClassName::getType()] = $ruleClassName::getDisplayLabel();
                 }
             }
         }
     }
     return $importRulesTypes;
 }
Example #29
0
 /**
  * contructor, creates node with reference to record and any options
  *
  * @param object $record                    instance of Doctrine_Record
  * @param array $options                    options
  */
 public function __construct(Doctrine_Record $record, $options)
 {
     $this->record = $record;
     $this->options = $options;
     // Make sure that the tree object of the root class is used in the case
     // of column aggregation inheritance (single table inheritance).
     $class = $record->getTable()->getComponentName();
     $thisTable = $record->getTable();
     $table = $thisTable;
     if ($thisTable->getOption('inheritanceMap')) {
         // Move up the hierarchy until we find the "subclasses" option. This option
         // MUST be set on the root class of the user's hierarchy that uses STI.
         while (!($subclasses = $table->getOption('subclasses'))) {
             $class = get_parent_class($class);
             $reflectionClass = new ReflectionClass($class);
             if ($reflectionClass->isAbstract()) {
                 continue;
             }
             if ($class == 'Doctrine_Record') {
                 throw new Doctrine_Node_Exception("No subclasses specified. You are " . "using Single Table Inheritance with NestedSet but you have " . "not specified the subclasses correctly. Make sure you use " . "setSubclasses() in the root class of your hierarchy.");
             }
             $table = $table->getConnection()->getTable($class);
         }
     }
     if ($thisTable !== $table) {
         $this->_tree = $table->getTree();
     } else {
         $this->_tree = $thisTable->getTree();
     }
 }
Example #30
0
 public function initialize()
 {
     $app = $this->app;
     if ($app['setup']) {
         $this->addView('setup', new Setup($app));
     } else {
         $cacheName = sha1(__CLASS__ . '_backendClasses');
         $backendClasses = $app->cache->load($cacheName);
         if ($backendClasses === false) {
             $backendClasses = array();
             $classes = ClassEnumerator::findClasses(__DIR__ . '/../Backend');
             foreach ($classes as $className) {
                 if (class_exists($className) && $className !== __CLASS__ && $className !== 'Curry\\Backend\\Setup') {
                     $r = new \ReflectionClass($className);
                     if ($r->isSubclassOf('Curry\\Backend\\AbstractBackend') && !$r->isAbstract()) {
                         $backendClasses[strtolower($r->getShortName())] = $className;
                     }
                 }
             }
             $app->cache->save($backendClasses, $cacheName);
         }
         foreach ($backendClasses as $viewName => $className) {
             $this->addView($viewName, new $className($this->app));
         }
     }
 }