Example #1
0
 /**
  * @param string $entityName
  */
 public function __construct($entityName)
 {
     $this->entityReflectionClass = new \ReflectionClass($entityName);
     if (!$this->entityReflectionClass->isSubclassOf(AggregateRootInterface::class)) {
         throw new \LogicException(\sprintf('%s not implement %s, only the aggregate roots can have a repository class', $this->entityReflectionClass->name, AggregateRootInterface::class));
     }
 }
 /**
  * DocBlockGenerator constructor.
  *
  * @param $className
  */
 public function __construct($className)
 {
     $this->className = $className;
     $this->reflector = new ReflectionClass($className);
     $generatorClass = $this->reflector->isSubclassOf('Controller') ? 'ControllerTagGenerator' : 'OrmTagGenerator';
     $this->tagGenerator = new $generatorClass($className, $this->getExistingTags());
 }
 public function display($url)
 {
     $data = (object) json_decode(file_get_contents('php://input'), true);
     $reflection = new ReflectionClass($data->_type);
     if ($reflection->isSubclassOf('DataSource')) {
         $object = $reflection->newInstance();
         $object->parameters()->{'root-element'} = 'data';
         foreach ($data->_parameters as $key => $value) {
             $object->parameters()->{$key} = $value;
         }
         $result = $object->render(new Register());
         header('content-type: text/xml');
         echo $result->saveXML();
         exit;
     }
     if ($reflection->isSubclassOf('Event')) {
         $object = $reflection->newInstance();
         $object->parameters()->{'root-element'} = 'data';
         foreach ($data->_parameters as $key => $value) {
             $object->parameters()->{$key} = $value;
         }
         $result = $object->trigger(new Register(), (array) $data->_data);
         header('content-type: text/xml');
         echo $result->saveXML();
         exit;
     }
 }
 public function testForm()
 {
     $this->loadClassFromVfs("Form/TheliaStudioTestModuleConfigForm");
     $reflection = new \ReflectionClass("TheliaStudioTestModule\\Form\\TheliaStudioTestModuleConfigForm");
     // Test mother classes
     $this->assertTrue($reflection->isSubclassOf("TheliaStudioTestModule\\Form\\Base\\TheliaStudioTestModuleConfigForm"));
     $this->assertTrue($reflection->isSubclassOf("Thelia\\Form\\BaseForm"));
 }
 /**
  * @see \Symfony\Component\HttpKernel\Bundle::registerCommands
  *
  * @param ContainerBuilder $container
  */
 public function process(ContainerBuilder $container)
 {
     if (!$container->hasParameter('bangpound_console.default_application_id')) {
         return;
     }
     $count = 0;
     $defaultApplicationId = $container->getParameter('bangpound_console.default_application_id');
     // Identify classes of already tagged Command services
     // so this pass does not create additional service definitions
     // for them.
     $classes = array_map(function ($id) use($container) {
         $class = $container->getDefinition($id)->getClass();
         return $container->getParameterBag()->resolveValue($class);
     }, array_keys($container->findTaggedServiceIds('console.command')));
     /** @var BundleInterface $bundle */
     foreach ($this->bundles as $bundle) {
         if (!is_dir($dir = $bundle->getPath() . '/Command')) {
             continue;
         }
         $finder = new Finder();
         $finder->files()->name('*Command.php')->in($dir);
         $prefix = $bundle->getNamespace() . '\\Command';
         /** @var SplFileInfo $file */
         foreach ($finder as $file) {
             $ns = $prefix;
             if ($relativePath = $file->getRelativePath()) {
                 $ns .= '\\' . strtr($relativePath, '/', '\\');
             }
             $class = $ns . '\\' . $file->getBasename('.php');
             // This command is already in the container.
             if (in_array($class, $classes)) {
                 continue;
             }
             $r = new \ReflectionClass($class);
             if ($r->isSubclassOf(self::COMMAND_CLASS) && !$r->isAbstract() && !$r->getConstructor()->getNumberOfRequiredParameters()) {
                 $name = Container::underscore(preg_replace('/Command/', '', $r->getShortName()));
                 $name = strtolower(str_replace('\\', '_', $name));
                 if (!$bundle->getContainerExtension()) {
                     $alias = preg_replace('/Bundle$/', '', $bundle->getName());
                     $alias = Container::underscore($alias);
                 } else {
                     $alias = $bundle->getContainerExtension()->getAlias();
                 }
                 $id = $alias . '.command.' . $name;
                 if ($container->hasDefinition($id)) {
                     $id = sprintf('%s_%d', hash('sha256', $file), ++$count);
                 }
                 $definition = $container->register($id, $r->getName());
                 $definition->addTag('console.command', ['application' => $defaultApplicationId]);
                 if ($r->isSubclassOf('Symfony\\Component\\DependencyInjection\\ContainerAwareInterface')) {
                     $definition->addMethodCall('setContainer', [new Reference('service_container')]);
                 }
             }
         }
     }
 }
Example #6
0
 /**
  * Get possible actions from Controller class.
  * Note! Code accelerator (eaccelerator, apc, xcache, etc ) should be disabled to get comment line.
  * Method returns only public methods that ends with "Action" 
  * @param string $controllerName
  * @return array like array(
  * 		array(
  * 			'name' => action name without "Action" postfix
  * 			'comment'=> doc comment
  * 		)
  * )
  */
 public static function getPossibleActions($controllerName)
 {
     $manager = new Backend_Modules_Manager();
     $appCfg = Registry::get('main', 'config');
     $designerConfig = Config::factory(Config::File_Array, $appCfg->get('configs') . 'designer.php');
     $templates = $designerConfig->get('templates');
     $reflector = new ReflectionClass($controllerName);
     if (!$reflector->isSubclassOf('Backend_Controller') && !$reflector->isSubclassOf('Frontend_Controller')) {
         return array();
     }
     $actions = array();
     $methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
     $url = array();
     if ($reflector->isSubclassOf('Backend_Controller')) {
         $url[] = $templates['adminpath'];
         $url[] = $manager->getModuleName($controllerName);
     } elseif ($reflector->isSubclassOf('Frontend_Controller')) {
         if ($appCfg['frontend_router_type'] == 'module') {
             $module = self::_moduleByClass($controllerName);
             if ($module !== false) {
                 $urlcode = Model::factory('Page')->getCodeByModule($module);
                 if ($urlcode !== false) {
                     $url[] = $urlcode;
                 }
             }
         } elseif ($appCfg['frontend_router_type'] == 'path') {
             $paths = explode('_', str_replace(array('Frontend_'), '', $controllerName));
             $pathsCount = count($paths) - 1;
             if ($paths[$pathsCount] === 'Controller') {
                 $paths = array_slice($paths, 0, $pathsCount);
             }
             $url = array_merge($url, $paths);
         } elseif ($appCfg['frontend_router_type'] == 'config') {
             $urlCode = self::_moduleByClass($controllerName);
             if ($urlCode !== false) {
                 $url[] = $urlCode;
             }
         }
     }
     if (!empty($methods)) {
         Request::setDelimiter($templates['urldelimiter']);
         Request::setRoot($templates['wwwroot']);
         foreach ($methods as $method) {
             if (substr($method->name, -6) !== 'Action') {
                 continue;
             }
             $actionName = substr($method->name, 0, -6);
             $paths = $url;
             $paths[] = $actionName;
             $actions[] = array('name' => $actionName, 'code' => $method->name, 'url' => Request::url($paths, false), 'comment' => self::_clearDocSymbols($method->getDocComment()));
         }
         Request::setDelimiter($appCfg['urlDelimiter']);
         Request::setRoot($appCfg['wwwroot']);
     }
     return $actions;
 }
Example #7
0
 /**
  * @param BootloadManager $bootloader
  */
 public function perform(BootloadManager $bootloader)
 {
     $grid = $this->tableHelper(['Class:', 'Module:', 'Booted:', 'Location:']);
     foreach ($bootloader->getClasses() as $class) {
         $reflection = new \ReflectionClass($class);
         $booted = $reflection->getConstant('BOOT') || !$reflection->isSubclassOf(Bootloader::class);
         $grid->addRow([$reflection->getName(), $reflection->isSubclassOf(ModuleInterface::class) ? '<info>yes</info>' : 'no', $booted ? 'yes' : '<info>no</info>', $reflection->getFileName()]);
     }
     $grid->render();
 }
 /**
  * Creates a new service reflector
  *
  * @param $className string The FQCN of the service class to reflect
  * @throws \Exception If the passed class name isn't a subclass of PartKeepr\Service\Service
  */
 public function __construct($className)
 {
     $this->reflClass = new \ReflectionClass($className);
     if (!$this->reflClass->isSubclassOf("PartKeepr\\Service\\Service")) {
         throw new \Exception(sprintf("%s isn't a subclass of PartKeepr\\Service\\Service, can't reflect", $className));
     }
     $this->className = $className;
     $this->reader = new \Doctrine\Common\Annotations\AnnotationReader();
     $this->registerAnnotationLoaders();
 }
 /**
  * @inheritdoc
  */
 public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
 {
     if (class_exists($requestedName)) {
         $reflect = new \ReflectionClass($requestedName);
         if ($reflect->isSubclassOf(AbstractForm::class) || $reflect->isSubclassOf(AbstractFieldset::class)) {
             return true;
         }
     }
     return false;
 }
 public static function getContent(sfGeneratorManager $generatorManager, $class, $parameters)
 {
     $data = '';
     // needed to maintain BC with the 1.0 admin generator
     $r = new ReflectionClass($class);
     if (class_exists('sfPropelAdminGenerator') && ('sfPropelAdminGenerator' == $class || $r->isSubclassOf(new ReflectionClass('sfPropelAdminGenerator'))) || class_exists('sfDoctrineAdminGenerator') && ('sfDoctrineAdminGenerator' == $class || $r->isSubclassOf(new ReflectionClass('sfDoctrineAdminGenerator')))) {
         $data .= "require sfConfig::get('sf_symfony_lib_dir').'/plugins/sfCompat10Plugin/config/config.php';\n";
     }
     $data .= $generatorManager->generate($class, $parameters);
     return $data;
 }
Example #11
0
 /**
  * Associate model and generate set of model related methods.
  *
  * @param string $name
  * @param string $class
  */
 public function associateModel($name, $class)
 {
     $this->file->addUse($class);
     $this->file->addUse(ValidatesInterface::class);
     $reflection = new \ReflectionClass($class);
     $shortClass = $reflection->getShortName();
     $selection = "{$shortClass}[]";
     if ($reflection->isSubclassOf(Record::class)) {
         $this->file->addUse(Selector::class);
         $selection .= "|Selector";
     } elseif ($reflection->isSubclassOf(Document::class)) {
         $this->file->addUse(Collection::class);
         $selection .= "|Collection";
     }
     /**
      * Create new entity method.
      */
     $create = $this->class->method('create');
     $create->setComment(["Create new {$shortClass}. You must save entity using save method..", "", "@param array|\\Traversable \$fields Initial set of fields.", "@return {$shortClass}"]);
     $create->parameter('fields')->setOptional(true, []);
     $create->setSource(["return {$shortClass}::create(\$fields);"]);
     /**
      * Save entity method.
      */
     $save = $this->class->method('save');
     $save->setComment(["Save {$shortClass} instance.", "", "@param {$shortClass} \${$name}", "@param bool  \$validate", "@param array \$errors Will be populated if save fails.", "@return bool"]);
     $save->parameter($name)->setType($shortClass);
     $save->parameter("validate")->setOptional(true, true);
     $save->parameter("errors")->setOptional(true, null)->setPBR(true);
     $save->setSource(["if (\${$name}->save(\$validate)) {", "    return true;", "}", "", "\$errors = \${$name}->getErrors();", "", "return false;"]);
     /**
      * Delete entity method.
      */
     $delete = $this->class->method('delete');
     $delete->setComment(["Delete {$shortClass}.", "", "@param {$shortClass} \${$name}", "@return bool"]);
     $delete->parameter($name)->setType($shortClass);
     $delete->setSource("return \${$name}->delete();");
     /**
      * Find entity by it's primary key.
      */
     $findPrimary = $this->class->method('findByPK');
     $findPrimary->setComment(["Find {$shortClass} it's primary key.", "", "@param mixed \$primaryKey", "@return {$shortClass}|null"]);
     $findPrimary->parameter("primaryKey");
     $findPrimary->setSource("return {$shortClass}::findByPK(\$primaryKey);");
     /**
      * Find entity using where conditions.
      */
     $find = $this->class->method('find');
     $find->setComment(["Find {$shortClass} using set of where conditions.", "", "@param array \$where", "@return {$selection}"]);
     $find->parameter("where")->setType('array')->setOptional(true, []);
     $find->setSource("return {$shortClass}::find(\$where);");
 }
 /**
  * @group unit
  */
 public function testInheritance()
 {
     $className = $this->_getExceptionClass();
     $reflection = new \ReflectionClass($className);
     $this->assertTrue($reflection->isSubclassOf('Exception'));
     $this->assertTrue($reflection->implementsInterface('Elastica\\Exception\\ExceptionInterface'));
 }
 private function checkComponentClass($componentClassName)
 {
     $reflectionClass = new ReflectionClass($componentClassName);
     if (!$reflectionClass->isSubclassOf('BASE_CLASS_Widget')) {
         throw new LogicException('Component is not configurable');
     }
 }
 public function evaluate($configFiles)
 {
     $routeDefinitions = $this->parse($configFiles);
     $routes = array();
     $limit = count($this->routes) > 0;
     foreach ($routeDefinitions as $name => $route) {
         // we only load routes defined in the app.yml from
         if ($limit && !in_array($this->getOriginalName($name), $this->routes)) {
             continue;
         }
         $r = new ReflectionClass($route[0]);
         if ($r->isSubclassOf('sfRouteCollection')) {
             $route[1][0]['requirements']['sw_app'] = $this->app;
             $route[1][0]['requirements']['sw_host'] = $this->host;
             $collection_route = $r->newInstanceArgs($route[1]);
             foreach ($collection_route->getRoutes() as $name => $route) {
                 $routes[$this->app . '.' . $name] = new swEncapsulateRoute($route, $this->host, $this->app);
             }
         } else {
             $route[1][2]['sw_app'] = $this->app;
             $route[1][2]['sw_host'] = $this->host;
             $routes[$name] = new swEncapsulateRoute($r->newInstanceArgs($route[1]), $this->host, $this->app);
         }
     }
     return $routes;
 }
 /**
  * {@inheritdoc}
  */
 public function process(ContainerBuilder $container)
 {
     $translationTargets = $container->getParameter('sonata_translation.targets');
     $adminExtensionReferences = $this->getAdminExtensionReferenceByTypes(array_keys($translationTargets));
     foreach ($container->findTaggedServiceIds('sonata.admin') as $id => $attributes) {
         $admin = $container->getDefinition($id);
         $modelClass = $container->getParameterBag()->resolveValue($admin->getArgument(1));
         if (!class_exists($modelClass)) {
             continue;
         }
         $modelClassReflection = new \ReflectionClass($modelClass);
         foreach ($adminExtensionReferences as $type => $reference) {
             foreach ($translationTargets[$type]['implements'] as $interface) {
                 if ($modelClassReflection->implementsInterface($interface)) {
                     $admin->addMethodCall('addExtension', array($reference));
                 }
             }
             foreach ($translationTargets[$type]['instanceof'] as $class) {
                 if ($modelClassReflection->getName() == $class || $modelClassReflection->isSubclassOf($class)) {
                     $admin->addMethodCall('addExtension', array($reference));
                 }
             }
         }
     }
 }
Example #16
0
 public static function register($class)
 {
     if (static::registered($class)) {
         throw new \InvalidArgumentException('Override already loaded');
     }
     $reflection = new \ReflectionClass($class);
     if (!$reflection->isSubclassOf('\\Skeetr\\Runtime\\Override')) {
         throw new \InvalidArgumentException(sprintf('%s not implements OverrideInterface', $class));
     }
     $functions = array();
     foreach ($reflection->getMethods(\ReflectionMethod::IS_FINAL) as $method) {
         $function = $method->getName();
         if (!function_exists($function)) {
             continue;
         }
         $call = static::getCall($class, $function);
         skeetr_override_function($call['function'], $call['args'], $call['code']);
         $functions[$function] = 1;
     }
     if (count($functions) == 0) {
         throw new \InvalidArgumentException(sprintf('The class "%s" not contains any override function', $class));
     }
     $class::reset();
     static::$functions = array_merge(static::$functions, $functions);
     static::$registered[$class] = 1;
 }
Example #17
0
 /**
  * @param ReflectionClass $filter
  * @param mixed           $args
  */
 public function addFilter(ReflectionClass $filter, $args)
 {
     if (!$filter->isSubclassOf('RecursiveFilterIterator')) {
         throw new InvalidArgumentException(sprintf('Class "%s" does not extend RecursiveFilterIterator', $filter->name));
     }
     $this->filters[] = array($filter, $args);
 }
Example #18
0
 /**
  * @param string $parentName
  * @param string $childName
  */
 protected final function assertExtends($parentName, $childName)
 {
     $this->assertTrue(class_exists($parentName) || interface_exists($parentName), sprintf('Failed to assert that class or interface "%s" exists', $parentName));
     $this->assertTrue(class_exists($childName) || interface_exists($childName), sprintf('Failed to assert that class or interface "%s" exists', $childName));
     $reflection = new \ReflectionClass($childName);
     $this->assertTrue($reflection->isSubclassOf($parentName), sprintf('Failed to assert that "%s" extends "%s"', $childName, $parentName));
 }
Example #19
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 #20
0
 /**
  * 加载模块子类
  * 备注:这里不直接用 __get() 实例化模块内子类是因为方便加载多个实例化对象,方便子类不同对象复用(如多个profile)
  * 这里用 protected 关键字是为了防止外部模块调用:如 $ctx->模块->loadC(),这样外部模块只能调用模块的mod声明的方法
  * 所有的模块子类只能让mod模块文件去进行调用
  */
 protected function loadC()
 {
     $args = func_get_args();
     $class = array_shift($args);
     echo '--初始化子对象' . $class . '(可以多次)--' . BRR;
     //@todo
     // print_r($args);exit;
     if (!empty($this->modName)) {
         require_once CODE_BASE . '/app/model/' . $this->modName . '/' . $class . '.php';
         $className = ucfirst($this->modName . $class . 'Model');
         $reflectClass = new ReflectionClass($className);
         $obj = $reflectClass->newInstanceArgs($args);
         if ($reflectClass->isSubclassOf('CtxModel')) {
             $obj->ctx = $this->ctx;
             $obj->setModName($this->modName);
             $obj->init();
         }
         // else {
         //     echo '--' . get_class($this) . '非子类CtxModel--' . BRR;
         // }
         return $obj;
         // $this->controllerReflection = new ReflectionClass($controller);
         // $this->controllerReflection->isAbstract() //不能为抽象类
         // $this->controllerReflection->isInterface()    //不能为接口
         // !$this->controllerReflection->isSubclassOf('CController') 必须为子控制器
         // $this->controllerReflection->hasMethod('action名')    action必须存在
         // $this->controllerReflection->getMethod('action名')->isPublic() action必须为public
     }
 }
 /**
  * @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);
     }
 }
 /**
  * Check return types of getExtensionAttributes() methods.
  */
 public function testGetSetExtensionAttributes()
 {
     $invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this);
     $invoker(function ($filename) {
         $errors = [];
         $fileContent = file_get_contents($filename);
         $extendsFromExtensibleDataInterface = preg_match('/' . str_replace('\\', '\\\\', self::EXTENSIBLE_DATA_INTERFACE) . '/', $fileContent);
         if ($extendsFromExtensibleDataInterface && preg_match('/namespace ([\\w\\\\]+).*interface ([\\w\\\\]+)/s', $fileContent, $matches)) {
             $namespace = $matches[1];
             $interfaceName = $matches[2];
             $fullInterfaceName = '\\' . $namespace . '\\' . $interfaceName;
             $interfaceReflection = new \ReflectionClass($fullInterfaceName);
             if ($interfaceReflection->isSubclassOf(self::EXTENSIBLE_DATA_INTERFACE)) {
                 $interfaceName = '\\' . $interfaceReflection->getName();
                 $extensionClassName = substr($interfaceName, 0, -strlen('Interface')) . 'Extension';
                 $extensionInterfaceName = $extensionClassName . 'Interface';
                 /** Check getExtensionAttributes method */
                 $errors = $this->checkGetExtensionAttributes($interfaceReflection, $extensionInterfaceName, $fullInterfaceName);
                 /** Check setExtensionAttributes method */
                 $errors = array_merge($errors, $this->checkSetExtensionAttributes($interfaceReflection, $extensionInterfaceName, $fullInterfaceName));
             }
         }
         $this->assertEmpty($errors, "Error validating {$filename}\n" . print_r($errors, true));
     }, $this->getInterfacesFiles());
 }
Example #23
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));
         }
     }
 }
 /**
  * @param scalar[] $data_
  * @param string $type_
  *
  * @return mixed
  */
 public function hydrateForType($type_, array $data_)
 {
     $object = new $type_();
     if ($object instanceof Object_Mappable) {
         $properties = $object->properties();
     } else {
         $properties = Object_Properties::forType($type_);
     }
     foreach ($properties->propertyNames() as $propertyName) {
         /* @var $property \Components\Object_Property */
         $property = $properties->{$propertyName};
         if (false === isset($data_[$property->nameMapped])) {
             continue;
         }
         $t = $property->type;
         if (Primitive::isNative($t)) {
             $object->{$property} = $data_[$property->nameMapped];
         } else {
             $o = new \ReflectionClass($t);
             if ($o->isSubclassOf('Components\\Value')) {
                 $object->{$property} = $t::valueOf($data_[$property->nameMapped]);
             }
         }
     }
     // TODO Recursive mapping ...
     return $object;
 }
Example #25
0
 /**
  * @param $pathInfo
  * @return bool|string
  */
 private function handlePathInfo($pathInfo)
 {
     @(list($id, $route) = explode('/', $pathInfo, 2));
     if (Yii::$app->hasModule($id) == false) {
         return false;
     }
     $module = Yii::$app->getModule($id);
     $controllerSuffix = Settings::getInstance()->isAdmin() ? AbstractModule::ADMIN_CONTROLLER_SUFFIX : AbstractModule::CONTROLLER_SUFFIX;
     $className = str_replace(' ', '', ucwords(str_replace('-', ' ', $id)) . $controllerSuffix);
     $className = ltrim($module->controllerNamespace . '\\' . $className, '\\');
     if (strpos($className, '-') !== false || !class_exists($className)) {
         return false;
     }
     if (isset($route)) {
         $routePaths = explode('/', $route, 2);
     } else {
         $routePaths = explode('/', $module->defaultRoute, 2);
     }
     $action = $routePaths[0];
     $reflectionClass = new \ReflectionClass($className);
     if ($reflectionClass->isSubclassOf('yii\\base\\Controller') && $reflectionClass->hasMethod('action' . $action)) {
         return sprintf('%s/%s', $id, $pathInfo);
     }
     return false;
 }
Example #26
0
 public function load()
 {
     $queries = $this->path . '/queries.php';
     $script = $this->path . '/script.php';
     if (file_exists($queries)) {
         $sql = null;
         include $queries;
         if (is_array($sql)) {
             $this->queries = $sql;
         }
     }
     if (file_exists($script)) {
         include_once $script;
         $suffix = str_replace('-', '_', baseName($this->path));
         $class = 'Nano_Migrate_Script_' . $suffix;
         if (class_exists($class, false)) {
             $reflection = new ReflectionClass($class);
             if ($reflection->isInstantiable() && $reflection->isSubclassOf('Nano_Migrate_Script')) {
                 $this->script = $reflection->newInstance();
             } else {
                 $this->script = Nano_Migrate_ScriptEmpty::instance();
             }
         } else {
             $this->script = Nano_Migrate_ScriptEmpty::instance();
         }
     } else {
         $this->script = Nano_Migrate_ScriptEmpty::instance();
     }
 }
Example #27
0
 private final function LoadModule($classname)
 {
     if (!$this->modules) {
         $this->SessionDestroy();
         $this->Login('ERROR: No modules defined.');
         exit;
     }
     $classes = explode(' ', $this->modules);
     if (!in_array($classname, $classes)) {
         exit('ERROR: LoadModule found unknown Class/Module');
     }
     $classfile = PANEL_BASE_PATH . '/server/modules/comp/' . $classname . '.class.php';
     if (is_file($classfile)) {
         require_once $classfile;
     }
     if (!class_exists($classname, false)) {
         exit('ERROR: ' . $classname . ' is not defined as a Class');
     }
     $class = new ReflectionClass($classname);
     if (!$class->isSubclassOf('PanelCommon')) {
         exit("ERROR: {$classname} must extends PanelCommon");
     }
     if (!$class->isUserDefined()) {
         exit("ERROR: {$classname} must be user defined and not internal to PHP");
     }
     if (!$class->IsInstantiable()) {
         exit("ERROR: {$classname} must be instantiable and not an Interface or Abstract class");
     }
     if (!$class->hasMethod('home')) {
         exit("ERROR: {$classname} lacks required method/function home()");
     }
     if (!$class->hasProperty('menu')) {
         exit("ERROR: {$classname} lacks \$menu as a class property");
     }
 }
 public function __construct($directory, $extension, $namespace = NULL)
 {
     $this->extension = $extension;
     $this->directory = $directory;
     $this->namespace = empty($namespace) ? '' : $namespace;
     if (($systemCache = $this->extension->getApp()->getCacheRepository('system')) != NULL && is_array($controllerClassFiles = $systemCache->get($this->directory . '::fileList'))) {
     } else {
         // Make sure all PHP files in the directory are included
         $controllerClassFiles = DirectoryHelper::directoryToArray($this->directory, TRUE, '.php');
         if ($systemCache != NULL) {
             $systemCache->forever($this->directory . '::fileList', $controllerClassFiles);
         }
     }
     foreach ($controllerClassFiles as $controllerClassFile) {
         include_once $controllerClassFile;
         $controllerClass = ReflectionHelper::createClassName($this->namespace, basename($controllerClassFile, '.php'));
         $this->controllerClasses[] = $controllerClass;
         $controller = new $controllerClass($this->extension);
         $rclass = new \ReflectionClass($controller);
         if ($rclass->isSubclassOf('\\MABI\\ModelController')) {
             /**
              * @var $controller \MABI\ModelController
              */
             $this->overriddenModelClasses[] = $controller->getModelClass();
         }
         $this->controllers[] = $controller;
     }
 }
 /**
  * Determine if we can create a service with name
  *
  * @param ServiceLocatorInterface $serviceLocator
  * @param $name
  * @param $requestedName
  *
  * @return bool
  * @throws \Zend\ServiceManager\Exception\ServiceNotFoundException
  */
 public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
 {
     if (array_key_exists($requestedName, $this->lookupCache)) {
         return $this->lookupCache[$requestedName];
     }
     if (!$serviceLocator->has('Config')) {
         // @codeCoverageIgnoreStart
         return false;
     }
     // @codeCoverageIgnoreEnd
     // Validate object is set
     $config = $serviceLocator->get('Config');
     if (!isset($config['zf-apigility']['doctrine-connected']) || !is_array($config['zf-apigility']['doctrine-connected']) || !isset($config['zf-apigility']['doctrine-connected'][$requestedName])) {
         $this->lookupCache[$requestedName] = false;
         return false;
     }
     // Validate if class a valid DoctrineResource
     $className = isset($config['class']) ? $config['class'] : $requestedName;
     $className = $this->normalizeClassname($className);
     $reflection = new \ReflectionClass($className);
     if (!$reflection->isSubclassOf('\\ZF\\Apigility\\Doctrine\\Server\\Resource\\DoctrineResource')) {
         // @codeCoverageIgnoreStart
         throw new ServiceNotFoundException(sprintf('%s requires that a valid DoctrineResource "class" is specified for listener %s; no service found', __METHOD__, $requestedName));
     }
     // @codeCoverageIgnoreEnd
     // Validate object manager
     $config = $config['zf-apigility']['doctrine-connected'];
     if (!isset($config[$requestedName]) || !isset($config[$requestedName]['object_manager'])) {
         // @codeCoverageIgnoreStart
         throw new ServiceNotFoundException(sprintf('%s requires that a valid "object_manager" is specified for listener %s; no service found', __METHOD__, $requestedName));
     }
     // @codeCoverageIgnoreEnd
     $this->lookupCache[$requestedName] = true;
     return true;
 }
Example #30
0
 public function plug($name, $class, $config = [])
 {
     $ref = new \ReflectionClass($class);
     // add to plugins
     $this->_plugins[$name] = ['name' => $name, 'class' => $ref->name, 'type' => $ref->isSubclassOf('bolt\\plugin\\singleton') ? 'singleton' : 'factory', 'ref' => $ref, 'config' => $config, 'instance' => false];
     return $this;
 }