_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q253400
Module.getTitle
validation
public function getTitle() { if (!is_object($this->_title)) { $this->_title = new Noun($this->_title); } return $this->_title; }
php
{ "resource": "" }
q253401
Module.getDetailsWidget
validation
public function getDetailsWidget($objectModel = null) { if (is_null($objectModel) && isset(Yii::$app->request->object)) { $objectModel = Yii::$app->request->object; } elseif (is_null($objectModel)) { $objectModel = $this->dummyModel; } $detailsSection = $this->getDetailsSection(); if ($detailsSection === false) { return false; } if ($detailsSection === true) { $detailsSection = '_self'; } $detailsWidgetClass = self::classNamespace() . '\widgets\\' . 'Details'; $widgetClass = $this->fallbackDetailsWidgetClass; @class_exists($detailsWidgetClass); if (class_exists($detailsWidgetClass, false)) { $widgetClass = $detailsWidgetClass; } $widget = ['class' => $widgetClass]; $widget['owner'] = $this; $widgetItem = ['widget' => $widget, 'locations' => ['self'], 'priority' => 1]; $widgetItem['section'] = Yii::$app->collectors['sections']->getOne($detailsSection); return $widgetItem; }
php
{ "resource": "" }
q253402
Module.getIsChildless
validation
public function getIsChildless() { if (empty($this->collectorItem) || empty($this->collectorItem->children)) { return true; } return false; }
php
{ "resource": "" }
q253403
Module.getForm
validation
public function getForm($primaryModel = false, $settings = []) { if (!$primaryModel) { return false; } $formSegments = [$this->getFormSegment($primaryModel, $settings)]; $config = ['class' => $this->formGeneratorClass, 'models' => $primaryModel->collectModels(), 'items' => $formSegments]; return Yii::createObject($config); }
php
{ "resource": "" }
q253404
Module.getFormSegment
validation
public function getFormSegment($primaryModel = null, $settings = []) { if (empty($primaryModel)) { return false; } return $primaryModel->form($settings); }
php
{ "resource": "" }
q253405
Schema.createAuthorityTable
validation
private function createAuthorityTable() { //Drop the authority table if exists, create if doesn't $this->database->query("DROP TABLE IF EXISTS `?authority`;"); $this->database->query( "CREATE TABLE IF NOT EXISTS `?authority` ( `authority_id` bigint(20) NOT NULL AUTO_INCREMENT, `authority_title` varchar(100) NOT NULL, `authority_parent_id` bigint(20) NOT NULL, `authority_name` varchar(45) NOT NULL COMMENT ' ', `authority_description` varchar(255) DEFAULT NULL, `lft` int(11) NOT NULL, `rgt` int(11) NOT NULL, PRIMARY KEY (`authority_id`), UNIQUE KEY `authority_name_UNIQUE` (`authority_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;" ); //Dumping data for table authority? $this->database->query( "INSERT INTO `?authority` (`authority_id`, `authority_title`, `authority_parent_id`, `authority_name`, `authority_description`, `lft`, `rgt`) VALUES (1, 'PUBLIC', 0, 'PUBLIC', 'All unregistered nodes, users and applications', 1, 8), (2, 'Registered Users', 1, 'REGISTEREDUSERS', 'All registered nodes with a known unique identifier', 2, 7), (3, 'Moderators', 2, 'MODERATORS', 'System moderators, Users allowed to manage user generated import', 3, 6), (4, 'Super Administrators', 3, 'MASTERADMINISTRATORS', 'Special users with awesome powers', 4, 5);" ); }
php
{ "resource": "" }
q253406
Schema.createAuthorityPermissionsTable
validation
private function createAuthorityPermissionsTable() { //Drop the authority table if exists, create if doesn't $this->database->query("DROP TABLE IF EXISTS `?authority_permissions`;"); $this->database->query( "CREATE TABLE IF NOT EXISTS `?authority_permissions` ( `authority_permission_key` bigint(20) NOT NULL AUTO_INCREMENT, `authority_id` bigint(20) NOT NULL, `permission_area_uri` varchar(255) NOT NULL, `permission` varchar(45) NOT NULL DEFAULT '1', `permission_type` varchar(45) NOT NULL, `permission_title` varchar(45) NOT NULL, PRIMARY KEY (`authority_permission_key`), UNIQUE KEY `UNIQUE` (`permission_area_uri`,`permission_type`,`authority_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;" ); //Dumping default permission data to authority_permission tablegit $this->database->query( "INSERT INTO `?authority_permissions` (`authority_permission_key`, `authority_id`, `permission_area_uri`, `permission`, `permission_type`, `permission_title`) VALUES (1, 4, '^/admin(/[a-z0-9-]*)*', 'allow', 'special', 'Console'), (2, 1, '^/admin/setup/install(/[a-z0-9-]*)*', 'allow', 'execute', 'Installer'), (3, 4, '^/page(/[a-z0-9-]*)*', 'allow', 'execute', 'Content'), (4, 2, '^/member(/[a-z0-9-]*)*', 'allow', 'execute', 'Member Pages'), (5, 1, '^/member/sign([a-z0-9-]*)*', 'allow', 'execute', 'Authentication'), (6, 2, '^/message(/[a-z0-9-]*)*', 'allow', 'execute', 'Messages'), (7, 1, '^/search(/[a-z0-9-]*)*', 'allow', 'execute', 'Search'), (8, 4, '^/listing(/[a-z0-9-]*)*', 'allow', 'special', 'Directory'), (9, 2, '^/notification(/[a-z0-9-]*)*', 'allow', 'execute', 'Messages'), (10, 1, '^/post(/[a-z0-9-]*)*', 'allow', 'view', 'Content'), (11, 1, '^/event(/[a-z0-9-]*)*', 'allow', 'view', 'Content'), (12, 1, '^/stream(/[a-z0-9-]*)*', 'allow', 'view', 'Content'), (13, 1, '^/group(/[a-z0-9-]*)*', 'allow', 'view', 'Content'), (14, 1, '^/file(/[a-z0-9-]*)*', 'allow', 'view', 'Content'), (16, 2, '^/post(/[a-z0-9-]*)*', 'allow', 'execute', 'Content'), (15, 1, '^/page(/[a-z0-9-]*)*', 'allow', 'view', 'Content');" ); }
php
{ "resource": "" }
q253407
Schema.createMenutable
validation
private function createMenutable() { //Drop the menu table if it already exists; $this->database->query("DROP TABLE IF EXISTS `?menu`;"); $this->database->query( "CREATE TABLE IF NOT EXISTS `?menu` ( `menu_id` int(11) NOT NULL AUTO_INCREMENT, `menu_parent_id` int(11) NOT NULL DEFAULT '0', `menu_title` varchar(45) NOT NULL, `menu_url` varchar(100) NOT NULL, `menu_classes` varchar(45) DEFAULT NULL, `menu_order` int(11) NOT NULL DEFAULT '0', `menu_group_id` int(11) NOT NULL, `menu_type` varchar(45) NOT NULL DEFAULT 'link', `menu_callback` varchar(255) DEFAULT NULL, `lft` int(11) NOT NULL, `rgt` int(11) NOT NULL, `menu_iscore` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`menu_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=99 ; " ); //Default menu data input; $this->database->query( "INSERT INTO `?menu` (`menu_id`, `menu_parent_id`, `menu_title`, `menu_url`, `menu_classes`, `menu_order`, `menu_group_id`, `menu_type`, `menu_callback`, `lft`, `rgt`, `menu_iscore`) VALUES (85, 0, 'Photos', '/photo/gallery', NULL, 0, 1, 'link', NULL, 3, 12, 1), (86, 0, 'Audio', '/audio/gallery', NULL, 0, 1, 'link', NULL, 4, 11, 1), (87, 0, 'Videos', '/video/gallery', NULL, 0, 1, 'link', NULL, 5, 10, 1), (88, 0, 'Text', '/text/gallery', '', 23, 1, 'link', '', 6, 9, 1), (73, 0, 'Dashboard', '/member/dashboard', '', 0, 2, 'link', NULL, 1, 2, 1), (74, 0, 'Settings', '/member/settings', NULL, 0, 2, 'link', NULL, 3, 4, 1), (75, 0, 'Inbox', '/member/messages', NULL, 0, 3, 'link', NULL, 2, 3, 1), (25, 80, 'Maintenance', '/admin/settings/maintenance', '', 20, 3, 'link', '', 12, 13, 1), (30, 80, 'Emails', '/admin/settings/emails', '', 20, 3, 'link', '', 10, 11, 1), (32, 80, 'Localization', '/admin/settings/localization', '', 20, 3, 'link', '', 8, 9, 1), (33, 80, 'Input', '/admin/settings/input', '', 20, 3, 'link', '', 6, 7, 1), (34, 80, 'Server', '/admin/settings/server', '', 20, 3, 'link', '', 4, 5, 1), (56, 0, 'Dashboard', '/member/dashboard', NULL, 0, 3, 'link', NULL, 1, 2, 1), (78, 80, 'Permissions', '/admin/settings/permissions', '', 20, 3, 'link', '', 14, 15, 1), (80, 0, 'Configuration', '/admin/settings/configuration', '', 20, 3, 'link', '', 3, 16, 1), (98, 0, 'Appearance', '/admin/settings/appearance', NULL, 0, 3, 'link', NULL, 17, 18, 1), (99, 0, 'Pages', '/admin/pages', NULL , 0, 3, 'link', NULL, 3, 4, 1), (101,0, 'Navigation', '/admin/settings/navigation', NULL, 0, 3, 'link', NULL, 17, 18, 1), (102,0, 'Extensions', '/admin/settings/extensions', NULL, 0, 3, 'link', NULL, 17, 18, 1), (103,0, 'Users', '/admin/users', NULL, 0, 3, 'link', NULL, 17, 18, 1);" ); }
php
{ "resource": "" }
q253408
Schema.createMenuGroupTable
validation
private function createMenuGroupTable() { $this->database->query("DROP TABLE IF EXISTS `?menu_group`;"); $this->database->query( "CREATE TABLE IF NOT EXISTS `?menu_group` ( `menu_group_id` int(11) NOT NULL AUTO_INCREMENT, `menu_group_title` varchar(45) NOT NULL, `menu_group_order` int(11) NOT NULL DEFAULT '0', `menu_group_uid` varchar(45) NOT NULL, `menu_group_iscore` TINYINT(1) NOT NULL DEFAULT '0', PRIMARY KEY (`menu_group_id`), UNIQUE KEY `menu_group_id_UNIQUE` (`menu_group_id`), UNIQUE KEY `menu_group_uid_UNIQUE` (`menu_group_uid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ; "); $this->database->query( "INSERT INTO `?menu_group` (`menu_group_id`, `menu_group_title`, `menu_group_order`, `menu_group_uid`, `menu_group_iscore`) VALUES (1, 'Media Menu', 1, 'mediamenu', 1), (2, 'User Menu', 2, 'usermenu', 1), (3, 'Dashboard Menu', 3, 'dashboardmenu', 1), (4, 'Messages Menu', 4, 'messagesmenu', 1), (5, 'Profile Menu', 5, 'profilemenu', 1), (6, 'People Menu', 6, 'peoplemenu', 1);" ); }
php
{ "resource": "" }
q253409
Schema.createPropertyValuesProxyTable
validation
public function createPropertyValuesProxyTable($group, $dropExisting = true) { $group = strtolower($group); if (!empty($group)) : $this->database->query("DROP TABLE IF EXISTS `?{$group}_property_values`;"); $this->database->query( "CREATE TABLE IF NOT EXISTS `?{$group}_property_values` ( `value_id` mediumint(11) NOT NULL AUTO_INCREMENT, `value_data` text NOT NULL, `value_updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `property_id` int(11) NOT NULL, `object_id` int(11) NOT NULL, PRIMARY KEY (`value_id`), UNIQUE KEY `object_property_uid` (`object_id`,`property_id`), KEY `property_id_idxfk` (`property_id`), KEY `object_id_idxfk` (`object_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;" ); $this->database->query("DROP TRIGGER IF EXISTS `?{$group}_property_value_validate_insert`;"); $this->database->query( "CREATE TRIGGER `?{$group}_property_value_validate_insert` BEFORE INSERT ON `?{$group}_property_values` FOR EACH ROW BEGIN CALL ?property_value_validate(NEW.property_id, NEW.value_data); END;" ); $this->database->query("DROP TRIGGER IF EXISTS `?{$group}_property_value_validate_update`;"); $this->database->query( "CREATE TRIGGER `?{$group}_property_value_validate_update` BEFORE UPDATE ON `?{$group}_property_values` FOR EACH ROW BEGIN CALL ?property_value_validate(NEW.property_id, NEW.value_data); END;" ); //Add reference constrains $this->database->query( "ALTER TABLE `?{$group}_property_values` ADD CONSTRAINT `{$group}_property_values_ibfk_1` FOREIGN KEY (`object_id`) REFERENCES `?objects` (`object_id`), ADD CONSTRAINT `{$group}_property_values_ibfk_2` FOREIGN KEY (`property_id`) REFERENCES `?properties` (`property_id`) ON DELETE CASCADE;" ); endif; }
php
{ "resource": "" }
q253410
Schema.createPropertyValuesTable
validation
private function createPropertyValuesTable() { $this->database->query("DROP TABLE IF EXISTS `?property_values`;"); $this->database->query( "CREATE TABLE IF NOT EXISTS `?property_values` ( `value_id` mediumint(11) NOT NULL AUTO_INCREMENT, `value_data` text NOT NULL, `value_updated_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `property_id` int(11) NOT NULL, `object_id` int(11) NOT NULL, PRIMARY KEY (`value_id`), UNIQUE KEY `object_property_uid` (`object_id`,`property_id`), KEY `property_id_idxfk` (`property_id`), KEY `object_id_idxfk` (`object_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;" ); $this->database->query("DROP PROCEDURE IF EXISTS `property_value_validate`;"); $this->database->query( "CREATE PROCEDURE `?property_value_validate`(IN _property_id INT, IN _value_data LONGTEXT) BEGIN DECLARE _validationFails CONDITION FOR SQLSTATE '99001'; DECLARE _dataTypeRegExp VARCHAR(255); DECLARE _signalText TEXT; SELECT r.datatype_validation FROM `?properties` AS d INNER JOIN `?property_datatypes` AS r WHERE `property_id`= _property_id AND d.property_datatype=r.datatype_name INTO _dataTypeRegExp; IF (_dataTypeRegExp IS NOT NULL) THEN IF (_value_data NOT REGEXP(_dataTypeRegExp)) THEN SET _signalText = CONCAT('The inserted/updated value fails the property data type validation'); SIGNAL _validationFails SET MESSAGE_TEXT=_signalText; END IF; END IF; END;" ); $this->database->query("DROP TRIGGER IF EXISTS `?property_value_validate_insert`;"); $this->database->query( "CREATE TRIGGER `?property_value_validate_insert` BEFORE INSERT ON `?property_values` FOR EACH ROW BEGIN CALL ?property_value_validate(NEW.property_id, NEW.value_data); END;" ); $this->database->query("DROP TRIGGER IF EXISTS `?property_value_validate_update`;"); $this->database->query( "CREATE TRIGGER `?property_value_validate_update` BEFORE UPDATE ON `?property_values` FOR EACH ROW BEGIN CALL ?property_value_validate(NEW.property_id, NEW.value_data); END;" ); }
php
{ "resource": "" }
q253411
Schema.createTables
validation
public function createTables(Database $database) { $this->database = $database; $this->database->startTransaction(); $this->createAuthorityTable(); $this->createAuthorityPermissionsTable(); $this->createMenutable(); $this->createMenuGroupTable(); $this->createOptionsTable(); //$this->createContentmetaTable(); //$this->createContentsTable(); $this->createSessionTable(); $this->createTaxonomyTable(); $this->createObjectsTable(); $this->createGroupsTable(); $this->createObjectsAuthorityTable(); $this->createObjectsGroupTable(); $this->createObjectsEdgesTable(); $this->createPropertiesTable(); $this->createPropertyDatatypeTable(); $this->createPropertyValuesTable(); $this->createIndices(); $this->insertPropertyDatatypes(); $this->createObjectsRatingTable(); $this->createPropertyValuesProxyTable("attachment"); //The attachment table $this->createPropertyValuesProxyTable("media"); //The media table $this->createPropertyValuesProxyTable("user"); //The users table $this->createPropertyValuesProxyTable("page"); //The users table //$this->createUsermetaTable(); //$this->createUsersTable(); //$this->createUsersView(); if (!$this->database->commitTransaction()) { //$this->setError($this->$database->getError()); return false; } return true; }
php
{ "resource": "" }
q253412
Definition.getDefaultForClass
validation
public static function getDefaultForClass($class, array $params = array()) { $reflectionClass = new ReflectionClass($class); if (!$reflectionClass->isInstantiable()) { throw new NotInstantiableException("Class $class is not instantiable"); } $factory = new static([$reflectionClass, 'newInstance'], "$class::__construct"); if ($reflectionClass->hasMethod('__construct')) { static::addReflectionArguments($factory, $reflectionClass->getMethod('__construct')); } return $factory->getFactory($params); }
php
{ "resource": "" }
q253413
Definition.getDefaultForCallable
validation
public static function getDefaultForCallable($callable, array $params = array()) { if ($callable instanceof Closure) { $factory = new static($callable, 'closure'); $factory->addOptionalClassArgument('$container', 'Autarky\Container\ContainerInterface'); return $factory->getFactory($params); } return static::getFromReflection($callable, null) ->getFactory($params); }
php
{ "resource": "" }
q253414
Definition.addReflectionArguments
validation
protected static function addReflectionArguments(Definition $factory, ReflectionFunctionAbstract $reflectionFunction = null) { if (!$reflectionFunction) { $callable = $factory->getCallable(); if (is_array($callable)) { $reflectionFunction = new ReflectionMethod($callable[0], $callable[1]); } else { $reflectionFunction = new ReflectionFunction($callable); } } foreach ($reflectionFunction->getParameters() as $arg) { try { $name = $arg->getName(); $required = ! $arg->isOptional(); if ($argClass = $arg->getClass()) { $factory->addClassArgument($name, $argClass->getName(), $required); } else { $default = ($required ? null : $arg->getDefaultValue()); $factory->addScalarArgument($name, null, $required, $default); } } catch (ReflectionException $re) { throw UnresolvableArgumentException::fromReflectionParam( $arg, $reflectionFunction, $re); } } }
php
{ "resource": "" }
q253415
Definition.addScalarArgument
validation
public function addScalarArgument($name, $type, $required = true, $default = null) { return $this->addArgument(new ScalarArgument($this->argumentPosition++, $name, $type, $required, $default)); }
php
{ "resource": "" }
q253416
Definition.addOptionalScalarArgument
validation
public function addOptionalScalarArgument($name, $type, $default) { return $this->addArgument(new ScalarArgument($this->argumentPosition++, $name, $type, false, $default)); }
php
{ "resource": "" }
q253417
Definition.addClassArgument
validation
public function addClassArgument($name, $class, $required = true) { return $this->addArgument(new ClassArgument($this->argumentPosition++, $name, $class, $required)); }
php
{ "resource": "" }
q253418
Definition.addArgument
validation
public function addArgument(ArgumentInterface $argument) { $this->argumentPositions[$argument->getPosition()] = $argument; $this->argumentNames[$argument->getName()] = $argument; if ($argument->isClass()) { $this->argumentClasses[$argument->getClass()] = $argument; } return $argument; }
php
{ "resource": "" }
q253419
User.getIndividual
validation
public function getIndividual() { if (!isset($this->_individual) && !empty($this->object_individual_id)) { $this->_individual = false; $individualType = Yii::$app->collectors['types']->getOne('Individual'); if (!empty($individualType->object)) { $individualClass = $individualType->object->primaryModel; $this->_individual = $individualClass::get($this->object_individual_id); } } return $this->_individual; }
php
{ "resource": "" }
q253420
User.getPhotoEmail
validation
public function getPhotoEmail() { if (!empty($this->email) && substr($this->email, -6) !== ".local") { return $this->email; } return false; }
php
{ "resource": "" }
q253421
Relationship.getTaxonomyPackage
validation
public function getTaxonomyPackage() { if (empty($this->taxonomy)) { return false; } $taxonomySettings = $this->taxonomy; if (!is_array($taxonomySettings)) { $taxonomySettings = ['id' => $taxonomySettings]; } $taxonomy = Yii::$app->collectors['taxonomies']->getOne($taxonomySettings['id']); if (empty($taxonomy) || empty($taxonomy->object)) { return false; } return $taxonomy->package($taxonomySettings); }
php
{ "resource": "" }
q253422
Relationship.getPrimaryObject
validation
public function getPrimaryObject($primaryObject, $relatedObject, $role) { if (!$this->handlePrimary) { return false; } if ($role === 'child') { $primaryField = 'primary_child'; if (!$relatedObject->objectType->getPrimaryAsChild($this->parent)) { // \d(['bad', $this->systemId, get_class($primaryObject), get_class($relatedObject), $role]); return false; } $primaryParent = $primaryObject; } else { $primaryField = 'primary_parent'; if (!$relatedObject->objectType->getPrimaryAsParent($this->child)) { // \d(['bad', $this->systemId, get_class($primaryObject), get_class($relatedObject), $role]); return false; } $primaryParent = $relatedObject; } $key = json_encode([__FUNCTION__, $this->systemId, $primaryObject->primaryKey]); if (!isset(self::$_cache[$key])) { self::$_cache[$key] = null; $relationClass = Yii::$app->classes['Relation']; $childClass = $this->child->primaryModel; $relation = $relationClass::find(); $alias = $relationClass::tableName(); $relation->andWhere(['`' . $alias . '`.`parent_object_id`' => $primaryParent->primaryKey, '`' . $alias . '`.`' . $primaryField . '`' => 1]); $relation->andWhere(['or', '`' . $alias . '`.`child_object_id` LIKE :prefix']); //, '`'. $alias.'`.`child_object_id` LIKE \''.$childClass.'\'' $relation->params[':prefix'] = $childClass::modelPrefix() . '-%'; $primaryObject->addActiveConditions($relation, $alias); // \d([$this->systemId, $relation->createCommand()->rawSql, $primaryField, $role]); $relation = $relation->one(); if (!empty($relation)) { self::$_cache[$key] = $relation; } } return self::$_cache[$key]; }
php
{ "resource": "" }
q253423
Relationship.getPrimaryChild
validation
public function getPrimaryChild($parentObject) { if (!$this->handlePrimary) { return false; } if (!$this->child->getPrimaryAsChild($this->parent)) { return false; } $key = json_encode([__FUNCTION__, $this->systemId, $parentObject->primaryKey]); if (!isset(self::$_cache[$key])) { self::$_cache[$key] = null; $relationClass = Yii::$app->classes['Relation']; $childClass = $this->child->primaryModel; $relation = $relationClass::find(); $alias = $relationClass::tableName(); $relation->andWhere(['`' . $alias . '`.`parent_object_id`' => $parentObject->primaryKey, '`' . $alias . '`.`primary_child`' => 1]); $relation->andWhere(['or', '`' . $alias . '`.`child_object_id` LIKE :prefix']); //, '`'. $alias.'`.`child_object_id` LIKE \''.$childClass.'\'' $relation->params[':prefix'] = $childClass::modelPrefix() . '-%'; $parentObject->addActiveConditions($relation, $alias); $relation = $relation->one(); if (!empty($relation)) { self::$_cache[$key] = $relation; } } return self::$_cache[$key]; }
php
{ "resource": "" }
q253424
Relationship.getOne
validation
public static function getOne(Item $parent, Item $child, $options = []) { $key = md5($parent->systemId . "." . $child->systemId); if (isset(self::$_relationships[$key])) { self::$_relationships[$key]->mergeOptions($options); } else { self::$_relationships[$key] = new Relationship($parent, $child, $options); } return self::$_relationships[$key]; }
php
{ "resource": "" }
q253425
Relationship.getById
validation
public static function getById($relationshipId) { $key = md5($relationshipId); if (isset(self::$_relationships[$key])) { return self::$_relationships[$key]; } return false; }
php
{ "resource": "" }
q253426
Relationship.getNiceId
validation
public function getNiceId($queryRole) { $roleType = $this->roleType($queryRole); if (empty($roleType)) { return false; } return implode(':', [$this->role($queryRole), $roleType->systemId]); }
php
{ "resource": "" }
q253427
Relationship.getCompanionNiceId
validation
public function getCompanionNiceId($queryRole) { $companionRoleType = $this->companionRoleType($queryRole); if (empty($companionRoleType)) { return false; } return implode(':', [$this->companionRole($queryRole), $companionRoleType->systemId]); }
php
{ "resource": "" }
q253428
Relationship.setDefaultOptions
validation
public function setDefaultOptions() { foreach ($this->_defaultOptions as $k => $v) { if (!array_key_exists($k, $this->_options)) { $this->_options[$k] = $v; } } return true; }
php
{ "resource": "" }
q253429
Relationship.getRelatedObject
validation
public function getRelatedObject($baseObject, $baseRole, $primaryRelation = null) { $companionRole = $this->companionRole($baseRole); $companionType = $this->companionRoleType($baseRole); $companionModel = $companionType->primaryModel; if (!isset($primaryRelation) || is_array($primaryRelation)) { if (!is_array($primaryRelation)) { $primaryRelation = []; } $primaryRelation = $this->getPrimaryRelation($baseObject, $baseRole, $primaryRelation); } if (!empty($primaryRelation)) { if ($companionRole === 'child') { return $primaryRelation->childObject; } else { return $primaryRelation->parentObject; } } return false; }
php
{ "resource": "" }
q253430
Relationship.getPrimaryRelation
validation
public function getPrimaryRelation($baseObject, $baseRole, $relationOptions = []) { $companionRole = $this->companionRole($baseRole); $companionType = $this->companionRoleType($baseRole); $companionModel = $companionType->primaryModel; if (!isset($relationOptions['order'])) { $relationOptions['order'] = []; } if ($companionRole === 'child') { array_unshift($relationOptions['order'], ['primary_child', SORT_DESC]); $relation = $baseObject->queryParentRelations($companionModel, $relationOptions)->one(); } else { array_unshift($relationOptions['order'], ['primary_parent', SORT_DESC]); $relation = $baseObject->queryParentRelations($companionModel, $relationOptions)->one(); } if (empty($relation)) { return false; } else { return $relation; } }
php
{ "resource": "" }
q253431
Relationship.getActive
validation
public function getActive() { return (isset($this->_child) and $this->_child->active) and (isset($this->_parent) and $this->_parent->active); }
php
{ "resource": "" }
q253432
UnresolveableArgumentException.buildMessage
validation
protected function buildMessage() { $className = $this->getClassName(); $methodName = $this->getMethodName(); $functionName = $this->getFunctionName(); if ($className !== null && $methodName !== null) { $callable = $className . '::' . $methodName;; } else { $callable = $functionName; } $this->message = s( 'Container could not resolve argument %s for %s.', $this->getArgumentIndex(), $callable ); }
php
{ "resource": "" }
q253433
ProfilingCacheDecorator.doSave
validation
protected function doSave($id, $data, $lifeTime = 0) { return $this->delegate->doSave($id, $data, $lifeTime); }
php
{ "resource": "" }
q253434
ExceptionListener.onKernelException
validation
public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof AuthenticationCredentialsNotFoundException) { return new RedirectResponse("/login"); } $message = $exception->getMessage(); if ($exception instanceof NotFoundHttpException || $exception instanceof PageNotPublishedException) { $this->render404page($event, $message); return; } if (!$exception instanceof RedKiteCmsExceptionInterface) { DataLogger::log($message, DataLogger::CRITICAL); if ($this->debug) { return $event; } $this->setUpResponse($event, $message); return; } $message = Utils::translateException($message, $exception); $this->setUpResponse($event, $message); DataLogger::log($message, DataLogger::ERROR); }
php
{ "resource": "" }
q253435
Instantiator.instantiate
validation
public function instantiate($className, array $data = []) { $refl = new \ReflectionClass($className); $instanceArgs = []; if ($data) { $instanceArgs = $this->extractArguments($refl->getConstructor()->getParameters(), $data); } return $refl->newInstanceArgs($instanceArgs); }
php
{ "resource": "" }
q253436
Instantiator.extractArguments
validation
protected function extractArguments(array $arguments, array $data) { $instanceArgs = []; foreach ($arguments as $arg) { if (array_key_exists($arg->getName(), $data)) { $instanceArgs[] = $data[$arg->getName()]; } else { $instanceArgs[] = null; } } return $instanceArgs; }
php
{ "resource": "" }
q253437
Url.current
validation
public static function current() { if (defined('PHPUNIT_RUNNING')) { return 'http://localhost'; } $protocol = 'http://'; if (!empty($_SERVER['HTTPS']) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https')) { $protocol = 'https://'; } return $protocol.request()->server('HTTP_HOST').request()->server('REQUEST_URI'); }
php
{ "resource": "" }
q253438
JsonTools.toBlock
validation
public static function toBlock(Serializer $serializer, $json) { if (empty($json)) { return null; } $contentArray = json_decode($json, true); if (!array_key_exists("type", $contentArray)) { return null; } $className = BlockFactory::getBlockClass($contentArray["type"]); if (!class_exists($className)) { return null; } return $serializer->deserialize($json, $className, 'json'); }
php
{ "resource": "" }
q253439
JsonTools.toJson
validation
public static function toJson(Serializer $serializer, \RedKiteCms\Content\Block\BaseBlock $block) { return $serializer->serialize($block, 'json'); }
php
{ "resource": "" }
q253440
JsonTools.join
validation
public static function join($json1, $json2) { return array_merge(self::jsonDecode($json1), self::jsonDecode($json2)); }
php
{ "resource": "" }
q253441
Map.getData
validation
public function getData($object) { if (!$this->validateObject($object)) { throw new InvalidArgumentException( "Given object isn't instance of {$this->localName}" ); } $reflection = new ReflectionObject($object); $data = []; foreach (array_keys($this->properties) as $localProperty) { $property = $reflection->getProperty($localProperty); $property->setAccessible(true); $data[$localProperty] = $property->getValue($object); } return $data; }
php
{ "resource": "" }
q253442
ElFinderMediaController.mediaAction
validation
public function mediaAction(Request $request, Application $app) { $options = array( "connector" => $app["red_kite_cms.elfinder_media_connector"], ); return parent::show($options); }
php
{ "resource": "" }
q253443
GuzzleResponseFactory.create
validation
public function create(int $status = 200, array $headers = [], $body = null) : ResponseInterface { return new Response($status, $headers, $body); }
php
{ "resource": "" }
q253444
RoleEventHandler.subscribe
validation
public function subscribe($events) { $events->listen('Neonbug\\Common\\Events\\AdminAddEditPrepareField', function($event) { if ($event->field['type'] != 'user_admin::add_fields.role') return; $roles = \Neonbug\Common\Models\Role::all(); $roles_by_key = []; foreach ($roles as $role) { if ($role->id_role == 'admin') continue; $roles_by_key[$role->id_role] = $role->name; } $event->field['values'] = $roles_by_key; $selected_roles = []; if ($event->item != null) { foreach ($event->item->roles as $role) { $selected_roles[] = $role->id_role; } } $event->field['selected_roles'] = $selected_roles; }); }
php
{ "resource": "" }
q253445
EmojiModifier.makeEmojiAccessible
validation
public function makeEmojiAccessible($text) { return preg_replace_callback( $this->search, function ($matches) { $desc = $this->emoji[$this->utf8ToUnicode($matches[0])]; return sprintf($this->output, $desc, $matches[0]); }, $text ); }
php
{ "resource": "" }
q253446
HTTPCachedResponseFactory.generate
validation
public function generate($date='global', Response $response=null) { if (!$response) $response = new Response; if ($this->maxAge) $response->setMaxAge ($this->maxAge); if ($this->sharedMaxAge) $response->setSharedMaxAge ($this->sharedMaxAge); if ($date instanceof \DateTime) { $response->setLastModified($date); } else { $response->setLastModified($this->manager->getLastUpdate($date)); } return $response; }
php
{ "resource": "" }
q253447
PaginationFactoryTrait.createPagination
validation
public function createPagination($currentPage, $total, $perPage = null, $baseUrl = null, $neighbours = null) { if (isset($this->container) && $this->container instanceof \League\Container\ContainerInterface) { return $this->getContainer()->get('Laasti\Pagination\Pagination', [$currentPage, $total, $perPage, $baseUrl, $neighbours]); } $perPage = $perPage ?: 10; $baseUrl = $baseUrl ?: ''; $neighbours = $neighbours ?: 3; return new Pagination($currentPage, $total, $perPage, $baseUrl, $neighbours); }
php
{ "resource": "" }
q253448
Slot.refresh
validation
public function refresh() { if (null === $this->options || null === $this->sourceDir) { return; } $this->render($this->sourceDir, $this->options, $this->username); }
php
{ "resource": "" }
q253449
SingleSection.getSingleWidget
validation
public function getSingleWidget() { if (is_null($this->_singleWidget)) { $this->_singleWidget = false; $widgets = $this->collectorItem->getAll(); if (!empty($widgets)) { $widget = array_shift($widgets); $this->_singleWidget = Yii::$app->collectors['widgets']->build($this, $widget->object); } } return $this->_singleWidget; }
php
{ "resource": "" }
q253450
ProcessOrders.getAccSys
validation
private function getAccSys($assetTypeCode) { $req = new \Praxigento\Accounting\Api\Service\Account\Get\Request(); $req->setIsSystem(TRUE); $req->setAssetTypeCode($assetTypeCode); $resp = $this->servAccount->exec($req); $result = $resp->getId(); return $result; }
php
{ "resource": "" }
q253451
ProcessOrders.saveTransLogs
validation
private function saveTransLogs($orders, $transIds) { /* re-map orders from with saleId key */ $bySaleId = []; foreach ($orders as $custId => $order) { $saleId = $order[QGetOrders::A_SALE_ID]; $bySaleId[$saleId] = $order; } foreach ($transIds as $tranId => $one) { $pref = substr($one, 0, 2); $orderId = str_replace($pref, '', $one); if ($pref == self::PREFIX_PV) { /* log PV off & order itself*/ $custId = $bySaleId[$orderId][QGetOrders::A_CUST_ID]; $this->daoLogCust->create([ LogCust::A_TRANS_ID => $tranId, LogCust::A_CUSTOMER_ID => $custId ]); $this->daoLogSale->create([ LogSales::A_TRANS_ID => $tranId, LogSales::A_SALE_ORDER_ID => $orderId ]); } elseif ($pref == self::PREFIX_BONUS_FATHER) { /* log BONUS Father On */ $custId = $bySaleId[$orderId][QGetOrders::A_PARENT_ID]; $this->daoLogCust->create([ LogCust::A_TRANS_ID => $tranId, LogCust::A_CUSTOMER_ID => $custId ]); } else { /* log BONUS Grand On */ $custId = $bySaleId[$orderId][QGetOrders::A_PARENT_GRAND_ID]; $this->daoLogCust->create([ LogCust::A_TRANS_ID => $tranId, LogCust::A_CUSTOMER_ID => $custId ]); } } }
php
{ "resource": "" }
q253452
AbstractCompositeView.addSnippet
validation
public function addSnippet(string $snptName): void { $this->snippets[$snptName] = ViewFactory::createSnippet($snptName); }
php
{ "resource": "" }
q253453
AbstractCompositeView.getSnippet
validation
public function getSnippet(string $snptName = '') { if (empty($snptName)) { return $this->snippets; } else { return isset($this->snippets[$snptName]) ? $this->snippets[$snptName] : null; } }
php
{ "resource": "" }
q253454
App.getMiddleware
validation
public function getMiddleware($name, $arguments = null) { if ($this->existsMiddleware($name)) { return $this->middlewares[$name](); } return false; }
php
{ "resource": "" }
q253455
App.run
validation
public function run($route) { if (!is_array($route)) { $this->makeResponse($route); } // Se separa la vista por ".", si es que la vista esta en subcarpetas // NOTA: En ForeverPHP los niveles de directorios se separan por "." $viewSegments = explode('.', $route['view']); // Nombre del metodo a ejecutar $method = $route['method']; Setup::toDefine('TEMPLATES_PATH', APPS_ROOT . DS . $this->appName . DS . 'Templates' . DS); Setup::toDefine('STATIC_PATH', APPS_ROOT . DS . 'static' . DS); $viewPath = ''; $view = $viewSegments[0]; if (count($viewSegments) > 1) { $view = $viewSegments[count($viewSegments) - 1]; // Se elimina el ultimo segmento de la vista, que es el nombre del archivo vista array_pop($viewSegments); // Se unen los segmentos de la vista con el separador de nombres de espacio $viewPath = implode('\\', $viewSegments); $viewPath .= '\\'; } // Verifico que la vista hereda de View if ($view instanceof \ForeverPHP\View\View) { throw new ViewException("La vista ($view) no hereda de View."); } // Creo la vista y la ejecuto y le asigno el request a la vista para manipulacion interna if (Settings::getInstance()->get('usingNamespaces')) { $view = '\\Apps\\' . $this->appName . '\\Views\\' . $viewPath . $view; } $v = new $view(); // Ejecuta la funcion y almacena su valor de retorno $returnValue = $v->$method(); // Se construye la respuesta $this->makeResponse($returnValue); }
php
{ "resource": "" }
q253456
ConfigurationCompiler.compileConfiguration
validation
protected function compileConfiguration(Traversable $source, string $target, CompilerContext $context) { $compiler = new StandardCompiler(); $compiler->setSource($source); $compiler->setTarget($target); $compiler->compile(); }
php
{ "resource": "" }
q253457
ConfigurationCompiler.yieldConfigurationFiles
validation
protected function yieldConfigurationFiles(CompilerContext $context): Generator{ $configDirs = []; foreach($context->getProjectSearchPaths(SearchPathAttribute::SEARCH_PATH_USER_CONFIG) as $configDir) { $configDirs[] = (string)$configDir; } $pattern = $this->info[ static::INFO_PATTERN_KEY ]; $defaultFile = $this->info[ static::INFO_CUSTOM_FILENAME_KEY ] ?? NULL; foreach($context->getSourceCodeManager()->yieldSourceFiles($pattern, $configDirs) as $fileName => $file) { if(basename($fileName) == $defaultFile) continue; yield $fileName => $file; } }
php
{ "resource": "" }
q253458
Mistake.register
validation
private function register() { // Don't display any errors since we want this error handler to handle all // errors. Error messages sent to the client will be serialized. ini_set('display_errors', false); // In development however it is beneficiary to display errors. if ($this->displayErrors) { ini_set('display_errors', true); } // Register handlers register_shutdown_function([$this, 'shutdownHandler']); set_error_handler([$this, 'errorHandler']); set_exception_handler([$this, 'exceptionHandler']); }
php
{ "resource": "" }
q253459
Mistake.shutdownHandler
validation
public function shutdownHandler() { $error = error_get_last(); if ($error && $error['type'] & $this->fatalErrors) { $this->errorHandler( $error['type'], $error['message'], $error['file'], $error['line'] ); } }
php
{ "resource": "" }
q253460
Mistake.errorHandler
validation
public function errorHandler($errno, $errstr, $errfile, $errline, array $errcontext = []) { $codes = array( 256 => 'E_USER_ERROR', 512 => 'E_USER_WARNING', 1024 => 'E_USER_NOTICE', 2048 => 'E_STRICT', 4096 => 'E_RECOVERABLE_ERROR', 8192 => 'E_DEPRECATED', 16384 => 'E_USER_DEPRECATED', 8 => 'E_NOTICE', 2 => 'E_WARNING' ); $message = 'Error of level '; if (array_key_exists($errno, $codes)) { $message .= $codes[$errno]; } else { $message .= sprintf('Unknown error level, code of %d passed', $errno); } $message .= sprintf( '. Error message was "%s" in file %s at line %d.', $errstr, $errfile, $errline ); // Log message $this->container['log']->error($message, $errcontext); $this->exceptionHandler(new InternalServerError('An unexpected error occurred.')); }
php
{ "resource": "" }
q253461
Mistake.exceptionHandler
validation
public function exceptionHandler($exception) { // Try and get the latest request, or a new request $request = (isset($this->container['latestRequest']) ? $this->container['latestRequest'] : $this->container['request']); // Try and get the latest response, or a new response $response = (isset($this->container['latestResponse']) ? $this->container['latestResponse'] : $this->container['response']); // Check if exception is an instance of the Phapi Exception. If not, create // an InternalServerError Exception to get better error message to send to // the client. This will also catch PHP 7 ErrorExceptions if (!($exception instanceof Exception)) { $exception = new InternalServerError( $exception->getMessage(), $exception->getCode(), $exception->getPrevious() ); } // Add to log $this->logException($exception); // Prepare response with updated body (error message) // Reset body $response = $response->withBody(new Stream('php://memory', 'w+')); // Set status code $response = $response->withStatus($exception->getStatusCode()); // Set error message $body = $this->prepareErrorBody($exception); // Set body to response $response = $response->withUnserializedBody($body); // Restart pipeline $this->container['pipeline']->prepareErrorQueue(); $this->container['pipeline']($request, $response); }
php
{ "resource": "" }
q253462
Mistake.logException
validation
private function logException(Exception $exception) { // Check if the error message should be logged or not if (in_array($exception->getStatusCode(), $this->doNotLog)) { return; } // Prepare log message $message = sprintf( 'Uncaught exception of type %s thrown in file %s at line %s%s.', get_class($exception), $exception->getFile(), $exception->getLine(), $exception->getMessage() ? sprintf(' with message "%s"', $exception->getMessage()) : '' ); // Log error $this->container['log']->error($message, array( 'exception' => $exception, 'Exception message' => $message, 'Exception line' => $exception->getLine(), 'Exception trace' => $exception->getTraceAsString(), )); }
php
{ "resource": "" }
q253463
Mistake.prepareErrorBody
validation
private function prepareErrorBody(Exception $exception) { // Prepare body $body = [ 'errors' => [] ]; // Set HTTP status code if (!empty($statusCode = $exception->getStatusCode())) { $body['errors']['statusCode'] = $statusCode; } // Check if a description exists if (!empty($description = $exception->getDescription())) { $body['errors']['description'] = $description; } // Check if a message has been defined if (!empty($message = $exception->getMessage())) { $body['errors']['message'] = $message; } // Check if an error code has been defined if (!empty($code = $exception->getCode())) { $body['errors']['code'] = $code; } // Check if a link has been specified if (!empty($link = $exception->getLink())) { $body['errors']['link'] = $link; } return $body; }
php
{ "resource": "" }
q253464
BuilderSearch.get
validation
public function get($keys=[]) { $this->buildIfNotBuilded(); $keys = $keys == [] ? $this->keys() : $keys; if (!$keys) { return $this->builder->get(); } return $this->builder->withColumns($keys)->get($keys); }
php
{ "resource": "" }
q253465
BuilderSearch.paginate
validation
public function paginate($keys=[], $perPage = null) { $this->buildIfNotBuilded(); $keys = $keys == [] ? $this->keys() : $keys; if (!$keys) { return $this->builder->paginate($perPage); } return $this->builder->withColumns($keys)->paginate($perPage); }
php
{ "resource": "" }
q253466
AbstractAPI.retryMiddleware
validation
protected function retryMiddleware() { return Middleware::retry(function ( $retries, RequestInterface $request, ResponseInterface $response = null ) { // Limit the number of retries to 2 if ($retries <= self::$maxRetries && $response && $body = $response->getBody()) { // Retry on server errors if (stripos($body, 'errcode') && (stripos($body, '40001') || stripos($body, '42001'))) { $field = $this->accessToken->getQueryName(); $token = $this->accessToken->getToken(true); $request = $request->withUri($newUri = Uri::withQueryValue($request->getUri(), $field, $token)); Log::debug("Retry with Request Token: {$token}"); Log::debug("Retry with Request Uri: {$newUri}"); return true; } } return false; }); }
php
{ "resource": "" }
q253467
SimpleDOM.insertBeforeSelf
validation
public function insertBeforeSelf(SimpleXMLElement $new) { $tmp = dom_import_simplexml($this); $node = $tmp->ownerDocument->importNode(dom_import_simplexml($new), true); return simplexml_import_dom($this->insertNode($tmp, $node, 'before'), get_class($this)); }
php
{ "resource": "" }
q253468
SimpleDOM.deleteSelf
validation
public function deleteSelf() { $tmp = dom_import_simplexml($this); if ($tmp->isSameNode($tmp->ownerDocument->documentElement)) { throw new BadMethodCallException('deleteSelf() cannot be used to delete the root node'); } $tmp->parentNode->removeChild($tmp); }
php
{ "resource": "" }
q253469
SimpleDOM.removeSelf
validation
public function removeSelf() { $tmp = dom_import_simplexml($this); if ($tmp->isSameNode($tmp->ownerDocument->documentElement)) { throw new BadMethodCallException('removeSelf() cannot be used to remove the root node'); } $node = $tmp->parentNode->removeChild($tmp); return simplexml_import_dom($node, get_class($this)); }
php
{ "resource": "" }
q253470
SimpleDOM.replaceSelf
validation
public function replaceSelf(SimpleXMLElement $new) { $old = dom_import_simplexml($this); $new = $old->ownerDocument->importNode(dom_import_simplexml($new), true); $node = $old->parentNode->replaceChild($new, $old); return simplexml_import_dom($node, get_class($this)); }
php
{ "resource": "" }
q253471
SimpleDOM.deleteNodes
validation
public function deleteNodes($xpath) { if (!is_string($xpath)) { throw new InvalidArgumentException( 'Argument 1 passed to deleteNodes() must be a string, ' . gettype($xpath) . ' given' ); } $nodes = $this->_xpath($xpath); if (isset($nodes[0])) { $tmp = dom_import_simplexml($nodes[0]); if ($tmp->isSameNode($tmp->ownerDocument->documentElement)) { unset($nodes[0]); } } foreach ($nodes as $node) { $node->deleteSelf(); } return count($nodes); }
php
{ "resource": "" }
q253472
SimpleDOM.copyAttributesFrom
validation
public function copyAttributesFrom(SimpleXMLElement $src, $overwrite = true) { $dom = dom_import_simplexml($this); foreach (dom_import_simplexml($src)->attributes as $attr) { if ($overwrite || !$dom->hasAttributeNS($attr->namespaceURI, $attr->nodeName) ) { $dom->setAttributeNS($attr->namespaceURI, $attr->nodeName, $attr->nodeValue); } } return $this; }
php
{ "resource": "" }
q253473
SimpleDOM.cloneChildrenFrom
validation
public function cloneChildrenFrom(SimpleXMLElement $src, $deep = true) { $src = dom_import_simplexml($src); $dst = dom_import_simplexml($this); $doc = $dst->ownerDocument; $fragment = $doc->createDocumentFragment(); foreach ($src->childNodes as $child) { $fragment->appendChild($doc->importNode($child->cloneNode($deep), $deep)); } $dst->appendChild($fragment); return $this; }
php
{ "resource": "" }
q253474
SimpleDOM.moveTo
validation
public function moveTo(SimpleXMLElement $dst) { return simplexml_import_dom(dom_import_simplexml($dst), get_class($this))->appendChild($this->removeSelf()); }
php
{ "resource": "" }
q253475
SimpleDOM.firstOf
validation
public function firstOf($xpath) { $nodes = $this->xpath($xpath); return (isset($nodes[0])) ? $nodes[0] : null; }
php
{ "resource": "" }
q253476
SimpleDOM.insertXML
validation
public function insertXML($xml, $mode = 'append') { $tmp = dom_import_simplexml($this); $fragment = $tmp->ownerDocument->createDocumentFragment(); /** * Disable error reporting */ $use_errors = libxml_use_internal_errors(true); if (!$fragment->appendXML($xml)) { libxml_use_internal_errors($use_errors); throw new InvalidArgumentException(libxml_get_last_error()->message); } libxml_use_internal_errors($use_errors); $this->insertNode($tmp, $fragment, $mode); return $this; }
php
{ "resource": "" }
q253477
SimpleDOM.insertPI
validation
public function insertPI($target, $data = null, $mode = 'before') { $tmp = dom_import_simplexml($this); $doc = $tmp->ownerDocument; if (isset($data)) { if (is_array($data)) { $str = ''; foreach ($data as $k => $v) { $str .= $k . '="' . htmlspecialchars($v) . '" '; } $data = substr($str, 0, -1); } else { $data = (string)$data; } $pi = $doc->createProcessingInstruction($target, $data); } else { $pi = $doc->createProcessingInstruction($target); } if ($pi !== false) { $this->insertNode($tmp, $pi, $mode); } return $this; }
php
{ "resource": "" }
q253478
SimpleDOM.setAttributes
validation
public function setAttributes(array $attr, $ns = null) { $dom = dom_import_simplexml($this); foreach ($attr as $k => $v) { $dom->setAttributeNS($ns, $k, $v); } return $this; }
php
{ "resource": "" }
q253479
SimpleDOM.innerHTML
validation
public function innerHTML() { $dom = dom_import_simplexml($this); $doc = $dom->ownerDocument; $html = ''; foreach ($dom->childNodes as $child) { $html .= ($child instanceof DOMText) ? $child->textContent : $doc->saveXML($child); } return $html; }
php
{ "resource": "" }
q253480
SimpleDOM.innerXML
validation
public function innerXML() { $xml = $this->outerXML(); $pos = 1 + strpos($xml, '>'); $len = strrpos($xml, '<') - $pos; return substr($xml, $pos, $len); }
php
{ "resource": "" }
q253481
SimpleDOM.getElementsByClassName
validation
public function getElementsByClassName($class) { if (strpos($class, '"') !== false || strpos($class, "'") !== false ) { return array(); } $xpath = './/*[contains(concat(" ", @class, " "), " ' . htmlspecialchars($class) . ' ")]'; return $this->xpath($xpath); }
php
{ "resource": "" }
q253482
SimpleDOM.addClass
validation
public function addClass($class) { if (!$this->hasClass($class)) { $current = (string)$this['class']; if ($current !== '' && substr($current, -1) !== ' ' ) { $this['class'] .= ' '; } $this['class'] .= $class; } return $this; }
php
{ "resource": "" }
q253483
SimpleDOM.asPrettyXML
validation
public function asPrettyXML($filepath = null) { /** * Dump and reload this node's XML with LIBXML_NOBLANKS. * * Also import it as a DOMDocument because some older of XSLTProcessor rejected * SimpleXMLElement as a source. */ $xml = dom_import_simplexml( new SimpleXMLElement( $this->asXML() ) ); $xsl = new DOMDocument; $xsl->loadXML( '<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" /> <xsl:template match="text()"> <!-- remove everything that contains only whitespace, with at least one LF --> <xsl:if test="not(normalize-space(.) = \'\' and contains(., \'&#10;\'))"> <xsl:value-of select="."/> </xsl:if> </xsl:template> <xsl:template match="node()"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:apply-templates /> </xsl:copy> </xsl:template> </xsl:stylesheet>' ); $xslt = new XSLTProcessor; $xslt->importStylesheet($xsl); $result = trim($xslt->transformToXML($xml)); if (isset($filepath)) { return (bool)file_put_contents($filepath, $result); } return $result; }
php
{ "resource": "" }
q253484
SimpleDOM.XSLT
validation
public function XSLT($filepath, $use_xslcache = true) { if ($use_xslcache && extension_loaded('xslcache')) { $xslt = new XSLTCache; $xslt->importStylesheet($filepath); } else { $xsl = new DOMDocument; $xsl->load($filepath); $xslt = new XSLTProcessor; $xslt->importStylesheet($xsl); } return $xslt->transformToXML(dom_import_simplexml($this)); }
php
{ "resource": "" }
q253485
SimpleDOM.sortedXPath
validation
public function sortedXPath($xpath) { $nodes = $this->xpath($xpath); $args = func_get_args(); $args[0] =& $nodes; call_user_func_array(array(get_class($this), 'sort'), $args); return $nodes; }
php
{ "resource": "" }
q253486
SimpleDOM.sortChildren
validation
public function sortChildren() { $nodes = $this->removeNodes('*'); $args = func_get_args(); array_unshift($args, null); $args[0] =& $nodes; call_user_func_array(array(get_class($this), 'sort'), $args); foreach ($nodes as $node) { $this->appendChild($node); } return $this; }
php
{ "resource": "" }
q253487
SimpleDOM.sort
validation
static public function sort(array &$nodes) { $args = func_get_args(); unset($args[0]); $sort = array(); $tmp = array(); foreach ($args as $k => $arg) { if (is_string($arg)) { $tmp[$k] = array(); if (preg_match('#^@?[a-z_0-9]+$#Di', $arg)) { if ($arg[0] === '@') { $name = substr($arg, 1); foreach ($nodes as $node) { $tmp[$k][] = (string)$node[$name]; } } else { foreach ($nodes as $node) { $tmp[$k][] = (string)$node->$arg; } } } elseif (preg_match('#^current\\(\\)|text\\(\\)|\\.$#i', $arg)) { /** * If the XPath is current() or text() or . we use this node's textContent */ foreach ($nodes as $node) { $tmp[$k][] = dom_import_simplexml($node)->textContent; } } else { foreach ($nodes as $node) { $_nodes = $node->xpath($arg); $tmp[$k][] = (empty($_nodes)) ? '' : (string)$_nodes[0]; } } } else { $tmp[$k] = $arg; } /** * array_multisort() wants everything to be passed as reference so we have to cheat */ $sort[] =& $tmp[$k]; } $sort[] =& $nodes; call_user_func_array('array_multisort', $sort); }
php
{ "resource": "" }
q253488
SimpleDOM.getNodeByName
validation
public function getNodeByName($strXpath, $strName) { $varResult = $this->xpath($strXpath . "[@name='" . $strName . "']"); if ($varResult !== false) { // Get first element return reset($varResult); } else { return false; } }
php
{ "resource": "" }
q253489
SimpleDOM.xpathSingle
validation
public function xpathSingle($strXpathQuery) { $arrResults = $this->xpath($strXpathQuery); if ($arrResults === false) { //throw new Exception('xpathElement returned an unspecified error on '.$strXpathQuery); return null; } if (is_array($arrResults) && count($arrResults) == 0) { return null; } else { if (count($arrResults) > 1) { throw new Exception( 'xpathSingle expects a single element as result, got ' . count($arrResults) . ' elements instead.' ); } else { return current($arrResults); } } }
php
{ "resource": "" }
q253490
SimpleDOM.xpathByAttribute
validation
public function xpathByAttribute($strXpathQuery, $strIndexAttribute = 'name') { $arrOut = array(); $objResult = $this->xpath($strXpathQuery); foreach ($objResult as $intIndex => $objNode) { $strIndex = (string)$objNode->attributes()->$strIndexAttribute; $arrOut[$strIndex] = $objResult[$intIndex]; } return $arrOut; }
php
{ "resource": "" }
q253491
SimpleDOM.getAttribute
validation
public function getAttribute($strName, $varDefault = false) { if (isset($this->attributes()->$strName) && (((string)$this->attributes()->$strName) !== '')) { return (string)$this->attributes()->$strName; } else { return $varDefault; } }
php
{ "resource": "" }
q253492
SimpleDOM.getNode
validation
public function getNode($strName, $varDefault = false) { $varResult = $this->$strName; if (($varResult !== false) && ((string)$varResult !== '')) { // Get first element return (string)$varResult; } else { return $varDefault; } }
php
{ "resource": "" }
q253493
SimpleDOM.addMissing
validation
public function addMissing($objStructure, &$objElement) { // Set missing attributes foreach ($objStructure->attributes() as $strName => $objAttribute) { if (!isset($objElement->attributes()->$strName)) { $objElement->addAttribute($strName, (string)$objAttribute); } } // Add missing nodes foreach ($objStructure->children() as $strName => $varNode) { if (count($varNode) > 0) { // Due to a PHP bug clone does not work $objNode = $objElement->addChild($strName); $this->addMissing($varNode, $objNode); } else { $objElement->addChild($strName, (string)$varNode); } } }
php
{ "resource": "" }
q253494
SimpleDOM.dump
validation
public function dump() { $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($this->asXML()); return $dom->saveXML(); }
php
{ "resource": "" }
q253495
CompilerContext.addCompiler
validation
public function addCompiler($compiler) { if($compiler instanceof CompilerFactoryInterface || $compiler instanceof CompilerInterface) { $this->compilers[] = $compiler; $this->orderedCompilers = NULL; } else throw new CompilerException("Can only add objects that implement CompilerInterface or CompilerFactoryInterface to context"); }
php
{ "resource": "" }
q253496
CompilerContext.removeCompiler
validation
public function removeCompiler($compiler) { if(($idx = array_search($compiler, $this->compilers)) !== false) { unset($this->compilers[$idx]); $this->orderedCompilers = NULL; } }
php
{ "resource": "" }
q253497
CompilerContext.getSkylineAppDirectory
validation
public function getSkylineAppDirectory(string $dirName) { $name = CC::get([], $dirName); if($name) { return $this->getSkylineAppDataDirectory() . "/$name"; } return NULL; }
php
{ "resource": "" }
q253498
CompilerContext.getProjectSearchPaths
validation
public function getProjectSearchPaths(string $name): array { $srcPaths = $this->getProject()->getAttribute(AttributeInterface::SEARCH_PATHS_ATTR_NAME); if($srcPaths instanceof SearchPathCollection) { return $srcPaths->getSearchPaths($name) ?? []; } return []; }
php
{ "resource": "" }
q253499
CompilerContext.getOrganizedCompilers
validation
public function getOrganizedCompilers() { if(NULL === $this->orderedCompilers) { $depCollection = new DependencyCollection(false); $depCollection->setAcceptsDuplicates(false); foreach($this->compilers as $compiler) { if($compiler instanceof CompilerInterface) { $id = $compiler->getCompilerID(); $deps = $compiler->getDependsOnCompilerIDs(); if($deps) $depCollection->add($id, $compiler, $deps); else $depCollection->add($id, $compiler); } elseif($compiler instanceof CompilerFactoryInterface) { $compiler->registerCompilerInstances($depCollection, $this); } } $this->orderedCompilers = $depCollection->getOrderedElements(); } return $this->orderedCompilers; }
php
{ "resource": "" }