Пример #1
1
 /**
  * Override startup of the Shell
  *
  * @return void
  */
 public function startup()
 {
     parent::startup();
     if (isset($this->params['connection'])) {
         $this->connection = $this->params['connection'];
     }
     $class = Configure::read('Acl.classname');
     list($plugin, $class) = pluginSplit($class, true);
     App::uses($class, $plugin . 'Controller/Component/Acl');
     if (!in_array($class, array('DbAcl', 'DB_ACL')) && !is_subclass_of($class, 'DbAcl')) {
         $out = "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Error: Your current Cake configuration is set to an ACL implementation other than DB.') . "\n";
         $out .= __d('cake_console', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n";
         $out .= "--------------------------------------------------\n";
         $out .= __d('cake_console', 'Current ACL Classname: %s', $class) . "\n";
         $out .= "--------------------------------------------------\n";
         $this->err($out);
         $this->_stop();
     }
     if ($this->command) {
         if (!config('database')) {
             $this->out(__d('cake_console', 'Your database configuration was not found. Take a moment to create one.'), true);
             $this->args = null;
             return $this->DbConfig->execute();
         }
         require_once APP . 'Config' . DS . 'database.php';
         if (!in_array($this->command, array('initdb'))) {
             $collection = new ComponentCollection();
             $this->Acl = new AclComponent($collection);
             $controller = new Controller();
             $this->Acl->startup($controller);
         }
     }
 }
Пример #2
1
 /**
  * The handler which sets all the values in the dynamic definition.
  *
  * @param String $class the Controller class name
  * @param LaravelSwagger $LS the LaravelSwagger instance.
  * @throws DynamicHandlerException
  */
 public function handle($class, LaravelSwagger $LS)
 {
     /**
      *************************************
      *         Default Behaviour         *
      *************************************
      *
      * Loops through all of the linked keys
      */
     foreach ($this->method->keys() as $key) {
         /** @var mixed $value the value associated with the specific key */
         $value = ValueContainer::getValue($class, $key);
         if (is_string($value)) {
             //if its a string of a class
             //if it is a model that has been registered.
             if (is_subclass_of($value, Model::class) && $LS->hasModel($value)) {
                 $value = "#/definitions/{$value}";
             }
         }
         //if there is no value then throw an exception
         if (is_null($value)) {
             throw new DynamicHandlerException("{$key} value is NULL");
         }
         $this->method->set($key, $value);
     }
 }
Пример #3
0
 /**
  * This creates a new MDB2Store instance.  It requires an
  * established database connection be given to it, and it allows
  * overriding the default table names.
  *
  * @param connection $connection This must be an established
  * connection to a database of the correct type for the SQLStore
  * subclass you're using.  This must be a PEAR::MDB2 connection
  * handle.
  *
  * @param associations_table: This is an optional parameter to
  * specify the name of the table used for storing associations.
  * The default value is 'oid_associations'.
  *
  * @param nonces_table: This is an optional parameter to specify
  * the name of the table used for storing nonces.  The default
  * value is 'oid_nonces'.
  */
 function Auth_OpenID_MDB2Store($connection, $associations_table = null, $nonces_table = null)
 {
     $this->associations_table_name = "oid_associations";
     $this->nonces_table_name = "oid_nonces";
     // Check the connection object type to be sure it's a PEAR
     // database connection.
     if (!is_object($connection) || !is_subclass_of($connection, 'mdb2_driver_common')) {
         trigger_error("Auth_OpenID_MDB2Store expected PEAR connection " . "object (got " . get_class($connection) . ")", E_USER_ERROR);
         return;
     }
     $this->connection = $connection;
     // Be sure to set the fetch mode so the results are keyed on
     // column name instead of column index.
     $this->connection->setFetchMode(MDB2_FETCHMODE_ASSOC);
     if (@PEAR::isError($this->connection->loadModule('Extended'))) {
         trigger_error("Unable to load MDB2_Extended module", E_USER_ERROR);
         return;
     }
     if ($associations_table) {
         $this->associations_table_name = $associations_table;
     }
     if ($nonces_table) {
         $this->nonces_table_name = $nonces_table;
     }
     $this->max_nonce_age = 6 * 60 * 60;
 }
Пример #4
0
 /**
  * Append any supported $content to $parent
  *
  * @param  DOMNode $parent  Node to append to
  * @param  mixed   $content Content to append
  * @return self
  */
 protected function XMLAppend(\DOMNode &$parent = null, $content = null)
 {
     if (is_null($parent)) {
         $parent = $this->root;
     }
     if (is_string($content) or is_numeric($content) or is_object($content) and method_exists($content, '__toString')) {
         $parent->appendChild($this->createTextNode("{$content}"));
     } elseif (is_object($content) and is_subclass_of($content, '\\DOMNode')) {
         $parent->appendChild($content);
     } elseif (is_array($content) or is_object($content) and $content = get_object_vars($content)) {
         array_map(function ($node, $value) use(&$parent) {
             if (is_string($node)) {
                 if (substr($node, 0, 1) === '@') {
                     $parent->setAttribute(substr($node, 1), $value);
                 } else {
                     $node = $parent->appendChild($this->createElement($node));
                     if (is_string($value)) {
                         $this->XMLAppend($node, $this->createTextNode($value));
                     } else {
                         $this->XMLAppend($node, $value);
                     }
                 }
             } else {
                 $this->XMLAppend($parent, $value);
             }
         }, array_keys($content), array_values($content));
     } elseif (is_bool($content)) {
         $parent->appendChild($this->createTextNode($content ? 'true' : 'false'));
     } else {
         throw new \InvalidArgumentException(sprintf('Unable to append unknown content [%s] to %s', get_class($content), get_class($this)));
     }
     return $this;
 }
 /**
  * Constructor - checks that the registry object has been passed correctly.
  *
  * @param	vB_Registry	Instance of the vBulletin data registry object - expected to have the database object as one of its $this->db member.
  * @param	integer		One of the ERRTYPE_x constants
  */
 function vB_DataManager_ThreadPost(&$registry, $errtype = ERRTYPE_STANDARD)
 {
     if (!is_subclass_of($this, 'vB_DataManager_ThreadPost')) {
         trigger_error("Direct Instantiation of vB_DataManager_ThreadPost class prohibited.", E_USER_ERROR);
     }
     parent::vB_DataManager($registry, $errtype);
 }
Пример #6
0
 public function logQuery(Nette\Database\Connection $connection, $result)
 {
     if ($this->disabled) {
         return;
     }
     $this->count++;
     $source = NULL;
     $trace = $result instanceof \PDOException ? $result->getTrace() : debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
     foreach ($trace as $row) {
         if (isset($row['file']) && is_file($row['file']) && !Tracy\Debugger::getBluescreen()->isCollapsed($row['file'])) {
             if (isset($row['function']) && strpos($row['function'], 'call_user_func') === 0 || isset($row['class']) && is_subclass_of($row['class'], '\\Nette\\Database\\Connection')) {
                 continue;
             }
             $source = [$row['file'], (int) $row['line']];
             break;
         }
     }
     if ($result instanceof Nette\Database\ResultSet) {
         $this->totalTime += $result->getTime();
         if ($this->count < $this->maxQueries) {
             $this->queries[] = [$connection, $result->getQueryString(), $result->getParameters(), $source, $result->getTime(), $result->getRowCount(), NULL];
         }
     } elseif ($result instanceof \PDOException && $this->count < $this->maxQueries) {
         $this->queries[] = [$connection, $result->queryString, NULL, $source, NULL, NULL, $result->getMessage()];
     }
 }
Пример #7
0
 /**
  * Registers widget.
  *
  * @param string $class
  * @throws \yii\base\InvalidParamException
  */
 public function registerWidget($class)
 {
     if (!is_subclass_of($class, $this->widgetBaseClass)) {
         throw new InvalidParamException("Class {$class} must extend {$this->widgetBaseClass}");
     }
     $this->_widgets[] = $class;
 }
Пример #8
0
 /**
  * Set table definition for Blameable behavior
  *
  * @return void
  */
 public function setTableDefinition()
 {
     if (!$this->_options['columns']['created']['disabled']) {
         $name = $this->_options['columns']['created']['name'];
         if ($this->_options['columns']['created']['alias']) {
             $name .= ' as ' . $this->_options['columns']['created']['alias'];
         }
         $this->hasColumn($name, $this->_options['columns']['created']['type'], $this->_options['columns']['created']['length'], $this->_options['columns']['created']['options']);
     }
     if (!$this->_options['columns']['updated']['disabled']) {
         $name = $this->_options['columns']['updated']['name'];
         if ($this->_options['columns']['updated']['alias']) {
             $name .= ' as ' . $this->_options['columns']['updated']['alias'];
         }
         if ($this->_options['columns']['updated']['onInsert'] !== true && $this->_options['columns']['updated']['options']['notnull'] === true) {
             $this->_options['columns']['updated']['options']['notnull'] = false;
         }
         $this->hasColumn($name, $this->_options['columns']['updated']['type'], $this->_options['columns']['updated']['length'], $this->_options['columns']['updated']['options']);
     }
     $listener = new $this->_options['listener']($this->_options);
     if (get_class($listener) !== 'Doctrine_Template_Listener_DmBlameable' && !is_subclass_of($listener, 'Doctrine_Template_Listener_DmBlameable')) {
         throw new Exception('Invalid listener. Must be Doctrine_Template_Listener_DmBlameable or subclass');
     }
     $this->addListener($listener, 'Blameable');
 }
 /**
  * {@inheritdoc}
  */
 protected function createWithConfig(ContainerInterface $container, $configKey)
 {
     $config = $this->retrieveConfig($container, $configKey, 'driver');
     if (!array_key_exists('class', $config)) {
         throw new OutOfBoundsException('Missing "class" config key');
     }
     if (!is_array($config['paths'])) {
         $config['paths'] = [$config['paths']];
     }
     if (AnnotationDriver::class === $config['class'] || is_subclass_of($config['class'], AnnotationDriver::class)) {
         $this->registerAnnotationLoader();
         $driver = new $config['class'](new CachedReader(new AnnotationReader(), $this->retrieveDependency($container, $config['cache'], 'cache', CacheFactory::class)), $config['paths']);
     } else {
         $driver = new $config['class']($config['paths']);
     }
     if (null !== $config['extension'] && $driver instanceof FileDriver) {
         $locator = $driver->getLocator();
         if (get_class($locator) !== DefaultFileLocator::class) {
             throw new Exception\DomainException(sprintf('File locator must be a concrete instance of %s, got %s', DefaultFileLocator::class, get_class($locator)));
         }
         $driver->setLocator(new DefaultFileLocator($locator->getPaths(), $config['extension']));
     }
     if ($driver instanceof MappingDriverChain) {
         foreach ($config['drivers'] as $namespace => $driverName) {
             if (null === $driverName) {
                 continue;
             }
             $driver->addDriver($this->createWithConfig($container, $driverName), $namespace);
         }
     }
     return $driver;
 }
Пример #10
0
 public function validateModel($attribute, $params)
 {
     if ($this->hasErrors('model')) {
         return;
     }
     $class = @Yii::import($this->model, true);
     if (!is_string($class) || !$this->classExists($class)) {
         $this->addError('model', "Class '{$this->model}' does not exist or has syntax error.");
     } else {
         if (!is_subclass_of($class, 'CActiveRecord')) {
             $this->addError('model', "'{$this->model}' must extend from CActiveRecord.");
         } else {
             $table = CActiveRecord::model($class)->tableSchema;
             if ($table->primaryKey === null) {
                 $this->addError('model', "Table '{$table->name}' does not have a primary key.");
             } else {
                 if (is_array($table->primaryKey)) {
                     $this->addError('model', "Table '{$table->name}' has a composite primary key which is not supported by crud generator.");
                 } else {
                     $this->_modelClass = $class;
                     $this->_table = $table;
                 }
             }
         }
     }
 }
Пример #11
0
 /**
  * 初始化分布式分发器
  * 根据分布式算法类型,获取分布式算法的处理器handler。然后根据配置文件,调用分布式算法处理器,做分布式处理的初始化工作
  *
  * @param array $clusterConfig 分布式集群的配置。你可以配置一个集群下的多个组,每个组都是由若干个主从对组成的
  *
  * @return Distributer|Modulo|DistriAbstract
  * @throws \Exception
  */
 public function init(array $clusterConfig = [])
 {
     $distriHandler = null;
     try {
         //根据分布式算法类型,初始化分布式算法处理器
         switch ($this->distriMode) {
             case DistriMode::DIS_CONSISTENT_HASHING:
                 $distriHandler = new ConsistentHashing();
                 break;
             case DistriMode::DIS_MODULO:
                 $distriHandler = new Modulo();
                 break;
         }
         //如果分布式算法处理器合法,则根据配置,做分布式算法处理的初始化工作
         if (is_object($distriHandler) && is_subclass_of($distriHandler, DistriAbstract::class)) {
             //初始化分布式算法处理器
             $distriHandler->init($clusterConfig);
             //将初始化后的分布式算法处理器,添加到当前分布式分发器的handler属性中
             $this->setDistriHandler($distriHandler);
         }
     } catch (\Exception $e) {
         throw $e;
     }
     return $this;
 }
Пример #12
0
 /**
  * Generates a default layout from the desktop layout if available, or from the model's
  * fields otherwise.
  * @param string $type 'form' or 'view'
  * @param string $modelName
  * @return array
  */
 public static function generateDefaultLayout($type, $modelName)
 {
     if ($type === 'form') {
         $layout = FormLayout::model()->findByAttributes(array('model' => ucfirst($modelName), 'defaultForm' => 1, 'scenario' => 'Default'));
     } else {
         $layout = FormLayout::model()->findByAttributes(array('model' => ucfirst($modelName), 'defaultView' => 1, 'scenario' => 'Default'));
     }
     $layoutData = array();
     if ($layout) {
         $layout = CJSON::decode($layout->layout);
         if (isset($layout['sections'])) {
             foreach ($layout['sections'] as $section) {
                 foreach ($section['rows'] as $row) {
                     foreach ($row['cols'] as $col) {
                         foreach ($col['items'] as $item) {
                             if (isset($item['name'])) {
                                 $fieldName = preg_replace('/^formItem_/u', '', $item['name']);
                                 $layoutData[] = $fieldName;
                             }
                         }
                     }
                 }
             }
         }
     } elseif (is_subclass_of($modelName, 'X2Model')) {
         $layoutData = Yii::app()->db->createCommand()->select('fieldName')->from('x2_fields')->where('modelName=:modelName', array(':modelName' => $modelName))->andWhere($type === 'view' ? 'readOnly' : 'true')->queryColumn();
     }
     return $layoutData;
 }
Пример #13
0
 /**
  * @param string $class
  *
  * @return $this|ProxyGuard
  */
 public function extends(string $class)
 {
     if (!is_subclass_of($this->value, $class)) {
         return new ProxyGuard(new ObjectException('%s did not extend %s', get_class($this->value), $class));
     }
     return $this;
 }
Пример #14
0
    /**
     * Add default menu for module
     * @param string $module
     */
    protected function addMenu($moduleName)
    {
        $menu = array();
        // Create default menu for the module
        $menu[] = array('route' => "#{$moduleName}/create", 'label' => 'LNK_NEW_RECORD', 'acl_action' => 'create', 'acl_module' => $moduleName, 'icon' => 'fa-plus');
        // Handle link to vCard
        $bean = BeanFactory::getBean($moduleName);
        if (is_subclass_of($bean, 'Person')) {
            $vCardRoute = in_array($moduleName, $GLOBALS['bwcModules']) ? '#bwc/index.php?' . http_build_query(array('module' => $moduleName, 'action' => 'ImportVCard')) : "#{$moduleName}/vcard-import";
            $menu[] = array('route' => $vCardRoute, 'label' => 'LNK_IMPORT_VCARD', 'acl_action' => 'create', 'acl_module' => $moduleName, 'icon' => 'fa-plus');
        }
        $menu[] = array('route' => "#{$moduleName}", 'label' => 'LNK_LIST', 'acl_action' => 'list', 'acl_module' => $moduleName, 'icon' => 'fa-bars');
        if ($bean instanceof SugarBean && $bean->importable) {
            $menu[] = array('route' => '#bwc/index.php?' . http_build_query(array('module' => 'Import', 'action' => 'Step1', 'import_module' => $moduleName)), 'label' => 'LNK_IMPORT_' . strtoupper($moduleName), 'acl_action' => 'import', 'acl_module' => $moduleName, 'icon' => 'fa-arrow-circle-o-up');
        }
        $content = <<<END
<?php
/* Created by SugarUpgrader for module {$moduleName} */
\$viewdefs['{$moduleName}']['base']['menu']['header'] =
END;
        $content .= var_export($menu, true) . ";\n";
        $this->ensureDir("modules/{$moduleName}/clients/base/menus/header");
        $this->putFile("modules/{$moduleName}/clients/base/menus/header/header.php", $content);
        $this->log("Added default menu file for {$moduleName}");
    }
Пример #15
0
 public function execute(App $app)
 {
     $argv = $app->argv;
     $script = $app->task_name;
     $script = explode('_', $script);
     $cls_file = ucfirst(strtolower(array_pop($script)));
     if (empty($cls_file)) {
         throw new Exception('task.err for run the task for :' . $this->task_name, 1033);
     }
     $path = '';
     $class = '';
     if (!empty($script)) {
         foreach ($script as $p) {
             $p = strtolower($p);
             $path .= $p . DOT;
             $class .= ucfirst($p);
         }
     }
     $class .= $cls_file;
     $path = TASK_PATH . $path;
     $file = $path . $cls_file . '.php';
     Pi::inc(PI_CORE . 'BaseTask.php');
     if (!Pi::inc($file)) {
         throw new Exception('task.err can not load the file :' . $file, 1034);
     }
     if (!class_exists($class)) {
         throw new Exception('task.err can not find the class :' . $class, 1035);
     }
     $cls = new $class();
     if (!is_subclass_of($cls, 'BaseTask')) {
         throw new Exception('task.err the class ' . $class . ' is not the subclass of BaseTask ', 1036);
     }
     $cls->execute($argv);
 }
 /** @inheritdoc */
 public function attach($owner)
 {
     if (!is_subclass_of($owner, BaseImagable::className())) {
         throw new Exception("The owner must be inherited from " . BaseImagable::className());
     }
     parent::attach($owner);
 }
Пример #17
0
 protected function handle($class)
 {
     if (is_subclass_of($class, 'Projects_Maker')) {
         $handler = new $class();
         $this->makers[$handler->name()] = $handler;
     }
 }
 function &get_dataset(&$counter, $params = array())
 {
     $counter = 0;
     $request = request::instance();
     if (!($version = $request->get_attribute('version'))) {
         return new empty_dataset();
     }
     if (!($node_id = $request->get_attribute('version_node_id'))) {
         return new empty_dataset();
     }
     $version = (int) $version;
     $node_id = (int) $node_id;
     if (!($site_object = wrap_with_site_object(fetch_one_by_node_id($node_id)))) {
         return new empty_dataset();
     }
     if (!is_subclass_of($site_object, 'content_object')) {
         return new empty_dataset();
     }
     if (($version_data = $site_object->fetch_version($version)) === false) {
         return new empty_dataset();
     }
     $result = array();
     foreach ($version_data as $attrib => $value) {
         $data['attribute'] = $attrib;
         $data['value'] = $value;
         $result[] = $data;
     }
     return new array_dataset($result);
 }
 /**
  * Migrate records of a single class
  *
  * @param string $class
  * @param null|string $stage
  */
 protected function upClass($class)
 {
     if (!class_exists($class)) {
         return;
     }
     if (is_subclass_of($class, 'SiteTree')) {
         $items = SiteTree::get()->filter('ClassName', $class);
     } else {
         $items = $class::get();
     }
     if ($count = $items->count()) {
         $this->message(sprintf('Migrating %s legacy %s records.', $count, $class));
         foreach ($items as $item) {
             $cancel = $item->extend('onBeforeUp');
             if ($cancel && min($cancel) === false) {
                 continue;
             }
             /**
              * @var MigratableObject $item
              */
             $result = $item->up();
             $this->message($result);
             $item->extend('onAfterUp');
         }
     }
 }
Пример #20
0
 /**
  * Gets the list of the properties for an subset of the classes
  *
  * @return  array Returns array of the ReflectionProperty
  */
 public function _getReflectionProperties()
 {
     if (is_null($this->reflectionProperties)) {
         $this->reflectionProperties = array();
         $f = false;
         $classes = array();
         foreach (array_reverse(class_parents($this)) as $class) {
             if (!$f && !($f = is_subclass_of($class, __CLASS__))) {
                 continue;
             }
             $classes[] = new \ReflectionClass($class);
         }
         $classes[] = new \ReflectionClass(get_class($this));
         foreach ($classes as $refl) {
             foreach ($refl->getProperties(\ReflectionProperty::IS_PRIVATE) as $refp) {
                 if (substr($refp->getName(), 0, 1) == '_') {
                     continue;
                 }
                 /* @var $refp \ReflectionProperty */
                 $refp->setAccessible(true);
                 $this->reflectionProperties[$refp->getName()] = $refp;
             }
         }
     }
     return $this->reflectionProperties;
 }
Пример #21
0
 /**
  * @internal
  *
  * @param Oxygen_Http_Request     $request
  * @param Oxygen_Util_RequestData $requestData
  * @param string                  $className
  * @param string                  $method
  * @param array                   $actionParameters
  *
  * @return Oxygen_Http_Response
  * @throws Oxygen_Exception
  */
 public function handleRaw($request, $requestData, $className, $method, array $actionParameters)
 {
     $reflectionMethod = new ReflectionMethod($className, $method);
     $parameters = $reflectionMethod->getParameters();
     $arguments = array();
     foreach ($parameters as $parameter) {
         if (isset($actionParameters[$parameter->getName()])) {
             $arguments[] = $actionParameters[$parameter->getName()];
         } else {
             if (!$parameter->isOptional()) {
                 throw new Oxygen_Exception(Oxygen_Exception::ACTION_ARGUMENT_NOT_PROVIDED);
             }
             $arguments[] = $parameter->getDefaultValue();
         }
     }
     if (is_subclass_of($className, 'Oxygen_Container_ServiceLocatorAware')) {
         $instance = call_user_func(array($className, 'createFromContainer'), $this->container);
     } else {
         $instance = new $className();
     }
     $result = call_user_func_array(array($instance, $method), $arguments);
     if (is_array($result)) {
         $result = $this->convertResultToResponse($request, $requestData, $result);
     } elseif (!$result instanceof Oxygen_Http_Response) {
         throw new LogicException(sprintf('An action should return array or an instance of Oxygen_Http_Response; %s gotten.', gettype($result)));
     }
     return $result;
 }
Пример #22
0
 public static function getSearchableAttributesAndLabels($viewClassName, $modelClassName)
 {
     assert('is_string($viewClassName)');
     assert('is_string($modelClassName) && is_subclass_of($modelClassName, "RedBeanModel")');
     $searchFormClassName = $viewClassName::getModelForMetadataClassName();
     $editableMetadata = $viewClassName::getMetadata();
     $designerRulesType = $viewClassName::getDesignerRulesType();
     $designerRulesClassName = $designerRulesType . 'DesignerRules';
     $designerRules = new $designerRulesClassName();
     $modelAttributesAdapter = DesignerModelToViewUtil::getModelAttributesAdapter($viewClassName, $modelClassName);
     $derivedAttributesAdapter = new DerivedAttributesAdapter($modelClassName);
     $attributeCollection = array_merge($modelAttributesAdapter->getAttributes(), $derivedAttributesAdapter->getAttributes());
     $attributesLayoutAdapter = AttributesLayoutAdapterUtil::makeAttributesLayoutAdapter($attributeCollection, $designerRules, $editableMetadata);
     $attributeIndexOrDerivedTypeAndLabels = array();
     foreach ($attributesLayoutAdapter->makeDesignerLayoutAttributes()->get() as $attributeIndexOrDerivedType => $data) {
         //special case with anyMixedAttributes since it is searchable but in the basic search part so never dynamically searchable
         if ($searchFormClassName::isAttributeSearchable($attributeIndexOrDerivedType) && $attributeIndexOrDerivedType != 'anyMixedAttributes') {
             $attributeIndexOrDerivedTypeAndLabels[$attributeIndexOrDerivedType] = $data['attributeLabel'];
         }
     }
     self::resolveAndAddViewDefinedNestedAttributes($modelAttributesAdapter->getModel(), $viewClassName, $attributeIndexOrDerivedTypeAndLabels);
     if (is_subclass_of($viewClassName, 'DynamicSearchView')) {
         $viewClassName::resolveAttributeIndexOrDerivedTypeAndLabelsForDynamicSearchRow($attributeIndexOrDerivedTypeAndLabels);
     }
     asort($attributeIndexOrDerivedTypeAndLabels);
     return $attributeIndexOrDerivedTypeAndLabels;
 }
 /**
  * Gets instance of application
  * @param  string  $appName  Application name
  * @param  string  $instance Instance name
  * @param  boolean $spawn    If true, we spawn an instance if absent
  * @param  boolean $preload  If true, worker is at the preload stage
  * @return object $instance AppInstance
  */
 public function getInstance($appName, $instance = '', $spawn = true, $preload = false)
 {
     $class = ClassFinder::find($appName, 'Applications');
     if (isset(Daemon::$appInstances[$class][$instance])) {
         return Daemon::$appInstances[$class][$instance];
     }
     if (!$spawn) {
         return false;
     }
     $fullname = $this->getAppFullname($appName, $instance);
     if (!class_exists($class)) {
         Daemon::$process->log(__METHOD__ . ': unable to find application class ' . $class . '\'');
         return false;
     }
     if (!is_subclass_of($class, '\\PHPDaemon\\Core\\AppInstance')) {
         Daemon::$process->log(__METHOD__ . ': class ' . $class . '\' found, but skipped as long as it is not subclass of \\PHPDaemon\\Core\\AppInstance');
         return false;
     }
     $fullnameClass = $this->getAppFullname($class, $instance);
     if ($fullname !== $fullnameClass && isset(Daemon::$config->{$fullname})) {
         Daemon::$config->renameSection($fullname, $fullnameClass);
     }
     if (!$preload) {
         /** @noinspection PhpUndefinedVariableInspection */
         if (!$class::$runOnDemand) {
             return false;
         }
         if (isset(Daemon::$config->{$fullnameClass}->limitinstances)) {
             return false;
         }
     }
     return new $class($instance);
 }
 /**
  * Implementation of ArrayAccess::offsetSet()
  *
  * Overrides ArrayObject::offsetSet() to validate that the value set at the
  * specified offset is a DbInstance.
  *
  * No value is returned.
  *
  * @param mixed $offset
  * @param DbInstanceInterface $value
  */
 public function offsetSet($offset, $value)
 {
     if (!is_subclass_of($value, 'Acquia\\Platform\\Cloud\\Hosting\\DbInstanceInterface')) {
         throw new \InvalidArgumentException(sprintf('%s: $value must be an implementation of DbInstanceInterface', __METHOD__));
     }
     parent::offsetSet($offset, $value);
 }
Пример #25
0
 /**
  * @param string $class_name
  */
 protected function getClass($class_name, $subclass_of = 'Cyan\\Framework\\Controller', array $arguments = [], \Closure $newInstance = null)
 {
     $required_traits = ['Cyan\\Framework\\TraitSingleton'];
     $reflection_class = new ReflectionClass($class_name);
     foreach ($required_traits as $required_trait) {
         if (!in_array($required_trait, $reflection_class->getTraitNames())) {
             throw new TraitException(sprintf('%s class must use %s', $class_name, $required_trait));
         }
     }
     if (!is_subclass_of($class_name, $subclass_of)) {
         throw new TraitException(sprintf('%s class must be a instance of %s', $class_name, $subclass_of));
     }
     if (is_callable($newInstance)) {
         $instance = call_user_func_array($newInstance, $arguments);
     } else {
         $instance = !empty($arguments) ? call_user_func_array([$class_name, 'getInstance'], $arguments) : $class_name::getInstance();
     }
     if ($this->hasContainer('application')) {
         if (!$instance->hasContainer('application')) {
             $instance->setContainer('application', $this->getContainer('application'));
         }
         if (!$instance->hasContainer('factory_plugin')) {
             $instance->setContainer('factory_plugin', $this->getContainer('application')->getContainer('factory_plugin'));
         }
     }
     if (is_callable([$instance, 'initialize']) || method_exists($instance, 'initialize')) {
         $instance->initialize();
     }
     return $instance;
 }
function respond_to_error($obj, $redirect_to_params, $options = array())
{
    $extra_api_params = isset($options['api']) ? $options['api'] : array();
    $status = isset($options['status']) ? $options['status'] : 500;
    if (is_object($obj) && is_subclass_of($obj, 'ActiveRecord')) {
        $obj = implode(', ', $obj->record_errors->full_messages());
        $status = 420;
    }
    if ($status == 420) {
        $status = '420 Invalid Record';
    } elseif ($status == 421) {
        $status = '421 User Throttled';
    } elseif ($status == 422) {
        $status = '422 Locked';
    } elseif ($status == 423) {
        $status = '423 Already Exists';
    } elseif ($status == 424) {
        $status = '424 Invalid Parameters';
    }
    switch (Request::$format) {
        case 'html':
            notice('Error: ' . $obj);
            check_array($redirect_to_params);
            call_user_func_array('redirect_to', $redirect_to_params);
        case 'json':
            render('json', to_json(array_merge($extra_api_params, array('success' => false, 'reason' => $obj))), array('status' => $status));
        case 'xml':
            // fmt.xml {render :xml => extra_api_params.merge(:success => false, :reason => obj).to_xml(:root => "response"), :status => status}
            break;
    }
}
Пример #27
0
 /**
  * Creates a new validation value for a validation set.
  * 
  * @param string|IValidator $validator The validator to build be it a class name (fully qualified)
  *                                     or a dummy validator object.
  * @param mixed ...$params The parameters to the validator. To use a field from the validated
  *                         object, set these as ValidationKey objects.
  */
 public function __construct($validator)
 {
     if (is_object($validator)) {
         if (!$validator instanceof IValidator) {
             throw new \InvalidArgumentException(Intl\GetText::_d('Flikore.Validator', 'The validator object must be a implementation of IValidator'));
         } else {
             $this->validator = get_class($validator);
         }
     } elseif (is_string($validator)) {
         if (!is_subclass_of($validator, 'Flikore\\Validator\\Interfaces\\IValidator')) {
             throw new \InvalidArgumentException(Intl\GetText::_d('Flikore.Validator', 'The validator object must be a implementation of IValidator'));
         } else {
             $this->validator = $validator;
         }
     } else {
         throw new \InvalidArgumentException(Intl\GetText::_d('Flikore.Validator', 'The validator object must be a implementation of IValidator'));
     }
     $params = func_get_args();
     array_shift($params);
     foreach ($params as $arg) {
         if ($arg instanceof ValidationKey) {
             $this->fields[] = $arg->getKey();
         }
     }
     $this->args = $params;
 }
Пример #28
0
 /**
  * Delete relations
  * @return bool
  */
 public function cleanUpRelations()
 {
     if (!is_subclass_of($this->owner, '\\yii\\db\\ActiveRecord')) {
         return false;
     }
     if (isset($this->owner->is_deleted) && 0 === intval($this->owner->is_deleted)) {
         return false;
     }
     if (null === ($object = Object::getForClass($this->owner->className()))) {
         return false;
     }
     $whereDelete = ['object_id' => $object->id, 'object_model_id' => $this->owner->id];
     ObjectPropertyGroup::deleteAll($whereDelete);
     ObjectStaticValues::deleteAll($whereDelete);
     Image::deleteAll($whereDelete);
     ViewObject::deleteAll($whereDelete);
     try {
         Yii::$app->db->createCommand()->delete($object->categories_table_name, ['object_model_id' => $this->owner->id])->execute();
         Yii::$app->db->createCommand()->delete($object->column_properties_table_name, ['object_model_id' => $this->owner->id])->execute();
         Yii::$app->db->createCommand()->delete($object->eav_table_name, ['object_model_id' => $this->owner->id])->execute();
     } catch (Exception $e) {
         // do nothing
     }
     return true;
 }
Пример #29
0
 public function output(Pagemill_Data $data, Pagemill_Stream $stream)
 {
     //$inner = $data->parseVariables($this->rawOutput(), false);
     $tmp = new Pagemill_Stream(true);
     foreach ($this->children() as $child) {
         $child->process($data, $tmp);
     }
     $inner = html_entity_decode($tmp->peek(), ENT_COMPAT, 'UTF-8');
     $data->set('value', $inner);
     $use = $data->parseVariables($this->getAttribute('use'));
     if ($use) {
         // Use the requested editor if available
         if (class_exists($use)) {
             if (is_subclass_of($use, __CLASS__)) {
                 $sub = new $use($this->name(), $this->attributes(), $this, $this->docType());
                 $sub->output($data, $stream);
                 return;
             } else {
                 trigger_error("Requested editor class '{$cls}' does not appear to be an editor subclass.");
             }
         } else {
             trigger_error("Requested editor class '{$cls}' does not exist.");
         }
     }
     if (TYPEF_DEFAULT_EDITOR != '') {
         // Use the requested editor if available
         $use = TYPEF_DEFAULT_EDITOR;
         if (class_exists($use)) {
             if (is_subclass_of($use, __CLASS__)) {
                 $sub = new $use($this->name(), $this->attributes(), $this, $this->docType());
                 $sub->output($data, $stream);
                 return;
             } else {
                 trigger_error("Configured editor class '{$use}' does not appear to be an editor subclass.");
             }
         } else {
             trigger_error("Configured editor class '{$use}' does not exist.");
         }
     }
     // Use CKEditor if available
     if (class_exists('Typeframe_Tag_Editor_CkEditor')) {
         $sub = new Typeframe_Tag_Editor_CkEditor($this->name(), $this->attributes(), $this, $this->docType());
         $sub->process($data, $stream);
         return;
     }
     // No editor available. Use a plain textarea.
     $attribs = '';
     foreach ($this->attributes() as $k => $v) {
         if ($k != 'use') {
             $attribs .= " {$k}=\"" . $data->parseVariables($v) . "\"";
         }
     }
     if (!$this->getAttribute('cols')) {
         $attribs .= ' cols="80"';
     }
     if (!$this->getAttribute('rows')) {
         $attribs .= ' rows="25"';
     }
     $stream->puts("<textarea{$attribs}>" . $inner . "</textarea>");
 }
Пример #30
0
 public function runProcess(IProcessMessage $message, IProcessDefinition $process, $taskId)
 {
     $this->_queueDelays[$taskId] = 0;
     $class = $process->getProcessClass();
     if (class_exists($class)) {
         $ruleClass = 'Qubes\\Defero\\Transport\\IMessageProcessor';
         /*
          * replaced below with faster implementation:
          * if(in_array($ruleClass, class_implements($class))))
          */
         if (is_subclass_of($class, $ruleClass)) {
             $proc = new $class($message);
         } else {
             $proc = new $class();
         }
         if ($proc instanceof IConfigurable) {
             $proc->configure($process->getConfig());
         }
         if ($proc instanceof IRule) {
             if ($proc->canProcess()) {
                 if ($proc instanceof IDeliveryRule) {
                     $this->_queueDelays[$taskId] = (int) $proc->getSendDelay();
                     Log::debug("Setting queue delay to " . $this->_queueDelays[$taskId]);
                 }
                 return true;
             }
             return false;
         } else {
             if ($proc instanceof IProcess) {
                 return $proc->process();
             }
         }
     }
     return false;
 }