repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php
AbstractRDBMapper.addRelatedObjects
protected function addRelatedObjects(array $objects, $buildDepth=BuildDepth::SINGLE) { // recalculate build depth for the next generation $newBuildDepth = $buildDepth; if ($buildDepth != BuildDepth::SINGLE && $buildDepth != BuildDepth::INFINITE && $buildDepth > 0) { $newBuildDepth = $buildDepth-1; } $loadNextGeneration = (($buildDepth != BuildDepth::SINGLE) && ($buildDepth > 0 || $buildDepth == BuildDepth::INFINITE)); // get dependend objects of this object $relationDescs = $this->getRelations(); foreach($relationDescs as $relationDesc) { $role = $relationDesc->getOtherRole(); $relationId = $role.$relationDesc->getThisRole(); // if the build depth is not satisfied already and the relation is not // currently loading, we load the complete objects and add them if ($loadNextGeneration && !isset($this->loadingRelations[$relationId])) { $this->loadingRelations[$relationId] = true; $relatives = $this->loadRelation($objects, $role, $newBuildDepth); // set the values foreach ($objects as $object) { $oidStr = $object->getOID()->__toString(); $object->setValue($role, isset($relatives[$oidStr]) ? $relatives[$oidStr] : null, true, false); } unset($this->loadingRelations[$relationId]); } // otherwise set the value to not initialized. // the Node will initialize it with the proxies for the relation objects // on first access else { foreach ($objects as $object) { if ($object instanceof Node) { $object->addRelation($role); } } } } }
php
protected function addRelatedObjects(array $objects, $buildDepth=BuildDepth::SINGLE) { // recalculate build depth for the next generation $newBuildDepth = $buildDepth; if ($buildDepth != BuildDepth::SINGLE && $buildDepth != BuildDepth::INFINITE && $buildDepth > 0) { $newBuildDepth = $buildDepth-1; } $loadNextGeneration = (($buildDepth != BuildDepth::SINGLE) && ($buildDepth > 0 || $buildDepth == BuildDepth::INFINITE)); // get dependend objects of this object $relationDescs = $this->getRelations(); foreach($relationDescs as $relationDesc) { $role = $relationDesc->getOtherRole(); $relationId = $role.$relationDesc->getThisRole(); // if the build depth is not satisfied already and the relation is not // currently loading, we load the complete objects and add them if ($loadNextGeneration && !isset($this->loadingRelations[$relationId])) { $this->loadingRelations[$relationId] = true; $relatives = $this->loadRelation($objects, $role, $newBuildDepth); // set the values foreach ($objects as $object) { $oidStr = $object->getOID()->__toString(); $object->setValue($role, isset($relatives[$oidStr]) ? $relatives[$oidStr] : null, true, false); } unset($this->loadingRelations[$relationId]); } // otherwise set the value to not initialized. // the Node will initialize it with the proxies for the relation objects // on first access else { foreach ($objects as $object) { if ($object instanceof Node) { $object->addRelation($role); } } } } }
[ "protected", "function", "addRelatedObjects", "(", "array", "$", "objects", ",", "$", "buildDepth", "=", "BuildDepth", "::", "SINGLE", ")", "{", "// recalculate build depth for the next generation", "$", "newBuildDepth", "=", "$", "buildDepth", ";", "if", "(", "$", ...
Append the child data to a list of object. If the buildDepth does not determine to load a child generation, only the oids of the children will be loaded. @param $objects Array of PersistentObject instances to append the children to @param $buildDepth @see PersistenceFacade::loadObjects()
[ "Append", "the", "child", "data", "to", "a", "list", "of", "object", ".", "If", "the", "buildDepth", "does", "not", "determine", "to", "load", "a", "child", "generation", "only", "the", "oids", "of", "the", "children", "will", "be", "loaded", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L1000-L1037
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php
AbstractRDBMapper.handleDbEvent
public function handleDbEvent($e) { $statement = $e->getParam('statement', null); if ($statement != null) { $this->statements[] = [$statement->getSql(), $statement->getParameterContainer()->getNamedArray()]; } }
php
public function handleDbEvent($e) { $statement = $e->getParam('statement', null); if ($statement != null) { $this->statements[] = [$statement->getSql(), $statement->getParameterContainer()->getNamedArray()]; } }
[ "public", "function", "handleDbEvent", "(", "$", "e", ")", "{", "$", "statement", "=", "$", "e", "->", "getParam", "(", "'statement'", ",", "null", ")", ";", "if", "(", "$", "statement", "!=", "null", ")", "{", "$", "this", "->", "statements", "[", ...
Handle an event triggered from the zend db layer @param $e
[ "Handle", "an", "event", "triggered", "from", "the", "zend", "db", "layer" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L1099-L1104
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php
AbstractRDBMapper.isInTransaction
protected function isInTransaction() { return isset(self::$inTransaction[$this->connId]) && self::$inTransaction[$this->connId] === true; }
php
protected function isInTransaction() { return isset(self::$inTransaction[$this->connId]) && self::$inTransaction[$this->connId] === true; }
[ "protected", "function", "isInTransaction", "(", ")", "{", "return", "isset", "(", "self", "::", "$", "inTransaction", "[", "$", "this", "->", "connId", "]", ")", "&&", "self", "::", "$", "inTransaction", "[", "$", "this", "->", "connId", "]", "===", "...
Check if the connection is currently in a transaction @return Boolean
[ "Check", "if", "the", "connection", "is", "currently", "in", "a", "transaction" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/AbstractRDBMapper.php#L1176-L1178
train
vufind-org/vufindharvest
src/OaiPmh/HarvesterConsoleRunner.php
HarvesterConsoleRunner.getHelp
public function getHelp() { $msg = $this->opts->getUsageMessage(); // Amend the auto-generated help message: $options = "[ options ] [ target ]\n" . "Where [ target ] is the name of a section of the configuration\n" . "specified by the ini option, or a directory to harvest into if\n" . "no .ini file is used. If [ target ] is omitted, all .ini sections\n" . "will be processed. [ options ] may be selected from those below,\n" . "and will override .ini settings where applicable."; $this->write(str_replace('[ options ]', $options, $msg)); }
php
public function getHelp() { $msg = $this->opts->getUsageMessage(); // Amend the auto-generated help message: $options = "[ options ] [ target ]\n" . "Where [ target ] is the name of a section of the configuration\n" . "specified by the ini option, or a directory to harvest into if\n" . "no .ini file is used. If [ target ] is omitted, all .ini sections\n" . "will be processed. [ options ] may be selected from those below,\n" . "and will override .ini settings where applicable."; $this->write(str_replace('[ options ]', $options, $msg)); }
[ "public", "function", "getHelp", "(", ")", "{", "$", "msg", "=", "$", "this", "->", "opts", "->", "getUsageMessage", "(", ")", ";", "// Amend the auto-generated help message:", "$", "options", "=", "\"[ options ] [ target ]\\n\"", ".", "\"Where [ target ] is the name ...
Render help message. @return void
[ "Render", "help", "message", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterConsoleRunner.php#L194-L205
train
vufind-org/vufindharvest
src/OaiPmh/HarvesterConsoleRunner.php
HarvesterConsoleRunner.run
public function run() { // Support help message: if ($this->opts->getOption('h')) { $this->getHelp(); return true; } if (!$allSettings = $this->getSettings()) { return false; } // Loop through all the settings and perform harvests: $processed = $skipped = 0; foreach ($allSettings as $target => $baseSettings) { $settings = $this->updateSettingsWithConsoleOptions($baseSettings); if (empty($target) || empty($settings)) { $skipped++; continue; } $this->writeLine("Processing {$target}..."); try { $this->harvestSingleRepository($target, $settings); } catch (\Exception $e) { $this->writeLine($e->getMessage()); return false; } $processed++; } // All done. if ($processed == 0 && $skipped > 0) { $this->writeLine( 'No valid settings found; ' . 'please set url and metadataPrefix at minimum.' ); return false; } $this->writeLine( "Completed without errors -- {$processed} source(s) processed." ); return true; }
php
public function run() { // Support help message: if ($this->opts->getOption('h')) { $this->getHelp(); return true; } if (!$allSettings = $this->getSettings()) { return false; } // Loop through all the settings and perform harvests: $processed = $skipped = 0; foreach ($allSettings as $target => $baseSettings) { $settings = $this->updateSettingsWithConsoleOptions($baseSettings); if (empty($target) || empty($settings)) { $skipped++; continue; } $this->writeLine("Processing {$target}..."); try { $this->harvestSingleRepository($target, $settings); } catch (\Exception $e) { $this->writeLine($e->getMessage()); return false; } $processed++; } // All done. if ($processed == 0 && $skipped > 0) { $this->writeLine( 'No valid settings found; ' . 'please set url and metadataPrefix at minimum.' ); return false; } $this->writeLine( "Completed without errors -- {$processed} source(s) processed." ); return true; }
[ "public", "function", "run", "(", ")", "{", "// Support help message:", "if", "(", "$", "this", "->", "opts", "->", "getOption", "(", "'h'", ")", ")", "{", "$", "this", "->", "getHelp", "(", ")", ";", "return", "true", ";", "}", "if", "(", "!", "$"...
Run the task and return true on success. @return bool
[ "Run", "the", "task", "and", "return", "true", "on", "success", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterConsoleRunner.php#L212-L254
train
vufind-org/vufindharvest
src/OaiPmh/HarvesterConsoleRunner.php
HarvesterConsoleRunner.getSettings
protected function getSettings() { $ini = $this->opts->getOption('ini'); $argv = $this->opts->getRemainingArgs(); $section = $argv[0] ?? false; if (!$ini && !$section) { $this->writeLine( 'Please specify an .ini file with the --ini flag' . ' or a target directory with the first parameter.' ); return false; } return $ini ? $this->getSettingsFromIni($ini, $section) : [$section => []]; }
php
protected function getSettings() { $ini = $this->opts->getOption('ini'); $argv = $this->opts->getRemainingArgs(); $section = $argv[0] ?? false; if (!$ini && !$section) { $this->writeLine( 'Please specify an .ini file with the --ini flag' . ' or a target directory with the first parameter.' ); return false; } return $ini ? $this->getSettingsFromIni($ini, $section) : [$section => []]; }
[ "protected", "function", "getSettings", "(", ")", "{", "$", "ini", "=", "$", "this", "->", "opts", "->", "getOption", "(", "'ini'", ")", ";", "$", "argv", "=", "$", "this", "->", "opts", "->", "getRemainingArgs", "(", ")", ";", "$", "section", "=", ...
Load the harvest settings. Return false on error. @return array|bool
[ "Load", "the", "harvest", "settings", ".", "Return", "false", "on", "error", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterConsoleRunner.php#L306-L321
train
vufind-org/vufindharvest
src/OaiPmh/HarvesterConsoleRunner.php
HarvesterConsoleRunner.harvestSingleRepository
protected function harvestSingleRepository($target, $settings) { $settings['from'] = $this->opts->getOption('from'); $settings['until'] = $this->opts->getOption('until'); $settings['silent'] = false; $harvest = $this->factory->getHarvester( $target, $this->getHarvestRoot(), $this->getHttpClient(), $settings ); $harvest->launch(); }
php
protected function harvestSingleRepository($target, $settings) { $settings['from'] = $this->opts->getOption('from'); $settings['until'] = $this->opts->getOption('until'); $settings['silent'] = false; $harvest = $this->factory->getHarvester( $target, $this->getHarvestRoot(), $this->getHttpClient(), $settings ); $harvest->launch(); }
[ "protected", "function", "harvestSingleRepository", "(", "$", "target", ",", "$", "settings", ")", "{", "$", "settings", "[", "'from'", "]", "=", "$", "this", "->", "opts", "->", "getOption", "(", "'from'", ")", ";", "$", "settings", "[", "'until'", "]",...
Harvest a single repository. @param string $target Name of repo (used for target directory) @param array $settings Settings for the harvester. @return void @throws \Exception
[ "Harvest", "a", "single", "repository", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterConsoleRunner.php#L332-L344
train
iherwig/wcmf
src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php
DefaultLockHandler.storeLock
protected function storeLock(Lock $lock) { if ($lock->getType() == Lock::TYPE_PESSIMISTIC) { // pessimistic locks must be stored in the database in order // to be seen by other users $lockObj = $this->persistenceFacade->create($this->lockType, BuildDepth::REQUIRED); $lockObj->setValue('objectid', $lock->getObjectId()); $lockObj->setValue('login', $lock->getLogin()); $lockObj->setValue('created', $lock->getCreated()); // save lock immediatly $lockObj->getMapper()->save($lockObj); } // store the lock in the session for faster retrieval $this->addSessionLock($lock); }
php
protected function storeLock(Lock $lock) { if ($lock->getType() == Lock::TYPE_PESSIMISTIC) { // pessimistic locks must be stored in the database in order // to be seen by other users $lockObj = $this->persistenceFacade->create($this->lockType, BuildDepth::REQUIRED); $lockObj->setValue('objectid', $lock->getObjectId()); $lockObj->setValue('login', $lock->getLogin()); $lockObj->setValue('created', $lock->getCreated()); // save lock immediatly $lockObj->getMapper()->save($lockObj); } // store the lock in the session for faster retrieval $this->addSessionLock($lock); }
[ "protected", "function", "storeLock", "(", "Lock", "$", "lock", ")", "{", "if", "(", "$", "lock", "->", "getType", "(", ")", "==", "Lock", "::", "TYPE_PESSIMISTIC", ")", "{", "// pessimistic locks must be stored in the database in order", "// to be seen by other users...
Store the given Lock instance for later retrieval @param $lock Lock instance
[ "Store", "the", "given", "Lock", "instance", "for", "later", "retrieval" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php#L209-L222
train
iherwig/wcmf
src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php
DefaultLockHandler.getSessionLocks
protected function getSessionLocks() { if ($this->session->exist(self::SESSION_VARNAME)) { return $this->session->get(self::SESSION_VARNAME); } return []; }
php
protected function getSessionLocks() { if ($this->session->exist(self::SESSION_VARNAME)) { return $this->session->get(self::SESSION_VARNAME); } return []; }
[ "protected", "function", "getSessionLocks", "(", ")", "{", "if", "(", "$", "this", "->", "session", "->", "exist", "(", "self", "::", "SESSION_VARNAME", ")", ")", "{", "return", "$", "this", "->", "session", "->", "get", "(", "self", "::", "SESSION_VARNA...
Get the Lock instances stored in the session @return Associative array with the serialized ObjectId instances as keys and the Lock instances as values
[ "Get", "the", "Lock", "instances", "stored", "in", "the", "session" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php#L237-L242
train
iherwig/wcmf
src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php
DefaultLockHandler.addSessionLock
protected function addSessionLock(Lock $lock) { $locks = $this->getSessionLocks(); $locks[$lock->getObjectId()->__toString()] = $lock; $this->session->set(self::SESSION_VARNAME, $locks); }
php
protected function addSessionLock(Lock $lock) { $locks = $this->getSessionLocks(); $locks[$lock->getObjectId()->__toString()] = $lock; $this->session->set(self::SESSION_VARNAME, $locks); }
[ "protected", "function", "addSessionLock", "(", "Lock", "$", "lock", ")", "{", "$", "locks", "=", "$", "this", "->", "getSessionLocks", "(", ")", ";", "$", "locks", "[", "$", "lock", "->", "getObjectId", "(", ")", "->", "__toString", "(", ")", "]", "...
Add a given Lock instance to the session @param $lock Lock instance
[ "Add", "a", "given", "Lock", "instance", "to", "the", "session" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php#L248-L252
train
iherwig/wcmf
src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php
DefaultLockHandler.removeSessionLock
protected function removeSessionLock(ObjectId $oid, $type) { $locks = $this->getSessionLocks(); if (isset($locks[$oid->__toString()])) { $lock = $locks[$oid->__toString()]; if ($type == null || $type != null && $lock->getType() == $type) { unset($locks[$oid->__toString()]); $this->session->set(self::SESSION_VARNAME, $locks); } } }
php
protected function removeSessionLock(ObjectId $oid, $type) { $locks = $this->getSessionLocks(); if (isset($locks[$oid->__toString()])) { $lock = $locks[$oid->__toString()]; if ($type == null || $type != null && $lock->getType() == $type) { unset($locks[$oid->__toString()]); $this->session->set(self::SESSION_VARNAME, $locks); } } }
[ "protected", "function", "removeSessionLock", "(", "ObjectId", "$", "oid", ",", "$", "type", ")", "{", "$", "locks", "=", "$", "this", "->", "getSessionLocks", "(", ")", ";", "if", "(", "isset", "(", "$", "locks", "[", "$", "oid", "->", "__toString", ...
Remove a given Lock instance from the session @param $oid The locked oid @param $type One of the Lock::Type constants or null for all types (default: _null_)
[ "Remove", "a", "given", "Lock", "instance", "from", "the", "session" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/concurrency/impl/DefaultLockHandler.php#L259-L268
train
iherwig/wcmf
src/wcmf/lib/presentation/format/impl/AbstractFormat.php
AbstractFormat.getNode
protected function getNode(ObjectId $oid) { $oidStr = $oid->__toString(); if (!isset($this->deserializedNodes[$oidStr])) { $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $type = $oid->getType(); if ($persistenceFacade->isKnownType($type)) { // don't create all values by default (-> don't use PersistenceFacade::create() directly, just for determining the class) $class = get_class($persistenceFacade->create($type, BuildDepth::SINGLE)); $node = new $class; } else { $node = new Node($type); } $node->setOID($oid); $this->deserializedNodes[$oidStr] = $node; } return $this->deserializedNodes[$oidStr]; }
php
protected function getNode(ObjectId $oid) { $oidStr = $oid->__toString(); if (!isset($this->deserializedNodes[$oidStr])) { $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $type = $oid->getType(); if ($persistenceFacade->isKnownType($type)) { // don't create all values by default (-> don't use PersistenceFacade::create() directly, just for determining the class) $class = get_class($persistenceFacade->create($type, BuildDepth::SINGLE)); $node = new $class; } else { $node = new Node($type); } $node->setOID($oid); $this->deserializedNodes[$oidStr] = $node; } return $this->deserializedNodes[$oidStr]; }
[ "protected", "function", "getNode", "(", "ObjectId", "$", "oid", ")", "{", "$", "oidStr", "=", "$", "oid", "->", "__toString", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "deserializedNodes", "[", "$", "oidStr", "]", ")", ")", "...
Get a node with the given oid to deserialize values from form fields into it. The method ensures that there is only one instance per oid. @param $oid The oid @return Node
[ "Get", "a", "node", "with", "the", "given", "oid", "to", "deserialize", "values", "from", "form", "fields", "into", "it", ".", "The", "method", "ensures", "that", "there", "is", "only", "one", "instance", "per", "oid", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/AbstractFormat.php#L121-L138
train
iherwig/wcmf
src/wcmf/lib/core/impl/MonologFileLogger.php
MonologFileLogger.prepareMessage
private function prepareMessage($message) { return is_string($message) ? $message : (is_object($message) && method_exists($message, '__toString') ? $message->__toString() : StringUtil::getDump($message)); }
php
private function prepareMessage($message) { return is_string($message) ? $message : (is_object($message) && method_exists($message, '__toString') ? $message->__toString() : StringUtil::getDump($message)); }
[ "private", "function", "prepareMessage", "(", "$", "message", ")", "{", "return", "is_string", "(", "$", "message", ")", "?", "$", "message", ":", "(", "is_object", "(", "$", "message", ")", "&&", "method_exists", "(", "$", "message", ",", "'__toString'", ...
Prepare a message to be used with the internal logger @param $message @return String
[ "Prepare", "a", "message", "to", "be", "used", "with", "the", "internal", "logger" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/impl/MonologFileLogger.php#L191-L195
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.filter
public static function filter(array $nodeList, ObjectId $oid=null, $type=null, $values=null, $properties=null, $useRegExp=true) { $returnArray = []; for ($i=0, $count=sizeof($nodeList); $i<$count; $i++) { $curNode = $nodeList[$i]; if ($curNode instanceof PersistentObject) { $match = true; // check oid if ($oid != null && $curNode->getOID() != $oid) { $match = false; } // check type if ($type != null) { $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $fqType = $persistenceFacade->getFullyQualifiedType($type); if ($fqType != null && $curNode->getType() != $fqType) { $match = false; } } // check values if ($values != null && is_array($values)) { foreach($values as $key => $value) { $nodeValue = $curNode->getValue($key); if ($useRegExp && !preg_match("/".$value."/m", $nodeValue) || !$useRegExp && $value != $nodeValue) { $match = false; break; } } } // check properties if ($properties != null && is_array($properties)) { foreach($properties as $key => $value) { $nodeProperty = $curNode->getProperty($key); if ($useRegExp && !preg_match("/".$value."/m", $nodeProperty) || !$useRegExp && $value != $nodeProperty) { $match = false; break; } } } if ($match) { $returnArray[] = $curNode; } } else { self::$logger->warn(StringUtil::getDump($curNode)." found, where a PersistentObject was expected.\n".ErrorHandler::getStackTrace(), __CLASS__); } } return $returnArray; }
php
public static function filter(array $nodeList, ObjectId $oid=null, $type=null, $values=null, $properties=null, $useRegExp=true) { $returnArray = []; for ($i=0, $count=sizeof($nodeList); $i<$count; $i++) { $curNode = $nodeList[$i]; if ($curNode instanceof PersistentObject) { $match = true; // check oid if ($oid != null && $curNode->getOID() != $oid) { $match = false; } // check type if ($type != null) { $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $fqType = $persistenceFacade->getFullyQualifiedType($type); if ($fqType != null && $curNode->getType() != $fqType) { $match = false; } } // check values if ($values != null && is_array($values)) { foreach($values as $key => $value) { $nodeValue = $curNode->getValue($key); if ($useRegExp && !preg_match("/".$value."/m", $nodeValue) || !$useRegExp && $value != $nodeValue) { $match = false; break; } } } // check properties if ($properties != null && is_array($properties)) { foreach($properties as $key => $value) { $nodeProperty = $curNode->getProperty($key); if ($useRegExp && !preg_match("/".$value."/m", $nodeProperty) || !$useRegExp && $value != $nodeProperty) { $match = false; break; } } } if ($match) { $returnArray[] = $curNode; } } else { self::$logger->warn(StringUtil::getDump($curNode)." found, where a PersistentObject was expected.\n".ErrorHandler::getStackTrace(), __CLASS__); } } return $returnArray; }
[ "public", "static", "function", "filter", "(", "array", "$", "nodeList", ",", "ObjectId", "$", "oid", "=", "null", ",", "$", "type", "=", "null", ",", "$", "values", "=", "null", ",", "$", "properties", "=", "null", ",", "$", "useRegExp", "=", "true"...
Get Nodes that match given conditions from a list. @param $nodeList An array of nodes to filter or a single Node. @param $oid The object id that the Nodes should match (optional, default: _null_) @param $type The type that the Nodes should match (either fully qualified or simple, if not ambiguous) (optional, default: _null_) @param $values An associative array holding key value pairs that the Node values should match (values are interpreted as regular expression, optional, default: _null_) @param $properties An associative array holding key value pairs that the Node properties should match (values are interpreted as regular expression, optional, default: _null_) @param $useRegExp Boolean whether to interpret the given values/properties as regular expressions or not (default: _true_) @return An Array holding references to the Nodes that matched.
[ "Get", "Nodes", "that", "match", "given", "conditions", "from", "a", "list", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L185-L237
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getRelationNames
public function getRelationNames() { $result = []; $relations = $this->getRelations(); foreach ($relations as $curRelation) { $result[] = $curRelation->getOtherRole(); } return $result; }
php
public function getRelationNames() { $result = []; $relations = $this->getRelations(); foreach ($relations as $curRelation) { $result[] = $curRelation->getOtherRole(); } return $result; }
[ "public", "function", "getRelationNames", "(", ")", "{", "$", "result", "=", "[", "]", ";", "$", "relations", "=", "$", "this", "->", "getRelations", "(", ")", ";", "foreach", "(", "$", "relations", "as", "$", "curRelation", ")", "{", "$", "result", ...
Get the names of all relations. @return An array of relation names.
[ "Get", "the", "names", "of", "all", "relations", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L305-L312
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.addNode
public function addNode(PersistentObject $other, $role=null, $forceSet=false, $trackChange=true, $updateOtherSide=true) { $mapper = $this->getMapper(); // set role if missing if ($role == null) { $otherType = $other->getType(); $relations = $mapper->getRelationsByType($otherType); $role = (sizeof($relations) > 0) ? $relations[0]->getOtherRole() : $otherType; } // get the relation description $relDesc = $mapper->getRelation($role); $value = $other; $oldValue = parent::getValue($role); $addedNodes = []; // this array contains the other node or nothing if (!$relDesc || $relDesc->isMultiValued()) { // check multiplicity if multivalued $maxMultiplicity = $relDesc->getOtherMaxMultiplicity(); if ($relDesc->isMultiValued() && !($maxMultiplicity == 'unbounded') && sizeof(oldValue) >= $maxMultiplicity) { throw new IllegalArgumentException("Maximum number of related objects exceeded: ".$role." (".(sizeof(oldValue)+1)." > ".$maxMultiplicity.")"); } // make sure that the value is an array if multivalued $mergeResult = self::mergeObjectLists($oldValue, [$value]); $value = $mergeResult['result']; $addedNodes = $mergeResult['added']; } elseif ($oldValue == null && $value != null || $oldValue->getOID()->__toString() != $value->getOID()->__toString()) { $addedNodes[] = $value; } $result1 = sizeof($addedNodes) > 0 && parent::setValue($role, $value, $forceSet, $trackChange); // remember the addition if (sizeof($addedNodes) > 0) { if (!isset($this->addedNodes[$role])) { $this->addedNodes[$role] = []; } $this->addedNodes[$role][] = $other; } // propagate add action to the other object $result2 = true; if ($updateOtherSide) { $thisRole = $relDesc ? $relDesc->getThisRole() : null; $result2 = $other->addNode($this, $thisRole, $forceSet, $trackChange, false); } return ($result1 & $result2); }
php
public function addNode(PersistentObject $other, $role=null, $forceSet=false, $trackChange=true, $updateOtherSide=true) { $mapper = $this->getMapper(); // set role if missing if ($role == null) { $otherType = $other->getType(); $relations = $mapper->getRelationsByType($otherType); $role = (sizeof($relations) > 0) ? $relations[0]->getOtherRole() : $otherType; } // get the relation description $relDesc = $mapper->getRelation($role); $value = $other; $oldValue = parent::getValue($role); $addedNodes = []; // this array contains the other node or nothing if (!$relDesc || $relDesc->isMultiValued()) { // check multiplicity if multivalued $maxMultiplicity = $relDesc->getOtherMaxMultiplicity(); if ($relDesc->isMultiValued() && !($maxMultiplicity == 'unbounded') && sizeof(oldValue) >= $maxMultiplicity) { throw new IllegalArgumentException("Maximum number of related objects exceeded: ".$role." (".(sizeof(oldValue)+1)." > ".$maxMultiplicity.")"); } // make sure that the value is an array if multivalued $mergeResult = self::mergeObjectLists($oldValue, [$value]); $value = $mergeResult['result']; $addedNodes = $mergeResult['added']; } elseif ($oldValue == null && $value != null || $oldValue->getOID()->__toString() != $value->getOID()->__toString()) { $addedNodes[] = $value; } $result1 = sizeof($addedNodes) > 0 && parent::setValue($role, $value, $forceSet, $trackChange); // remember the addition if (sizeof($addedNodes) > 0) { if (!isset($this->addedNodes[$role])) { $this->addedNodes[$role] = []; } $this->addedNodes[$role][] = $other; } // propagate add action to the other object $result2 = true; if ($updateOtherSide) { $thisRole = $relDesc ? $relDesc->getThisRole() : null; $result2 = $other->addNode($this, $thisRole, $forceSet, $trackChange, false); } return ($result1 & $result2); }
[ "public", "function", "addNode", "(", "PersistentObject", "$", "other", ",", "$", "role", "=", "null", ",", "$", "forceSet", "=", "false", ",", "$", "trackChange", "=", "true", ",", "$", "updateOtherSide", "=", "true", ")", "{", "$", "mapper", "=", "$"...
Add a Node to the given relation. Delegates to setValue internally. @param $other PersistentObject @param $role The role of the Node in the created relation. If null, the role will be the Node's simple type (without namespace) (default: _null_) @param $forceSet @see PersistentObject::setValue() @param $trackChange @see PersistentObject::setValue() @param $updateOtherSide Boolean whether to update also the other side of the relation (default: _true_) @return Boolean whether the operation succeeds or not
[ "Add", "a", "Node", "to", "the", "given", "relation", ".", "Delegates", "to", "setValue", "internally", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L324-L373
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.deleteNode
public function deleteNode(PersistentObject $other, $role=null, $updateOtherSide=true) { $mapper = $this->getMapper(); // set role if missing if ($role == null) { $otherType = $other->getType(); $relations = $mapper->getRelationsByType($otherType); $role = (sizeof($relations) > 0) ? $relations[0]->getOtherRole() : $otherType; } $nodes = $this->getValue($role); if (empty($nodes)) { // nothing to delete return; } // get the relation description $relDesc = $mapper->getRelation($role); $oid = $other->getOID(); if (is_array($nodes)) { // multi valued relation for($i=0, $count=sizeof($nodes); $i<$count; $i++) { if ($nodes[$i]->getOID() == $oid) { // remove child array_splice($nodes, $i, 1); break; } } } else { // single valued relation if ($nodes->getOID() == $oid) { // remove child $nodes = null; } } parent::setValue($role, $nodes); // remember the deletion if (!isset($this->deletedNodes[$role])) { $this->deletedNodes[$role] = []; } $this->deletedNodes[$role][] = $other->getOID(); $this->setState(PersistentOBject::STATE_DIRTY); // propagate add action to the other object if ($updateOtherSide) { $thisRole = $relDesc ? $relDesc->getThisRole() : null; $other->deleteNode($this, $thisRole, false); } }
php
public function deleteNode(PersistentObject $other, $role=null, $updateOtherSide=true) { $mapper = $this->getMapper(); // set role if missing if ($role == null) { $otherType = $other->getType(); $relations = $mapper->getRelationsByType($otherType); $role = (sizeof($relations) > 0) ? $relations[0]->getOtherRole() : $otherType; } $nodes = $this->getValue($role); if (empty($nodes)) { // nothing to delete return; } // get the relation description $relDesc = $mapper->getRelation($role); $oid = $other->getOID(); if (is_array($nodes)) { // multi valued relation for($i=0, $count=sizeof($nodes); $i<$count; $i++) { if ($nodes[$i]->getOID() == $oid) { // remove child array_splice($nodes, $i, 1); break; } } } else { // single valued relation if ($nodes->getOID() == $oid) { // remove child $nodes = null; } } parent::setValue($role, $nodes); // remember the deletion if (!isset($this->deletedNodes[$role])) { $this->deletedNodes[$role] = []; } $this->deletedNodes[$role][] = $other->getOID(); $this->setState(PersistentOBject::STATE_DIRTY); // propagate add action to the other object if ($updateOtherSide) { $thisRole = $relDesc ? $relDesc->getThisRole() : null; $other->deleteNode($this, $thisRole, false); } }
[ "public", "function", "deleteNode", "(", "PersistentObject", "$", "other", ",", "$", "role", "=", "null", ",", "$", "updateOtherSide", "=", "true", ")", "{", "$", "mapper", "=", "$", "this", "->", "getMapper", "(", ")", ";", "// set role if missing", "if",...
Delete a Node from the given relation. @param $other The Node to delete. @param $role The role of the Node. If null, the role is the Node's type (without namespace) (default: _null_) @param $updateOtherSide Boolean whether to update also the other side of the relation (default: _true_)
[ "Delete", "a", "Node", "from", "the", "given", "relation", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L391-L443
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.setNodeOrder
public function setNodeOrder(array $orderedList, array $movedList=null, $role=null) { $this->orderedNodes = [ 'ordered' => $orderedList, 'moved' => $movedList, 'role' => $role ]; $this->setState(PersistentOBject::STATE_DIRTY); }
php
public function setNodeOrder(array $orderedList, array $movedList=null, $role=null) { $this->orderedNodes = [ 'ordered' => $orderedList, 'moved' => $movedList, 'role' => $role ]; $this->setState(PersistentOBject::STATE_DIRTY); }
[ "public", "function", "setNodeOrder", "(", "array", "$", "orderedList", ",", "array", "$", "movedList", "=", "null", ",", "$", "role", "=", "null", ")", "{", "$", "this", "->", "orderedNodes", "=", "[", "'ordered'", "=>", "$", "orderedList", ",", "'moved...
Define the order of related Node instances. The mapper is responsible for persisting the order of the given Node instances in relation to this Node. @note Note instances, that are not explicitly sortable by a sortkey (@see PersistenceMapper::getDefaultOrder()) will be ignored. If a given Node instance is not related to this Node yet, an exception will be thrown. Any not persisted definition of a previous call will be overwritten @param $orderedList Array of ordered Node instances @param $movedList Array of repositioned Node instances (optional, improves performance) @param $role Role name of the Node instances (optional)
[ "Define", "the", "order", "of", "related", "Node", "instances", ".", "The", "mapper", "is", "responsible", "for", "persisting", "the", "order", "of", "the", "given", "Node", "instances", "in", "relation", "to", "this", "Node", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L466-L473
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.loadChildren
public function loadChildren($role=null, $buildDepth=BuildDepth::SINGLE) { if ($role != null) { $this->loadRelations([$role], $buildDepth); } else { $this->loadRelations(array_keys($this->getPossibleChildren()), $buildDepth); } }
php
public function loadChildren($role=null, $buildDepth=BuildDepth::SINGLE) { if ($role != null) { $this->loadRelations([$role], $buildDepth); } else { $this->loadRelations(array_keys($this->getPossibleChildren()), $buildDepth); } }
[ "public", "function", "loadChildren", "(", "$", "role", "=", "null", ",", "$", "buildDepth", "=", "BuildDepth", "::", "SINGLE", ")", "{", "if", "(", "$", "role", "!=", "null", ")", "{", "$", "this", "->", "loadRelations", "(", "[", "$", "role", "]", ...
Load the children of a given role and add them. If all children should be loaded, set the role parameter to null. @param $role The role of children to load (maybe null, to load all children) (default: _null_) @param $buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to build (default: _BuildDepth::SINGLE_)
[ "Load", "the", "children", "of", "a", "given", "role", "and", "add", "them", ".", "If", "all", "children", "should", "be", "loaded", "set", "the", "role", "parameter", "to", "null", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L491-L498
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getFirstChild
public function getFirstChild($role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { $children = $this->getChildrenEx(null, $role, $type, $values, $properties, $useRegExp); if (sizeof($children) > 0) { return $children[0]; } else { return null; } }
php
public function getFirstChild($role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { $children = $this->getChildrenEx(null, $role, $type, $values, $properties, $useRegExp); if (sizeof($children) > 0) { return $children[0]; } else { return null; } }
[ "public", "function", "getFirstChild", "(", "$", "role", "=", "null", ",", "$", "type", "=", "null", ",", "$", "values", "=", "null", ",", "$", "properties", "=", "null", ",", "$", "useRegExp", "=", "true", ")", "{", "$", "children", "=", "$", "thi...
Get the first child that matches given conditions. @param $role The role that the child should match (optional, default: _null_). @param $type The type that the child should match (either fully qualified or simple, if not ambiguous) (optional, default: _null_). @param $values An associative array holding key value pairs that the child values should match (optional, default: _null_). @param $properties An associative array holding key value pairs that the child properties should match (optional, default: _null_). @param $useRegExp Boolean whether to interpret the given values/properties as regular expressions or not (default: _true_) @return Node instance or null.
[ "Get", "the", "first", "child", "that", "matches", "given", "conditions", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L519-L527
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getChildrenEx
public function getChildrenEx(ObjectId $oid=null, $role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { if ($role != null) { // nodes of a given role are requested // make sure it is a child role $childRoles = $this->getPossibleChildren(); if (!isset($childRoles[$role])) { throw new IllegalArgumentException("No child role defined with name: ".$role); } // we are only looking for nodes that are in memory already $nodes = parent::getValue($role); if (!is_array($nodes)) { $nodes = [$nodes]; } // sort out proxies $children = []; foreach($nodes as $curNode) { if ($curNode instanceof PersistentObject) { $children[] = $curNode; } } return self::filter($children, $oid, $type, $values, $properties, $useRegExp); } else { return self::filter($this->getChildren(), $oid, $type, $values, $properties, $useRegExp); } }
php
public function getChildrenEx(ObjectId $oid=null, $role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { if ($role != null) { // nodes of a given role are requested // make sure it is a child role $childRoles = $this->getPossibleChildren(); if (!isset($childRoles[$role])) { throw new IllegalArgumentException("No child role defined with name: ".$role); } // we are only looking for nodes that are in memory already $nodes = parent::getValue($role); if (!is_array($nodes)) { $nodes = [$nodes]; } // sort out proxies $children = []; foreach($nodes as $curNode) { if ($curNode instanceof PersistentObject) { $children[] = $curNode; } } return self::filter($children, $oid, $type, $values, $properties, $useRegExp); } else { return self::filter($this->getChildren(), $oid, $type, $values, $properties, $useRegExp); } }
[ "public", "function", "getChildrenEx", "(", "ObjectId", "$", "oid", "=", "null", ",", "$", "role", "=", "null", ",", "$", "type", "=", "null", ",", "$", "values", "=", "null", ",", "$", "properties", "=", "null", ",", "$", "useRegExp", "=", "true", ...
Get the children that match given conditions. @note This method will only return objects that are already loaded, to get all objects in the given relation (including proxies), use the Node::getValue() method and filter the returned list afterwards. @param $oid The object id that the children should match (optional, default: _null_). @param $role The role that the children should match (optional, default: _null_). @param $type The type that the children should match (either fully qualified or simple, if not ambiguous) (optional, default: _null_). @param $values An associative array holding key value pairs that the children values should match (optional, default: _null_). @param $properties An associative array holding key value pairs that the children properties should match (optional, default: _null_). @param $useRegExp Boolean whether to interpret the given values/properties as regular expressions or not (default: _true_) @return Array containing children Nodes that matched (proxies not included).
[ "Get", "the", "children", "that", "match", "given", "conditions", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L552-L578
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.loadParents
public function loadParents($role=null, $buildDepth=BuildDepth::SINGLE) { if ($role != null) { $this->loadRelations([$role], $buildDepth); } else { $this->loadRelations(array_keys($this->getPossibleParents()), $buildDepth); } }
php
public function loadParents($role=null, $buildDepth=BuildDepth::SINGLE) { if ($role != null) { $this->loadRelations([$role], $buildDepth); } else { $this->loadRelations(array_keys($this->getPossibleParents()), $buildDepth); } }
[ "public", "function", "loadParents", "(", "$", "role", "=", "null", ",", "$", "buildDepth", "=", "BuildDepth", "::", "SINGLE", ")", "{", "if", "(", "$", "role", "!=", "null", ")", "{", "$", "this", "->", "loadRelations", "(", "[", "$", "role", "]", ...
Load the parents of a given role and add them. If all parents should be loaded, set the role parameter to null. @param $role The role of parents to load (maybe null, to load all parents) (default: _null_) @param $buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to build (default: _BuildDepth::SINGLE_)
[ "Load", "the", "parents", "of", "a", "given", "role", "and", "add", "them", ".", "If", "all", "parents", "should", "be", "loaded", "set", "the", "role", "parameter", "to", "null", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L600-L607
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getFirstParent
public function getFirstParent($role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { $parents = $this->getParentsEx(null, $role, $type, $values, $properties, $useRegExp); if (sizeof($parents) > 0) { return $parents[0]; } else { return null; } }
php
public function getFirstParent($role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { $parents = $this->getParentsEx(null, $role, $type, $values, $properties, $useRegExp); if (sizeof($parents) > 0) { return $parents[0]; } else { return null; } }
[ "public", "function", "getFirstParent", "(", "$", "role", "=", "null", ",", "$", "type", "=", "null", ",", "$", "values", "=", "null", ",", "$", "properties", "=", "null", ",", "$", "useRegExp", "=", "true", ")", "{", "$", "parents", "=", "$", "thi...
Get the first parent that matches given conditions. @param $role The role that the parent should match (optional, default: _null_). @param $type The type that the parent should match (either fully qualified or simple, if not ambiguous) (optional, default: _null_). @param $values An associative array holding key value pairs that the parent values should match (optional, default: _null_). @param $properties An associative array holding key value pairs that the parent properties should match (optional, default: _null_). @param $useRegExp Boolean whether to interpret the given values/properties as regular expressions or not (default: _true_) @return Node instance or null.
[ "Get", "the", "first", "parent", "that", "matches", "given", "conditions", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L643-L652
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getParentsEx
public function getParentsEx(ObjectId $oid=null, $role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { if ($role != null) { // nodes of a given role are requested // make sure it is a parent role $parentRoles = $this->getPossibleParents(); if (!isset($parentRoles[$role])) { throw new IllegalArgumentException("No parent role defined with name: ".$role); } // we are only looking for nodes that are in memory already $nodes = parent::getValue($role); if (!is_array($nodes)) { $nodes = [$nodes]; } // sort out proxies $parents = []; foreach($nodes as $curNode) { if ($curNode instanceof PersistentObject) { $parents[] = $curNode; } } return self::filter($parents, $oid, $type, $values, $properties, $useRegExp); } else { return self::filter($this->getParents(), $oid, $type, $values, $properties, $useRegExp); } }
php
public function getParentsEx(ObjectId $oid=null, $role=null, $type=null, $values=null, $properties=null, $useRegExp=true) { if ($role != null) { // nodes of a given role are requested // make sure it is a parent role $parentRoles = $this->getPossibleParents(); if (!isset($parentRoles[$role])) { throw new IllegalArgumentException("No parent role defined with name: ".$role); } // we are only looking for nodes that are in memory already $nodes = parent::getValue($role); if (!is_array($nodes)) { $nodes = [$nodes]; } // sort out proxies $parents = []; foreach($nodes as $curNode) { if ($curNode instanceof PersistentObject) { $parents[] = $curNode; } } return self::filter($parents, $oid, $type, $values, $properties, $useRegExp); } else { return self::filter($this->getParents(), $oid, $type, $values, $properties, $useRegExp); } }
[ "public", "function", "getParentsEx", "(", "ObjectId", "$", "oid", "=", "null", ",", "$", "role", "=", "null", ",", "$", "type", "=", "null", ",", "$", "values", "=", "null", ",", "$", "properties", "=", "null", ",", "$", "useRegExp", "=", "true", ...
Get the parents that match given conditions. @note This method will only return objects that are already loaded, to get all objects in the given relation (including proxies), use the Node::getValue() method and filter the returned list afterwards. @param $oid The object id that the parent should match (optional, default: _null_). @param $role The role that the parents should match (optional, default: _null_). @param $type The type that the parents should match (either fully qualified or simple, if not ambiguous) (optional, default: _null_). @param $values An associative array holding key value pairs that the parent values should match (optional, default: _null_). @param $properties An associative array holding key value pairs that the parent properties should match (optional, default: _null_). @param $useRegExp Boolean whether to interpret the given values/properties as regular expressions or not (default: _true_) @return Array containing parent Nodes that matched (proxies not included).
[ "Get", "the", "parents", "that", "match", "given", "conditions", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L677-L703
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getNodeRelation
public function getNodeRelation($object) { $relations = $this->getRelations(); foreach ($relations as $curRelation) { $curRelatives = parent::getValue($curRelation->getOtherRole()); if ($curRelatives instanceof Node && $curRelatives->getOID() == $object->getOID()) { return $curRelation; } elseif (is_array($curRelatives)) { foreach ($curRelatives as $curRelative) { if ($curRelative->getOID() == $object->getOID()) { return $curRelation; } } } } return null; }
php
public function getNodeRelation($object) { $relations = $this->getRelations(); foreach ($relations as $curRelation) { $curRelatives = parent::getValue($curRelation->getOtherRole()); if ($curRelatives instanceof Node && $curRelatives->getOID() == $object->getOID()) { return $curRelation; } elseif (is_array($curRelatives)) { foreach ($curRelatives as $curRelative) { if ($curRelative->getOID() == $object->getOID()) { return $curRelation; } } } } return null; }
[ "public", "function", "getNodeRelation", "(", "$", "object", ")", "{", "$", "relations", "=", "$", "this", "->", "getRelations", "(", ")", ";", "foreach", "(", "$", "relations", "as", "$", "curRelation", ")", "{", "$", "curRelatives", "=", "parent", "::"...
Get the relation description for a given node. @param $object PersistentObject instance to look for @return RelationDescription instance or null, if the Node is not related
[ "Get", "the", "relation", "description", "for", "a", "given", "node", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L723-L739
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.loadRelations
protected function loadRelations(array $roles, $buildDepth=BuildDepth::SINGLE) { $oldState = $this->getState(); foreach ($roles as $curRole) { if (isset($this->relationStates[$curRole]) && $this->relationStates[$curRole] != self::RELATION_STATE_LOADED) { $relatives = []; // resolve proxies if the relation is already initialized if ($this->relationStates[$curRole] == self::RELATION_STATE_INITIALIZED) { $proxies = $this->getValue($curRole); if (is_array($proxies)) { foreach ($proxies as $curRelative) { if ($curRelative instanceof PersistentObjectProxy) { // resolve proxies $curRelative->resolve($buildDepth); $relatives[] = $curRelative->getRealSubject(); } else { $relatives[] = $curRelative; } } } } // otherwise load the objects directly else { $mapper = $this->getMapper(); $allRelatives = $mapper->loadRelation([$this], $curRole, $buildDepth); $oidStr = $this->getOID()->__toString(); $relatives = isset($allRelatives[$oidStr]) ? $allRelatives[$oidStr] : null; $relDesc = $mapper->getRelation($curRole); if (!$relDesc->isMultiValued()) { $relatives = $relatives != null ? $relatives[0] : null; } } $this->setValueInternal($curRole, $relatives); $this->relationStates[$curRole] = self::RELATION_STATE_LOADED; } } $this->setState($oldState); }
php
protected function loadRelations(array $roles, $buildDepth=BuildDepth::SINGLE) { $oldState = $this->getState(); foreach ($roles as $curRole) { if (isset($this->relationStates[$curRole]) && $this->relationStates[$curRole] != self::RELATION_STATE_LOADED) { $relatives = []; // resolve proxies if the relation is already initialized if ($this->relationStates[$curRole] == self::RELATION_STATE_INITIALIZED) { $proxies = $this->getValue($curRole); if (is_array($proxies)) { foreach ($proxies as $curRelative) { if ($curRelative instanceof PersistentObjectProxy) { // resolve proxies $curRelative->resolve($buildDepth); $relatives[] = $curRelative->getRealSubject(); } else { $relatives[] = $curRelative; } } } } // otherwise load the objects directly else { $mapper = $this->getMapper(); $allRelatives = $mapper->loadRelation([$this], $curRole, $buildDepth); $oidStr = $this->getOID()->__toString(); $relatives = isset($allRelatives[$oidStr]) ? $allRelatives[$oidStr] : null; $relDesc = $mapper->getRelation($curRole); if (!$relDesc->isMultiValued()) { $relatives = $relatives != null ? $relatives[0] : null; } } $this->setValueInternal($curRole, $relatives); $this->relationStates[$curRole] = self::RELATION_STATE_LOADED; } } $this->setState($oldState); }
[ "protected", "function", "loadRelations", "(", "array", "$", "roles", ",", "$", "buildDepth", "=", "BuildDepth", "::", "SINGLE", ")", "{", "$", "oldState", "=", "$", "this", "->", "getState", "(", ")", ";", "foreach", "(", "$", "roles", "as", "$", "cur...
Load all objects in the given set of relations @param $roles An array of relation (=role) names @param $buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to build (default: _BuildDepth::SINGLE_)
[ "Load", "all", "objects", "in", "the", "given", "set", "of", "relations" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L747-L786
train
iherwig/wcmf
src/wcmf/lib/model/Node.php
Node.getRelatives
public function getRelatives($hierarchyType, $memOnly=true) { $relatives = []; $relations = $this->getRelations($hierarchyType); foreach ($relations as $curRelation) { $curRelatives = null; if ($memOnly) { $curRelatives = parent::getValue($curRelation->getOtherRole()); } else { $curRelatives = $this->getValue($curRelation->getOtherRole()); } if (!$curRelatives) { continue; } if (!is_array($curRelatives)) { $curRelatives = [$curRelatives]; } foreach ($curRelatives as $curRelative) { if ($curRelative instanceof PersistentObjectProxy && $memOnly) { // ignore proxies continue; } else { $relatives[] = $curRelative; } } } return $relatives; }
php
public function getRelatives($hierarchyType, $memOnly=true) { $relatives = []; $relations = $this->getRelations($hierarchyType); foreach ($relations as $curRelation) { $curRelatives = null; if ($memOnly) { $curRelatives = parent::getValue($curRelation->getOtherRole()); } else { $curRelatives = $this->getValue($curRelation->getOtherRole()); } if (!$curRelatives) { continue; } if (!is_array($curRelatives)) { $curRelatives = [$curRelatives]; } foreach ($curRelatives as $curRelative) { if ($curRelative instanceof PersistentObjectProxy && $memOnly) { // ignore proxies continue; } else { $relatives[] = $curRelative; } } } return $relatives; }
[ "public", "function", "getRelatives", "(", "$", "hierarchyType", ",", "$", "memOnly", "=", "true", ")", "{", "$", "relatives", "=", "[", "]", ";", "$", "relations", "=", "$", "this", "->", "getRelations", "(", "$", "hierarchyType", ")", ";", "foreach", ...
Get the relatives of a given hierarchyType. @param $hierarchyType @see PersistenceMapper::getRelations @param $memOnly Boolean whether to only get the relatives in memory or all relatives (including proxies) (default: _true_). @return An array containing the relatives.
[ "Get", "the", "relatives", "of", "a", "given", "hierarchyType", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/Node.php#L803-L831
train
iherwig/wcmf
src/wcmf/lib/core/impl/ClientSideSession.php
ClientSideSession.createToken
protected function createToken($login) { $jwt = (new Builder()) ->setIssuer($this->getTokenIssuer()) ->setIssuedAt(time()) ->setExpiration(time()+3600) ->set(self::AUTH_USER_NAME, $login) ->sign($this->getTokenSigner(), $this->key) ->getToken(); return $jwt->__toString(); }
php
protected function createToken($login) { $jwt = (new Builder()) ->setIssuer($this->getTokenIssuer()) ->setIssuedAt(time()) ->setExpiration(time()+3600) ->set(self::AUTH_USER_NAME, $login) ->sign($this->getTokenSigner(), $this->key) ->getToken(); return $jwt->__toString(); }
[ "protected", "function", "createToken", "(", "$", "login", ")", "{", "$", "jwt", "=", "(", "new", "Builder", "(", ")", ")", "->", "setIssuer", "(", "$", "this", "->", "getTokenIssuer", "(", ")", ")", "->", "setIssuedAt", "(", "time", "(", ")", ")", ...
Create the token for the given login @param $login @return String
[ "Create", "the", "token", "for", "the", "given", "login" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/impl/ClientSideSession.php#L177-L186
train
iherwig/wcmf
src/wcmf/lib/core/impl/ClientSideSession.php
ClientSideSession.getTokenData
protected function getTokenData() { $result = null; $request = ObjectFactory::getInstance('request'); $token = $request->hasHeader(self::TOKEN_HEADER) ? trim(str_replace(self::AUTH_TYPE, '', $request->getHeader(self::TOKEN_HEADER))) : $this->token; if ($token !== null) { $jwt = (new Parser())->parse((string)$token); // validate $data = new ValidationData(); $data->setIssuer($this->getTokenIssuer()); if ($jwt->validate($data) && $jwt->verify($this->getTokenSigner(), $this->key)) { $result = $jwt->getClaims(); } } return $result; }
php
protected function getTokenData() { $result = null; $request = ObjectFactory::getInstance('request'); $token = $request->hasHeader(self::TOKEN_HEADER) ? trim(str_replace(self::AUTH_TYPE, '', $request->getHeader(self::TOKEN_HEADER))) : $this->token; if ($token !== null) { $jwt = (new Parser())->parse((string)$token); // validate $data = new ValidationData(); $data->setIssuer($this->getTokenIssuer()); if ($jwt->validate($data) && $jwt->verify($this->getTokenSigner(), $this->key)) { $result = $jwt->getClaims(); } } return $result; }
[ "protected", "function", "getTokenData", "(", ")", "{", "$", "result", "=", "null", ";", "$", "request", "=", "ObjectFactory", "::", "getInstance", "(", "'request'", ")", ";", "$", "token", "=", "$", "request", "->", "hasHeader", "(", "self", "::", "TOKE...
Get the claims stored in the JWT @return Associative array
[ "Get", "the", "claims", "stored", "in", "the", "JWT" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/impl/ClientSideSession.php#L208-L225
train
iherwig/wcmf
src/wcmf/lib/service/SoapServer.php
SoapServer.getResponseHeaders
public function getResponseHeaders() { $headerStrings = headers_list(); header_remove(); $headers = []; foreach ($headerStrings as $header) { list($name, $value) = explode(':', $header, 2); $headers[trim($name)] = trim($value); } return $headers; }
php
public function getResponseHeaders() { $headerStrings = headers_list(); header_remove(); $headers = []; foreach ($headerStrings as $header) { list($name, $value) = explode(':', $header, 2); $headers[trim($name)] = trim($value); } return $headers; }
[ "public", "function", "getResponseHeaders", "(", ")", "{", "$", "headerStrings", "=", "headers_list", "(", ")", ";", "header_remove", "(", ")", ";", "$", "headers", "=", "[", "]", ";", "foreach", "(", "$", "headerStrings", "as", "$", "header", ")", "{", ...
Get the response headers after a call to the service method @return Array
[ "Get", "the", "response", "headers", "after", "a", "call", "to", "the", "service", "method" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/SoapServer.php#L120-L129
train
iherwig/wcmf
src/wcmf/lib/service/SoapServer.php
SoapServer.doCall
public function doCall($action, $params) { if (self::$logger->isDebugEnabled()) { self::$logger->debug("SoapServer action: ".$action); self::$logger->debug($params); } $authHeader = $this->requestHeader['Security']['UsernameToken']; $request = ObjectFactory::getInstance('request'); $request->setAction('actionSet'); $request->setFormat('soap'); $request->setResponseFormat('null'); $request->setValues([ 'data' => [ 'action1' => [ 'action' => 'login', 'params' => [ 'user' => $authHeader['Username'], 'password' => $authHeader['Password']['!'] ] ], 'action2' => [ 'action' => $action, 'params' => $params ], 'action3' => [ 'action' => 'logout' ] ] ]); // run the application $actionResponse = ObjectFactory::getInstance('response'); try { $response = $this->application->run($request); if ($response->hasErrors()) { $errors = $response->getErrors(); $this->handleException(new ApplicationException($request, $response, $errors[0])); } else { $responseData = $response->getValue('data'); $data = $responseData['action2']; $actionResponse->setSender($data['controller']); $actionResponse->setContext($data['context']); $actionResponse->setAction($data['action']); $actionResponse->setFormat('soap'); $actionResponse->setValues($data); $formatter = ObjectFactory::getInstance('formatter'); $formatter->serialize($actionResponse); if (self::$logger->isDebugEnabled()) { self::$logger->debug($actionResponse->__toString()); } } } catch (\Exception $ex) { $this->handleException($ex); } return $actionResponse; }
php
public function doCall($action, $params) { if (self::$logger->isDebugEnabled()) { self::$logger->debug("SoapServer action: ".$action); self::$logger->debug($params); } $authHeader = $this->requestHeader['Security']['UsernameToken']; $request = ObjectFactory::getInstance('request'); $request->setAction('actionSet'); $request->setFormat('soap'); $request->setResponseFormat('null'); $request->setValues([ 'data' => [ 'action1' => [ 'action' => 'login', 'params' => [ 'user' => $authHeader['Username'], 'password' => $authHeader['Password']['!'] ] ], 'action2' => [ 'action' => $action, 'params' => $params ], 'action3' => [ 'action' => 'logout' ] ] ]); // run the application $actionResponse = ObjectFactory::getInstance('response'); try { $response = $this->application->run($request); if ($response->hasErrors()) { $errors = $response->getErrors(); $this->handleException(new ApplicationException($request, $response, $errors[0])); } else { $responseData = $response->getValue('data'); $data = $responseData['action2']; $actionResponse->setSender($data['controller']); $actionResponse->setContext($data['context']); $actionResponse->setAction($data['action']); $actionResponse->setFormat('soap'); $actionResponse->setValues($data); $formatter = ObjectFactory::getInstance('formatter'); $formatter->serialize($actionResponse); if (self::$logger->isDebugEnabled()) { self::$logger->debug($actionResponse->__toString()); } } } catch (\Exception $ex) { $this->handleException($ex); } return $actionResponse; }
[ "public", "function", "doCall", "(", "$", "action", ",", "$", "params", ")", "{", "if", "(", "self", "::", "$", "logger", "->", "isDebugEnabled", "(", ")", ")", "{", "self", "::", "$", "logger", "->", "debug", "(", "\"SoapServer action: \"", ".", "$", ...
Process a soap call @param $action The action @param $params The action parameters @return The Response instance from the executed Controller
[ "Process", "a", "soap", "call" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/SoapServer.php#L154-L211
train
iherwig/wcmf
src/wcmf/application/controller/SearchIndexController.php
SearchIndexController.collect
protected function collect($types) { $persistenceFacade = $this->getPersistenceFacade(); $nodesPerCall = $this->getRequestValue('nodesPerCall'); foreach ($types as $type) { $oids = $persistenceFacade->getOIDs($type); $oidLists = array_chunk($oids, self::OPTIMIZE_FREQ); for ($i=0, $count=sizeof($oidLists); $i<$count; $i++) { $this->addWorkPackage($this->getMessage()->getText('Indexing %0% %1% objects, starting from %2%., ', [sizeof($oids), $type, ($i*self::OPTIMIZE_FREQ+1)]), $nodesPerCall, $oidLists[$i], 'index'); $this->addWorkPackage($this->getMessage()->getText('Optimizing index'), 1, [0], 'optimize'); } } }
php
protected function collect($types) { $persistenceFacade = $this->getPersistenceFacade(); $nodesPerCall = $this->getRequestValue('nodesPerCall'); foreach ($types as $type) { $oids = $persistenceFacade->getOIDs($type); $oidLists = array_chunk($oids, self::OPTIMIZE_FREQ); for ($i=0, $count=sizeof($oidLists); $i<$count; $i++) { $this->addWorkPackage($this->getMessage()->getText('Indexing %0% %1% objects, starting from %2%., ', [sizeof($oids), $type, ($i*self::OPTIMIZE_FREQ+1)]), $nodesPerCall, $oidLists[$i], 'index'); $this->addWorkPackage($this->getMessage()->getText('Optimizing index'), 1, [0], 'optimize'); } } }
[ "protected", "function", "collect", "(", "$", "types", ")", "{", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "$", "nodesPerCall", "=", "$", "this", "->", "getRequestValue", "(", "'nodesPerCall'", ")", ";", "foreac...
Collect all oids of the given types @param $types The types to process @note This is a callback method called on a matching work package @see BatchController::addWorkPackage()
[ "Collect", "all", "oids", "of", "the", "given", "types" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SearchIndexController.php#L129-L142
train
iherwig/wcmf
src/wcmf/application/controller/SearchIndexController.php
SearchIndexController.index
protected function index($oids) { $persistenceFacade = $this->getPersistenceFacade(); foreach($oids as $oid) { if (ObjectId::isValid($oid)) { $obj = $persistenceFacade->load($oid); if ($obj) { $this->search->addToIndex($obj); } } } $this->search->commitIndex(false); if ($this->getStepNumber() == $this->getNumberOfSteps()) { $this->addWorkPackage($this->getMessage()->getText('Optimizing index'), 1, [0], 'optimize'); } }
php
protected function index($oids) { $persistenceFacade = $this->getPersistenceFacade(); foreach($oids as $oid) { if (ObjectId::isValid($oid)) { $obj = $persistenceFacade->load($oid); if ($obj) { $this->search->addToIndex($obj); } } } $this->search->commitIndex(false); if ($this->getStepNumber() == $this->getNumberOfSteps()) { $this->addWorkPackage($this->getMessage()->getText('Optimizing index'), 1, [0], 'optimize'); } }
[ "protected", "function", "index", "(", "$", "oids", ")", "{", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "foreach", "(", "$", "oids", "as", "$", "oid", ")", "{", "if", "(", "ObjectId", "::", "isValid", "(",...
Create the lucene index from the given objects @param $oids The oids to process @note This is a callback method called on a matching work package @see BatchController::addWorkPackage()
[ "Create", "the", "lucene", "index", "from", "the", "given", "objects" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SearchIndexController.php#L149-L165
train
iherwig/wcmf
src/wcmf/lib/core/ErrorHandler.php
ErrorHandler.getStackTrace
public static function getStackTrace() { ob_start(); debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $trace = ob_get_contents(); ob_end_clean(); // remove first item from backtrace as it's this function which is redundant. $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '', $trace, 1); return $trace; }
php
public static function getStackTrace() { ob_start(); debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $trace = ob_get_contents(); ob_end_clean(); // remove first item from backtrace as it's this function which is redundant. $trace = preg_replace('/^#0\s+'.__FUNCTION__."[^\n]*\n/", '', $trace, 1); return $trace; }
[ "public", "static", "function", "getStackTrace", "(", ")", "{", "ob_start", "(", ")", ";", "debug_print_backtrace", "(", "DEBUG_BACKTRACE_IGNORE_ARGS", ")", ";", "$", "trace", "=", "ob_get_contents", "(", ")", ";", "ob_end_clean", "(", ")", ";", "// remove first...
Get the stack trace @return The stack trace as string
[ "Get", "the", "stack", "trace" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/ErrorHandler.php#L45-L55
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.getConnections
public static function getConnections($type, $otherRole, $otherType, $hierarchyType='all') { $paths = []; self::getConnectionsImpl($type, $otherRole, $otherType, $hierarchyType, $paths); $minLength = -1; $shortestPaths = []; foreach ($paths as $curPath) { $curLength = $curPath->getPathLength(); if ($minLength == -1 || $minLength > $curLength) { $minLength = $curLength; $shortestPaths = [$curPath]; } elseif ($curLength == $minLength) { $shortestPaths[] = $curPath; } } return $shortestPaths; }
php
public static function getConnections($type, $otherRole, $otherType, $hierarchyType='all') { $paths = []; self::getConnectionsImpl($type, $otherRole, $otherType, $hierarchyType, $paths); $minLength = -1; $shortestPaths = []; foreach ($paths as $curPath) { $curLength = $curPath->getPathLength(); if ($minLength == -1 || $minLength > $curLength) { $minLength = $curLength; $shortestPaths = [$curPath]; } elseif ($curLength == $minLength) { $shortestPaths[] = $curPath; } } return $shortestPaths; }
[ "public", "static", "function", "getConnections", "(", "$", "type", ",", "$", "otherRole", ",", "$", "otherType", ",", "$", "hierarchyType", "=", "'all'", ")", "{", "$", "paths", "=", "[", "]", ";", "self", "::", "getConnectionsImpl", "(", "$", "type", ...
Get the shortest paths that connect a type to another type. @param $type The type to start from @param $otherRole The role of the type at the other end (maybe null, if only type shoudl match) @param $otherType The type at the other end (maybe null, if only role shoudl match) @param $hierarchyType The hierarchy type that the other type has in relation to this type 'parent', 'child', 'undefined' or 'all' to get all relations (default: 'all') @return An array of PathDescription instances
[ "Get", "the", "shortest", "paths", "that", "connect", "a", "type", "to", "another", "type", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L39-L55
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.getConnectionsImpl
protected static function getConnectionsImpl($type, $otherRole, $otherType, $hierarchyType, array &$result=[], array $currentPath=[]) { $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $mapper = $persistenceFacade->getMapper($type); // check relations $relationDescs = $mapper->getRelations($hierarchyType); foreach ($relationDescs as $relationDesc) { // loop detection $loopDetected = false; foreach ($currentPath as $pathPart) { if ($relationDesc->isSameRelation($pathPart)) { $loopDetected = true; break; } } if ($loopDetected) { // continue with next relation continue; } $pathFound = null; $nextType = $relationDesc->getOtherType(); $nextRole = $relationDesc->getOtherRole(); $otherTypeFq = $otherType != null ? $persistenceFacade->getFullyQualifiedType($otherType) : null; if (($otherRole != null && $nextRole == $otherRole) || ($otherType != null && $nextType == $otherTypeFq)) { // other end found -> terminate $pathFound = $currentPath; $pathFound[] = $relationDesc; } else { // nothing found -> proceed with next generation $nextCurrentPath = $currentPath; $nextCurrentPath[] = $relationDesc; self::getConnectionsImpl($nextType, $otherRole, $otherType, $hierarchyType, $result, $nextCurrentPath); } // if a path is found, add it to the result if ($pathFound) { $result[] = new PathDescription($pathFound); } } }
php
protected static function getConnectionsImpl($type, $otherRole, $otherType, $hierarchyType, array &$result=[], array $currentPath=[]) { $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $mapper = $persistenceFacade->getMapper($type); // check relations $relationDescs = $mapper->getRelations($hierarchyType); foreach ($relationDescs as $relationDesc) { // loop detection $loopDetected = false; foreach ($currentPath as $pathPart) { if ($relationDesc->isSameRelation($pathPart)) { $loopDetected = true; break; } } if ($loopDetected) { // continue with next relation continue; } $pathFound = null; $nextType = $relationDesc->getOtherType(); $nextRole = $relationDesc->getOtherRole(); $otherTypeFq = $otherType != null ? $persistenceFacade->getFullyQualifiedType($otherType) : null; if (($otherRole != null && $nextRole == $otherRole) || ($otherType != null && $nextType == $otherTypeFq)) { // other end found -> terminate $pathFound = $currentPath; $pathFound[] = $relationDesc; } else { // nothing found -> proceed with next generation $nextCurrentPath = $currentPath; $nextCurrentPath[] = $relationDesc; self::getConnectionsImpl($nextType, $otherRole, $otherType, $hierarchyType, $result, $nextCurrentPath); } // if a path is found, add it to the result if ($pathFound) { $result[] = new PathDescription($pathFound); } } }
[ "protected", "static", "function", "getConnectionsImpl", "(", "$", "type", ",", "$", "otherRole", ",", "$", "otherType", ",", "$", "hierarchyType", ",", "array", "&", "$", "result", "=", "[", "]", ",", "array", "$", "currentPath", "=", "[", "]", ")", "...
Get the relations that connect a type to another type. @param $type The type to start from @param $otherRole The role of the type at the other end (maybe null, if only type shoudl match) @param $otherType The type at the other end (maybe null, if only role shoudl match) @param $hierarchyType The hierarchy type that the other type has in relation to this type 'parent', 'child', 'undefined' or 'all' to get all relations (default: 'all') @param $result Array of PathDescriptions after execution @param $currentPath Internal use only
[ "Get", "the", "relations", "that", "connect", "a", "type", "to", "another", "type", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L67-L109
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.getRelationQueryCondition
public static function getRelationQueryCondition($node, $otherRole) { $mapper = $node->getMapper(); $relationDescription = $mapper->getRelation($otherRole); $otherType = $relationDescription->getOtherType(); $query = new ObjectQuery($otherType, __CLASS__.__METHOD__.$node->getType().$otherRole); // add the primary keys of the node // using the role name as alias (avoids ambiguous paths) $nodeTpl = $query->getObjectTemplate($node->getType(), $relationDescription->getThisRole()); $oid = $node->getOID(); $ids = $oid->getId(); $i = 0; foreach ($mapper->getPkNames() as $pkName) { $nodeTpl->setValue($pkName, Criteria::asValue("=", $ids[$i++])); } // add the other type in the given relation $otherTpl = $query->getObjectTemplate($otherType); $nodeTpl->addNode($otherTpl, $otherRole); $condition = $query->getQueryCondition(); // prevent selecting all objects, if the condition is empty if (strlen($condition) == 0) { $condition = 0; } return $condition; }
php
public static function getRelationQueryCondition($node, $otherRole) { $mapper = $node->getMapper(); $relationDescription = $mapper->getRelation($otherRole); $otherType = $relationDescription->getOtherType(); $query = new ObjectQuery($otherType, __CLASS__.__METHOD__.$node->getType().$otherRole); // add the primary keys of the node // using the role name as alias (avoids ambiguous paths) $nodeTpl = $query->getObjectTemplate($node->getType(), $relationDescription->getThisRole()); $oid = $node->getOID(); $ids = $oid->getId(); $i = 0; foreach ($mapper->getPkNames() as $pkName) { $nodeTpl->setValue($pkName, Criteria::asValue("=", $ids[$i++])); } // add the other type in the given relation $otherTpl = $query->getObjectTemplate($otherType); $nodeTpl->addNode($otherTpl, $otherRole); $condition = $query->getQueryCondition(); // prevent selecting all objects, if the condition is empty if (strlen($condition) == 0) { $condition = 0; } return $condition; }
[ "public", "static", "function", "getRelationQueryCondition", "(", "$", "node", ",", "$", "otherRole", ")", "{", "$", "mapper", "=", "$", "node", "->", "getMapper", "(", ")", ";", "$", "relationDescription", "=", "$", "mapper", "->", "getRelation", "(", "$"...
Get the query condition used to select all related Nodes of a given role. @param $node The Node to select the relatives for @param $otherRole The role of the other nodes @return The condition string to be used with StringQuery.
[ "Get", "the", "query", "condition", "used", "to", "select", "all", "related", "Nodes", "of", "a", "given", "role", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L117-L141
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.makeNodeUrlsRelative
public static function makeNodeUrlsRelative(Node $node, $baseUrl, $recursive=true) { // use NodeValueIterator to iterate over all Node values // and call the global convert function on each $iter = new NodeValueIterator($node, $recursive); for($iter->rewind(); $iter->valid(); $iter->next()) { self::makeValueUrlsRelative($iter->currentNode(), $iter->key(), $baseUrl); } }
php
public static function makeNodeUrlsRelative(Node $node, $baseUrl, $recursive=true) { // use NodeValueIterator to iterate over all Node values // and call the global convert function on each $iter = new NodeValueIterator($node, $recursive); for($iter->rewind(); $iter->valid(); $iter->next()) { self::makeValueUrlsRelative($iter->currentNode(), $iter->key(), $baseUrl); } }
[ "public", "static", "function", "makeNodeUrlsRelative", "(", "Node", "$", "node", ",", "$", "baseUrl", ",", "$", "recursive", "=", "true", ")", "{", "// use NodeValueIterator to iterate over all Node values", "// and call the global convert function on each", "$", "iter", ...
Make all urls matching a given base url in a Node relative. @param $node Node instance that holds the value @param $baseUrl The baseUrl to which matching urls will be made relative @param $recursive Boolean whether to recurse into child Nodes or not (default: true)
[ "Make", "all", "urls", "matching", "a", "given", "base", "url", "in", "a", "Node", "relative", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L202-L209
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.makeValueUrlsRelative
private static function makeValueUrlsRelative(PersistentObject $object, $valueName, $baseUrl) { $value = $object->getValue($valueName); // find urls in texts $urls = StringUtil::getUrls($value); // find direct attribute urls if (strpos($value, 'http://') === 0 || strpos($value, 'https://') === 0) { $urls[] = $value; } // process urls foreach ($urls as $url) { // convert absolute urls matching baseUrl $urlConv = $url; if (strpos($url, $baseUrl) === 0) { $urlConv = str_replace($baseUrl, '', $url); } // replace url $value = str_replace($url, $urlConv, $value); } $object->setValue($valueName, $value); }
php
private static function makeValueUrlsRelative(PersistentObject $object, $valueName, $baseUrl) { $value = $object->getValue($valueName); // find urls in texts $urls = StringUtil::getUrls($value); // find direct attribute urls if (strpos($value, 'http://') === 0 || strpos($value, 'https://') === 0) { $urls[] = $value; } // process urls foreach ($urls as $url) { // convert absolute urls matching baseUrl $urlConv = $url; if (strpos($url, $baseUrl) === 0) { $urlConv = str_replace($baseUrl, '', $url); } // replace url $value = str_replace($url, $urlConv, $value); } $object->setValue($valueName, $value); }
[ "private", "static", "function", "makeValueUrlsRelative", "(", "PersistentObject", "$", "object", ",", "$", "valueName", ",", "$", "baseUrl", ")", "{", "$", "value", "=", "$", "object", "->", "getValue", "(", "$", "valueName", ")", ";", "// find urls in texts"...
Make the urls matching a given base url in a PersistentObject value relative. @param $node Node instance that holds the value @param $valueName The name of the value @param $baseUrl The baseUrl to which matching urls will be made relative
[ "Make", "the", "urls", "matching", "a", "given", "base", "url", "in", "a", "PersistentObject", "value", "relative", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L217-L237
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.translateValues
public static function translateValues(&$nodes, $language=null, $itemDelim=", ") { // translate the node values for($i=0; $i<sizeof($nodes); $i++) { $iter = new NodeValueIterator($nodes[$i], false); for($iter->rewind(); $iter->valid(); $iter->next()) { self::translateValue($iter->currentNode(), $iter->key(), $language, $itemDelim); } } }
php
public static function translateValues(&$nodes, $language=null, $itemDelim=", ") { // translate the node values for($i=0; $i<sizeof($nodes); $i++) { $iter = new NodeValueIterator($nodes[$i], false); for($iter->rewind(); $iter->valid(); $iter->next()) { self::translateValue($iter->currentNode(), $iter->key(), $language, $itemDelim); } } }
[ "public", "static", "function", "translateValues", "(", "&", "$", "nodes", ",", "$", "language", "=", "null", ",", "$", "itemDelim", "=", "\", \"", ")", "{", "// translate the node values", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "sizeof", ...
Translate all list values in a list of Nodes. @note Translation in this case refers to mapping list values from the key to the value and should not be confused with localization, although values maybe localized using the language parameter. @param $nodes A reference to the array of Node instances @param $language The language code, if the translated values should be localized. Optional, default is Localizat$objectgetDefaultLanguage() @param $itemDelim Delimiter string for array values (optional, default: ", ")
[ "Translate", "all", "list", "values", "in", "a", "list", "of", "Nodes", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L249-L257
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.translateValue
public static function translateValue(PersistentObject $object, $valueName, $language, $itemDelim=", ") { $value = $object->getValue($valueName); // translate list values $value = ValueListProvider::translateValue($value, $object->getValueProperty($valueName, 'input_type'), $language, $itemDelim); // force set (the rendered value may not be satisfy validation rules) $object->setValue($valueName, $value, true); }
php
public static function translateValue(PersistentObject $object, $valueName, $language, $itemDelim=", ") { $value = $object->getValue($valueName); // translate list values $value = ValueListProvider::translateValue($value, $object->getValueProperty($valueName, 'input_type'), $language, $itemDelim); // force set (the rendered value may not be satisfy validation rules) $object->setValue($valueName, $value, true); }
[ "public", "static", "function", "translateValue", "(", "PersistentObject", "$", "object", ",", "$", "valueName", ",", "$", "language", ",", "$", "itemDelim", "=", "\", \"", ")", "{", "$", "value", "=", "$", "object", "->", "getValue", "(", "$", "valueName"...
Translate a PersistentObject list value. @param $object The object whose value to translate @param $valueName The name of the value to translate @param $language The language to use @param $itemDelim Delimiter string for array values (optional, default: ", ")
[ "Translate", "a", "PersistentObject", "list", "value", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L266-L272
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.removeNonDisplayValues
public static function removeNonDisplayValues(Node $node) { $displayValues = $node->getProperty('displayValues'); $valueNames = $node->getValueNames(); foreach($valueNames as $name) { if (!in_array($name, $displayValues)) { $node->removeValue($name); } } }
php
public static function removeNonDisplayValues(Node $node) { $displayValues = $node->getProperty('displayValues'); $valueNames = $node->getValueNames(); foreach($valueNames as $name) { if (!in_array($name, $displayValues)) { $node->removeValue($name); } } }
[ "public", "static", "function", "removeNonDisplayValues", "(", "Node", "$", "node", ")", "{", "$", "displayValues", "=", "$", "node", "->", "getProperty", "(", "'displayValues'", ")", ";", "$", "valueNames", "=", "$", "node", "->", "getValueNames", "(", ")",...
Remove all values from a Node that are not a display value. @param $node The Node instance
[ "Remove", "all", "values", "from", "a", "Node", "that", "are", "not", "a", "display", "value", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L278-L286
train
iherwig/wcmf
src/wcmf/lib/model/NodeUtil.php
NodeUtil.removeNonPkValues
public static function removeNonPkValues(Node $node) { $mapper = $node->getMapper(); $pkValues = $mapper->getPkNames(); $valueNames = $node->getValueNames(); foreach($valueNames as $name) { if (!in_array($name, $pkValues)) { $node->removeValue($name); } } }
php
public static function removeNonPkValues(Node $node) { $mapper = $node->getMapper(); $pkValues = $mapper->getPkNames(); $valueNames = $node->getValueNames(); foreach($valueNames as $name) { if (!in_array($name, $pkValues)) { $node->removeValue($name); } } }
[ "public", "static", "function", "removeNonPkValues", "(", "Node", "$", "node", ")", "{", "$", "mapper", "=", "$", "node", "->", "getMapper", "(", ")", ";", "$", "pkValues", "=", "$", "mapper", "->", "getPkNames", "(", ")", ";", "$", "valueNames", "=", ...
Remove all values from a Node that are not a primary key value. @param $node The Node instance
[ "Remove", "all", "values", "from", "a", "Node", "that", "are", "not", "a", "primary", "key", "value", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/NodeUtil.php#L292-L301
train
iherwig/wcmf
src/wcmf/lib/presentation/impl/DefaultRequest.php
DefaultRequest.getBestRoute
protected function getBestRoute($routes) { // order matching routes by number of parameters $method = $this->getMethod(); usort($routes, function($a, $b) use ($method) { $numParamsA = $a['numPathParameters']; $numParamsB = $b['numPathParameters']; if ($numParamsA == $numParamsB) { $numPatternsA = $a['numPathPatterns']; $numPatternsB = $b['numPathPatterns']; if ($numPatternsA == $numPatternsB) { $hasMethodA = in_array($method, $a['methods']); $hasMethodB = in_array($method, $b['methods']); return ($hasMethodA && !$hasMethodB) ? -1 : ((!$hasMethodA && $hasMethodB) ? 1 : 0); } // more patterns is more specific return ($numPatternsA < $numPatternsB) ? 1 : -1; } // less parameters is more specific return ($numParamsA > $numParamsB) ? 1 : -1; }); if (self::$logger->isDebugEnabled()) { self::$logger->debug("Ordered routes:"); self::$logger->debug($routes); } // return most specific route return array_shift($routes); }
php
protected function getBestRoute($routes) { // order matching routes by number of parameters $method = $this->getMethod(); usort($routes, function($a, $b) use ($method) { $numParamsA = $a['numPathParameters']; $numParamsB = $b['numPathParameters']; if ($numParamsA == $numParamsB) { $numPatternsA = $a['numPathPatterns']; $numPatternsB = $b['numPathPatterns']; if ($numPatternsA == $numPatternsB) { $hasMethodA = in_array($method, $a['methods']); $hasMethodB = in_array($method, $b['methods']); return ($hasMethodA && !$hasMethodB) ? -1 : ((!$hasMethodA && $hasMethodB) ? 1 : 0); } // more patterns is more specific return ($numPatternsA < $numPatternsB) ? 1 : -1; } // less parameters is more specific return ($numParamsA > $numParamsB) ? 1 : -1; }); if (self::$logger->isDebugEnabled()) { self::$logger->debug("Ordered routes:"); self::$logger->debug($routes); } // return most specific route return array_shift($routes); }
[ "protected", "function", "getBestRoute", "(", "$", "routes", ")", "{", "// order matching routes by number of parameters", "$", "method", "=", "$", "this", "->", "getMethod", "(", ")", ";", "usort", "(", "$", "routes", ",", "function", "(", "$", "a", ",", "$...
Get the best matching route from the given list of routes @param $routes Array of route definitions as returned by getMatchingRoutes() @return Array with keys 'numPathParameters', 'parameters', 'methods'
[ "Get", "the", "best", "matching", "route", "from", "the", "given", "list", "of", "routes" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/impl/DefaultRequest.php#L333-L361
train
iherwig/wcmf
src/wcmf/lib/util/DOMUtils.php
DOMUtils.processHtml
public static function processHtml($content, callable $processor) { $doc = new \DOMDocument(); $doc->loadHTML('<html>'.trim(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')).'</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $processor($doc); return trim(str_replace(['<html>', '</html>'], '', $doc->saveHTML())); }
php
public static function processHtml($content, callable $processor) { $doc = new \DOMDocument(); $doc->loadHTML('<html>'.trim(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8')).'</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); $processor($doc); return trim(str_replace(['<html>', '</html>'], '', $doc->saveHTML())); }
[ "public", "static", "function", "processHtml", "(", "$", "content", ",", "callable", "$", "processor", ")", "{", "$", "doc", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "doc", "->", "loadHTML", "(", "'<html>'", ".", "trim", "(", "mb_convert_enco...
Process the given html fragment using the given function @param $content Html string @param $processor Function that accepts a DOMDocument as only parameter @return String
[ "Process", "the", "given", "html", "fragment", "using", "the", "given", "function" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DOMUtils.php#L25-L30
train
iherwig/wcmf
src/wcmf/lib/util/DOMUtils.php
DOMUtils.getChildNodesOfName
public static function getChildNodesOfName(\DOMElement $element, $elementName) { $result = []; foreach ($element->childNodes as $child) { if ($child->nodeName == $elementName) { $result[] = $child; } } return $result; }
php
public static function getChildNodesOfName(\DOMElement $element, $elementName) { $result = []; foreach ($element->childNodes as $child) { if ($child->nodeName == $elementName) { $result[] = $child; } } return $result; }
[ "public", "static", "function", "getChildNodesOfName", "(", "\\", "DOMElement", "$", "element", ",", "$", "elementName", ")", "{", "$", "result", "=", "[", "]", ";", "foreach", "(", "$", "element", "->", "childNodes", "as", "$", "child", ")", "{", "if", ...
Get the child nodes of a given element name @param \DOMElement $element @param $elementName @return \DOMNodeList[]
[ "Get", "the", "child", "nodes", "of", "a", "given", "element", "name" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DOMUtils.php#L38-L46
train
iherwig/wcmf
src/wcmf/lib/util/DOMUtils.php
DOMUtils.getNextSiblingOfType
public static function getNextSiblingOfType(\DOMElement $element, $elementType) { $nextSibling = $element->nextSibling; while ($nextSibling && $nextSibling->nodeType != $elementType) { $nextSibling = $nextSibling->nextSibling; } return $nextSibling; }
php
public static function getNextSiblingOfType(\DOMElement $element, $elementType) { $nextSibling = $element->nextSibling; while ($nextSibling && $nextSibling->nodeType != $elementType) { $nextSibling = $nextSibling->nextSibling; } return $nextSibling; }
[ "public", "static", "function", "getNextSiblingOfType", "(", "\\", "DOMElement", "$", "element", ",", "$", "elementType", ")", "{", "$", "nextSibling", "=", "$", "element", "->", "nextSibling", ";", "while", "(", "$", "nextSibling", "&&", "$", "nextSibling", ...
Get the next sibling of the given element type @param $element Reference element @param $elementType Element type (e.g. XML_ELEMENT_NODE) @return \DomElement
[ "Get", "the", "next", "sibling", "of", "the", "given", "element", "type" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DOMUtils.php#L54-L60
train
iherwig/wcmf
src/wcmf/lib/util/DOMUtils.php
DOMUtils.getInnerHtml
public static function getInnerHtml(\DOMElement $element) { $innerHTML= ''; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $child->ownerDocument->saveXML( $child ); } return $innerHTML; }
php
public static function getInnerHtml(\DOMElement $element) { $innerHTML= ''; $children = $element->childNodes; foreach ($children as $child) { $innerHTML .= $child->ownerDocument->saveXML( $child ); } return $innerHTML; }
[ "public", "static", "function", "getInnerHtml", "(", "\\", "DOMElement", "$", "element", ")", "{", "$", "innerHTML", "=", "''", ";", "$", "children", "=", "$", "element", "->", "childNodes", ";", "foreach", "(", "$", "children", "as", "$", "child", ")", ...
Get the inner html string of an element @param \DOMElement $element @return String
[ "Get", "the", "inner", "html", "string", "of", "an", "element" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DOMUtils.php#L67-L74
train
iherwig/wcmf
src/wcmf/lib/util/DOMUtils.php
DOMUtils.setInnerHtml
public static function setInnerHtml(\DOMElement $element, $html) { $fragment = $element->ownerDocument->createDocumentFragment(); $fragment->appendXML($html); $element->appendChild($fragment); }
php
public static function setInnerHtml(\DOMElement $element, $html) { $fragment = $element->ownerDocument->createDocumentFragment(); $fragment->appendXML($html); $element->appendChild($fragment); }
[ "public", "static", "function", "setInnerHtml", "(", "\\", "DOMElement", "$", "element", ",", "$", "html", ")", "{", "$", "fragment", "=", "$", "element", "->", "ownerDocument", "->", "createDocumentFragment", "(", ")", ";", "$", "fragment", "->", "appendXML...
Set the inner html string of an element @param \DOMElement $element @param $html
[ "Set", "the", "inner", "html", "string", "of", "an", "element" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DOMUtils.php#L81-L85
train
iherwig/wcmf
src/wcmf/lib/util/DOMUtils.php
DOMUtils.removeEmptyLines
public static function removeEmptyLines($html) { // merge multiple linebreaks to one $html = preg_replace("/(<br>\s*)+/", "<br>", $html); // remove linebreaks at the beginning of a paragraph $html = preg_replace("/<p>(\s|<br>)*/", "<p>", $html); // remove linebreaks at the end of a paragraph $html = preg_replace("/(\s|<br>)*<\/p>/", "</p>", $html); // remove empty paragraphs $html = preg_replace("/<p><\/p>/", "", $html); return $html; }
php
public static function removeEmptyLines($html) { // merge multiple linebreaks to one $html = preg_replace("/(<br>\s*)+/", "<br>", $html); // remove linebreaks at the beginning of a paragraph $html = preg_replace("/<p>(\s|<br>)*/", "<p>", $html); // remove linebreaks at the end of a paragraph $html = preg_replace("/(\s|<br>)*<\/p>/", "</p>", $html); // remove empty paragraphs $html = preg_replace("/<p><\/p>/", "", $html); return $html; }
[ "public", "static", "function", "removeEmptyLines", "(", "$", "html", ")", "{", "// merge multiple linebreaks to one", "$", "html", "=", "preg_replace", "(", "\"/(<br>\\s*)+/\"", ",", "\"<br>\"", ",", "$", "html", ")", ";", "// remove linebreaks at the beginning of a pa...
Remove double linebreaks and empty paragraphs @param $content @return String
[ "Remove", "double", "linebreaks", "and", "empty", "paragraphs" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DOMUtils.php#L93-L103
train
iherwig/wcmf
src/wcmf/lib/core/impl/DefaultFactory.php
DefaultFactory.resolveValue
protected function resolveValue($value) { // special treatments, if value is a string if (is_string($value)) { // replace variables denoted by a leading $ if (strpos($value, '$') === 0) { $value = $this->getInstance(preg_replace('/^\$/', '', $value)); } else { // convert booleans $lower = strtolower($value); if ($lower === 'true') { $value = true; } if ($lower === 'false') { $value = false; } } } // special treatments, if value is an array if (is_array($value)) { $result = []; $containsInstance = false; // check for variables foreach ($value as $val) { if (is_string($val) && strpos($val, '$') === 0) { $result[] = $this->getInstance(preg_replace('/^\$/', '', $val)); $containsInstance = true; } else { $result[] = $val; } } // only replace value, if the array containes an variable if ($containsInstance) { $value = $result; } } return $value; }
php
protected function resolveValue($value) { // special treatments, if value is a string if (is_string($value)) { // replace variables denoted by a leading $ if (strpos($value, '$') === 0) { $value = $this->getInstance(preg_replace('/^\$/', '', $value)); } else { // convert booleans $lower = strtolower($value); if ($lower === 'true') { $value = true; } if ($lower === 'false') { $value = false; } } } // special treatments, if value is an array if (is_array($value)) { $result = []; $containsInstance = false; // check for variables foreach ($value as $val) { if (is_string($val) && strpos($val, '$') === 0) { $result[] = $this->getInstance(preg_replace('/^\$/', '', $val)); $containsInstance = true; } else { $result[] = $val; } } // only replace value, if the array containes an variable if ($containsInstance) { $value = $result; } } return $value; }
[ "protected", "function", "resolveValue", "(", "$", "value", ")", "{", "// special treatments, if value is a string", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "// replace variables denoted by a leading $", "if", "(", "strpos", "(", "$", "value", ",",...
Resolve a configuration value into a parameter @param $value @return Mixed
[ "Resolve", "a", "configuration", "value", "into", "a", "parameter" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/impl/DefaultFactory.php#L331-L369
train
iherwig/wcmf
src/wcmf/lib/core/impl/DefaultFactory.php
DefaultFactory.getInterface
protected function getInterface($name) { if (isset($this->requiredInterfaces[$name])) { return $this->requiredInterfaces[$name]; } return null; }
php
protected function getInterface($name) { if (isset($this->requiredInterfaces[$name])) { return $this->requiredInterfaces[$name]; } return null; }
[ "protected", "function", "getInterface", "(", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "requiredInterfaces", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "requiredInterfaces", "[", "$", "name", "]", ";", ...
Get the interface that is required to be implemented by the given instance @param $name The name of the instance @return Interface or null, if undefined
[ "Get", "the", "interface", "that", "is", "required", "to", "be", "implemented", "by", "the", "given", "instance" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/impl/DefaultFactory.php#L376-L381
train
iherwig/wcmf
src/wcmf/lib/security/impl/AbstractPermissionManager.php
AbstractPermissionManager.serializePermissions
protected function serializePermissions($permissions) { $result = $permissions['default'] === true ? PermissionManager::PERMISSION_MODIFIER_ALLOW.'* ' : PermissionManager::PERMISSION_MODIFIER_DENY.'* '; if (isset($permissions['allow'])) { foreach ($permissions['allow'] as $role) { $result .= PermissionManager::PERMISSION_MODIFIER_ALLOW.$role.' '; } } if (isset($permissions['deny'])) { foreach ($permissions['deny'] as $role) { $result .= PermissionManager::PERMISSION_MODIFIER_DENY.$role.' '; } } return trim($result); }
php
protected function serializePermissions($permissions) { $result = $permissions['default'] === true ? PermissionManager::PERMISSION_MODIFIER_ALLOW.'* ' : PermissionManager::PERMISSION_MODIFIER_DENY.'* '; if (isset($permissions['allow'])) { foreach ($permissions['allow'] as $role) { $result .= PermissionManager::PERMISSION_MODIFIER_ALLOW.$role.' '; } } if (isset($permissions['deny'])) { foreach ($permissions['deny'] as $role) { $result .= PermissionManager::PERMISSION_MODIFIER_DENY.$role.' '; } } return trim($result); }
[ "protected", "function", "serializePermissions", "(", "$", "permissions", ")", "{", "$", "result", "=", "$", "permissions", "[", "'default'", "]", "===", "true", "?", "PermissionManager", "::", "PERMISSION_MODIFIER_ALLOW", ".", "'* '", ":", "PermissionManager", ":...
Convert an associative permissions array with keys 'default', 'allow', 'deny' into a string. @param $permissions Associative array with keys 'default', 'allow', 'deny', where 'allow', 'deny' are arrays itself holding roles and 'default' is a boolean value derived from the wildcard policy (+* or -*). @return A role string (+*, +administrators, -guest, entries without '+' or '-' prefix default to allow rules).
[ "Convert", "an", "associative", "permissions", "array", "with", "keys", "default", "allow", "deny", "into", "a", "string", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/AbstractPermissionManager.php#L349-L363
train
iherwig/wcmf
src/wcmf/lib/security/impl/AbstractPermissionManager.php
AbstractPermissionManager.matchRoles
protected function matchRoles($resource, $permissions, $login) { if (self::$logger->isDebugEnabled()) { self::$logger->debug("Matching roles for ".$login); } $user = $this->principalFactory->getUser($login, true); if ($user != null) { foreach (['allow' => true, 'deny' => false] as $key => $result) { if (isset($permissions[$key])) { foreach ($permissions[$key] as $role) { if ($this->matchRole($user, $role, $resource)) { if (self::$logger->isDebugEnabled()) { self::$logger->debug($key." because of role ".$role); } return $result; } } } } } if (self::$logger->isDebugEnabled()) { self::$logger->debug("Check default ".$permissions['default']); } return (isset($permissions['default']) ? $permissions['default'] : false); }
php
protected function matchRoles($resource, $permissions, $login) { if (self::$logger->isDebugEnabled()) { self::$logger->debug("Matching roles for ".$login); } $user = $this->principalFactory->getUser($login, true); if ($user != null) { foreach (['allow' => true, 'deny' => false] as $key => $result) { if (isset($permissions[$key])) { foreach ($permissions[$key] as $role) { if ($this->matchRole($user, $role, $resource)) { if (self::$logger->isDebugEnabled()) { self::$logger->debug($key." because of role ".$role); } return $result; } } } } } if (self::$logger->isDebugEnabled()) { self::$logger->debug("Check default ".$permissions['default']); } return (isset($permissions['default']) ? $permissions['default'] : false); }
[ "protected", "function", "matchRoles", "(", "$", "resource", ",", "$", "permissions", ",", "$", "login", ")", "{", "if", "(", "self", "::", "$", "logger", "->", "isDebugEnabled", "(", ")", ")", "{", "self", "::", "$", "logger", "->", "debug", "(", "\...
Matches the roles of the user and the roles in the given permissions @param $resource The resource string to authorize. @param $permissions An array containing permissions as an associative array with the keys 'default', 'allow', 'deny', where 'allow', 'deny' are arrays itself holding roles and 'default' is a boolean value derived from the wildcard policy (+* or -*). 'allow' overwrites 'deny' overwrites 'default' @param $login the login of the user to match the roles for @return Boolean whether the user is authorized according to the permissions
[ "Matches", "the", "roles", "of", "the", "user", "and", "the", "roles", "in", "the", "given", "permissions" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/AbstractPermissionManager.php#L375-L398
train
iherwig/wcmf
src/wcmf/lib/security/impl/AbstractPermissionManager.php
AbstractPermissionManager.matchRole
protected function matchRole(User $user, $role, $resource) { $isDynamicRole = isset($this->dynamicRoles[$role]); return (($isDynamicRole && $this->dynamicRoles[$role]->match($user, $resource) === true) || (!$isDynamicRole && $user->hasRole($role))); }
php
protected function matchRole(User $user, $role, $resource) { $isDynamicRole = isset($this->dynamicRoles[$role]); return (($isDynamicRole && $this->dynamicRoles[$role]->match($user, $resource) === true) || (!$isDynamicRole && $user->hasRole($role))); }
[ "protected", "function", "matchRole", "(", "User", "$", "user", ",", "$", "role", ",", "$", "resource", ")", "{", "$", "isDynamicRole", "=", "isset", "(", "$", "this", "->", "dynamicRoles", "[", "$", "role", "]", ")", ";", "return", "(", "(", "$", ...
Check if a user matches the role for a resource @param $user The user instance. @param $role The role name. @param $resource The resource string to authorize. @return Boolean
[ "Check", "if", "a", "user", "matches", "the", "role", "for", "a", "resource" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/AbstractPermissionManager.php#L407-L411
train
GW2Treasures/gw2api
src/V2/Endpoint/Continent/MapEndpoint.php
MapEndpoint.poisOf
public function poisOf( $map ) { return new PoiEndpoint( $this->api, $this->continent, $this->floor, $this->region, $map ); }
php
public function poisOf( $map ) { return new PoiEndpoint( $this->api, $this->continent, $this->floor, $this->region, $map ); }
[ "public", "function", "poisOf", "(", "$", "map", ")", "{", "return", "new", "PoiEndpoint", "(", "$", "this", "->", "api", ",", "$", "this", "->", "continent", ",", "$", "this", "->", "floor", ",", "$", "this", "->", "region", ",", "$", "map", ")", ...
Get the maps points of interest. @param int $map @return PoiEndpoint
[ "Get", "the", "maps", "points", "of", "interest", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Endpoint/Continent/MapEndpoint.php#L52-L54
train
GW2Treasures/gw2api
src/V2/Endpoint/Continent/MapEndpoint.php
MapEndpoint.tasksOf
public function tasksOf( $map ) { return new TaskEndpoint( $this->api, $this->continent, $this->floor, $this->region, $map ); }
php
public function tasksOf( $map ) { return new TaskEndpoint( $this->api, $this->continent, $this->floor, $this->region, $map ); }
[ "public", "function", "tasksOf", "(", "$", "map", ")", "{", "return", "new", "TaskEndpoint", "(", "$", "this", "->", "api", ",", "$", "this", "->", "continent", ",", "$", "this", "->", "floor", ",", "$", "this", "->", "region", ",", "$", "map", ")"...
Get the maps tasks. @param int $map @return TaskEndpoint
[ "Get", "the", "maps", "tasks", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Endpoint/Continent/MapEndpoint.php#L63-L65
train
GW2Treasures/gw2api
src/V2/Endpoint/Continent/MapEndpoint.php
MapEndpoint.sectorsOf
public function sectorsOf( $map ) { return new SectorEndpoint( $this->api, $this->continent, $this->floor, $this->region, $map ); }
php
public function sectorsOf( $map ) { return new SectorEndpoint( $this->api, $this->continent, $this->floor, $this->region, $map ); }
[ "public", "function", "sectorsOf", "(", "$", "map", ")", "{", "return", "new", "SectorEndpoint", "(", "$", "this", "->", "api", ",", "$", "this", "->", "continent", ",", "$", "this", "->", "floor", ",", "$", "this", "->", "region", ",", "$", "map", ...
Get the maps sectors. @param int $map @return SectorEndpoint
[ "Get", "the", "maps", "sectors", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Endpoint/Continent/MapEndpoint.php#L74-L76
train
iherwig/wcmf
src/wcmf/lib/pdf/PDF.php
PDF.numberOfLines
public function numberOfLines($width, $text) { $nbLines = 0; $lines = preg_split('/\n/', $text); foreach ($lines as $line) { $nbLines += $this->NbLines($width, $line); } return $nbLines; }
php
public function numberOfLines($width, $text) { $nbLines = 0; $lines = preg_split('/\n/', $text); foreach ($lines as $line) { $nbLines += $this->NbLines($width, $line); } return $nbLines; }
[ "public", "function", "numberOfLines", "(", "$", "width", ",", "$", "text", ")", "{", "$", "nbLines", "=", "0", ";", "$", "lines", "=", "preg_split", "(", "'/\\n/'", ",", "$", "text", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", ...
Computes the number of lines a MultiCell of width w will take instead of NbLines it correctly handles linebreaks @param $width The width @param $text The text
[ "Computes", "the", "number", "of", "lines", "a", "MultiCell", "of", "width", "w", "will", "take", "instead", "of", "NbLines", "it", "correctly", "handles", "linebreaks" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/pdf/PDF.php#L96-L103
train
iherwig/wcmf
src/wcmf/lib/pdf/PDF.php
PDF.CheckPageBreak
public function CheckPageBreak($h) { if($this->GetY()+$h>$this->PageBreakTrigger) { $this->AddPage($this->CurOrientation); return true; } return false; }
php
public function CheckPageBreak($h) { if($this->GetY()+$h>$this->PageBreakTrigger) { $this->AddPage($this->CurOrientation); return true; } return false; }
[ "public", "function", "CheckPageBreak", "(", "$", "h", ")", "{", "if", "(", "$", "this", "->", "GetY", "(", ")", "+", "$", "h", ">", "$", "this", "->", "PageBreakTrigger", ")", "{", "$", "this", "->", "AddPage", "(", "$", "this", "->", "CurOrientat...
If the height h would cause an overflow, add a new page immediately @param $h The height @return Boolean whether a new page was inserted or not
[ "If", "the", "height", "h", "would", "cause", "an", "overflow", "add", "a", "new", "page", "immediately" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/pdf/PDF.php#L115-L121
train
iherwig/wcmf
src/wcmf/lib/io/impl/FileCache.php
FileCache.initializeCache
private function initializeCache($section) { if (!isset($this->cache[$section])) { $file = $this->getCacheFile($section); if (file_exists($file)) { $this->cache[$section] = unserialize(file_get_contents($file)); } else { $this->cache[$section] = []; } } }
php
private function initializeCache($section) { if (!isset($this->cache[$section])) { $file = $this->getCacheFile($section); if (file_exists($file)) { $this->cache[$section] = unserialize(file_get_contents($file)); } else { $this->cache[$section] = []; } } }
[ "private", "function", "initializeCache", "(", "$", "section", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "cache", "[", "$", "section", "]", ")", ")", "{", "$", "file", "=", "$", "this", "->", "getCacheFile", "(", "$", "section", ")...
Initialize the cache @param $section The caching section
[ "Initialize", "the", "cache" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/impl/FileCache.php#L134-L144
train
iherwig/wcmf
src/wcmf/lib/io/impl/FileCache.php
FileCache.isExpired
private function isExpired($createTs, $lifetime) { if ($lifetime === null) { return false; } $expireDate = (new \DateTime())->setTimeStamp($createTs); if (intval($lifetime)) { $expireDate = $expireDate->modify('+'.$lifetime.' seconds'); } return $expireDate < new \DateTime(); }
php
private function isExpired($createTs, $lifetime) { if ($lifetime === null) { return false; } $expireDate = (new \DateTime())->setTimeStamp($createTs); if (intval($lifetime)) { $expireDate = $expireDate->modify('+'.$lifetime.' seconds'); } return $expireDate < new \DateTime(); }
[ "private", "function", "isExpired", "(", "$", "createTs", ",", "$", "lifetime", ")", "{", "if", "(", "$", "lifetime", "===", "null", ")", "{", "return", "false", ";", "}", "$", "expireDate", "=", "(", "new", "\\", "DateTime", "(", ")", ")", "->", "...
Check if an entry with the given creation timestamp and lifetime is expired @param $createTs The creation timestamp @param $lifetime The lifetime in seconds @return Boolean
[ "Check", "if", "an", "entry", "with", "the", "given", "creation", "timestamp", "and", "lifetime", "is", "expired" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/impl/FileCache.php#L152-L161
train
iherwig/wcmf
src/wcmf/lib/io/impl/FileCache.php
FileCache.saveCache
private function saveCache($section) { $content = serialize($this->cache[$section]); $file = $this->getCacheFile($section); $this->fileUtil->mkdirRec(dirname($file)); $fh = fopen($file, "w"); if ($fh !== false) { fwrite($fh, $content); fclose($fh); } else { throw new ConfigurationException("The cache path is not writable: ".$file); } }
php
private function saveCache($section) { $content = serialize($this->cache[$section]); $file = $this->getCacheFile($section); $this->fileUtil->mkdirRec(dirname($file)); $fh = fopen($file, "w"); if ($fh !== false) { fwrite($fh, $content); fclose($fh); } else { throw new ConfigurationException("The cache path is not writable: ".$file); } }
[ "private", "function", "saveCache", "(", "$", "section", ")", "{", "$", "content", "=", "serialize", "(", "$", "this", "->", "cache", "[", "$", "section", "]", ")", ";", "$", "file", "=", "$", "this", "->", "getCacheFile", "(", "$", "section", ")", ...
Save the cache @param $section The caching section
[ "Save", "the", "cache" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/impl/FileCache.php#L167-L179
train
iherwig/wcmf
src/wcmf/lib/persistence/Criteria.php
Criteria.getId
public function getId() { $str = "[".$this->combineOperator."] ".$this->type.".".$this->attribute. " ".$this->operator.(is_array($this->value) ? sizeof($this->value) : ""); return $str; }
php
public function getId() { $str = "[".$this->combineOperator."] ".$this->type.".".$this->attribute. " ".$this->operator.(is_array($this->value) ? sizeof($this->value) : ""); return $str; }
[ "public", "function", "getId", "(", ")", "{", "$", "str", "=", "\"[\"", ".", "$", "this", "->", "combineOperator", ".", "\"] \"", ".", "$", "this", "->", "type", ".", "\".\"", ".", "$", "this", "->", "attribute", ".", "\" \"", ".", "$", "this", "->...
Get an identifier for the instance @return String
[ "Get", "an", "identifier", "for", "the", "instance" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/Criteria.php#L148-L152
train
iherwig/wcmf
src/wcmf/application/controller/SortController.php
SortController.doMoveBefore
protected function doMoveBefore() { $request = $this->getRequest(); $persistenceFacade = $this->getPersistenceFacade(); $isOrderBottom = $this->isOrderBotton($request); // load the moved object and the reference object $insertOid = ObjectId::parse($request->getValue('insertOid')); $referenceOid = ObjectId::parse($request->getValue('referenceOid')); $insertObject = $persistenceFacade->load($insertOid); $referenceObject = $isOrderBottom ? new NullNode() : $persistenceFacade->load($referenceOid); // check object existence $objectMap = ['insertOid' => $insertObject, 'referenceOid' => $referenceObject]; if ($this->checkObjects($objectMap)) { // determine the sort key $mapper = $insertObject->getMapper(); $type = $insertObject->getType(); $sortkeyDef = $mapper->getSortkey(); $sortkey = $sortkeyDef['sortFieldName']; $sortdir = strtoupper($sortkeyDef['sortDirection']); // get the sortkey values of the objects before and after the insert position if ($isOrderBottom) { $lastObject = $this->loadLastObject($type, $sortkey, $sortdir); $prevValue = $lastObject != null ? $this->getSortkeyValue($lastObject, $sortkey) : 1; $nextValue = ceil($sortdir == 'ASC' ? $prevValue+1 : $prevValue-1); } else { $nextValue = $this->getSortkeyValue($referenceObject, $sortkey); $prevObject = $this->loadPreviousObject($type, $sortkey, $nextValue, $sortdir); $prevValue = $prevObject != null ? $this->getSortkeyValue($prevObject, $sortkey) : ceil($sortdir == 'ASC' ? $nextValue-1 : $nextValue+1); } // set the sortkey value to the average $insertObject->setValue($sortkey, ($nextValue+$prevValue)/2); } }
php
protected function doMoveBefore() { $request = $this->getRequest(); $persistenceFacade = $this->getPersistenceFacade(); $isOrderBottom = $this->isOrderBotton($request); // load the moved object and the reference object $insertOid = ObjectId::parse($request->getValue('insertOid')); $referenceOid = ObjectId::parse($request->getValue('referenceOid')); $insertObject = $persistenceFacade->load($insertOid); $referenceObject = $isOrderBottom ? new NullNode() : $persistenceFacade->load($referenceOid); // check object existence $objectMap = ['insertOid' => $insertObject, 'referenceOid' => $referenceObject]; if ($this->checkObjects($objectMap)) { // determine the sort key $mapper = $insertObject->getMapper(); $type = $insertObject->getType(); $sortkeyDef = $mapper->getSortkey(); $sortkey = $sortkeyDef['sortFieldName']; $sortdir = strtoupper($sortkeyDef['sortDirection']); // get the sortkey values of the objects before and after the insert position if ($isOrderBottom) { $lastObject = $this->loadLastObject($type, $sortkey, $sortdir); $prevValue = $lastObject != null ? $this->getSortkeyValue($lastObject, $sortkey) : 1; $nextValue = ceil($sortdir == 'ASC' ? $prevValue+1 : $prevValue-1); } else { $nextValue = $this->getSortkeyValue($referenceObject, $sortkey); $prevObject = $this->loadPreviousObject($type, $sortkey, $nextValue, $sortdir); $prevValue = $prevObject != null ? $this->getSortkeyValue($prevObject, $sortkey) : ceil($sortdir == 'ASC' ? $nextValue-1 : $nextValue+1); } // set the sortkey value to the average $insertObject->setValue($sortkey, ($nextValue+$prevValue)/2); } }
[ "protected", "function", "doMoveBefore", "(", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "$", "isOrderBottom", "=", "$", "this", ...
Execute the moveBefore action
[ "Execute", "the", "moveBefore", "action" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SortController.php#L154-L192
train
iherwig/wcmf
src/wcmf/application/controller/SortController.php
SortController.doInsertBefore
protected function doInsertBefore() { $request = $this->getRequest(); $persistenceFacade = $this->getPersistenceFacade(); $isOrderBottom = $this->isOrderBotton($request); // load the moved object, the reference object and the conainer object $insertOid = ObjectId::parse($request->getValue('insertOid')); $referenceOid = ObjectId::parse($request->getValue('referenceOid')); $containerOid = ObjectId::parse($request->getValue('containerOid')); $insertObject = $persistenceFacade->load($insertOid); $referenceObject = $isOrderBottom ? new NullNode() : $persistenceFacade->load($referenceOid); $containerObject = $persistenceFacade->load($containerOid); // check object existence $objectMap = ['insertOid' => $insertObject, 'referenceOid' => $referenceObject, 'containerOid' => $containerObject]; if ($this->checkObjects($objectMap)) { $role = $request->getValue('role'); $originalChildren = $containerObject->getValue($role); // add the new node to the container, if it is not yet $nodeExists = sizeof(Node::filter($originalChildren, $insertOid)) == 1; if (!$nodeExists) { $containerObject->addNode($insertObject, $role); } // reorder the children list $orderedChildren = []; foreach ($originalChildren as $curChild) { $oid = $curChild->getOID(); if ($oid == $referenceOid) { $orderedChildren[] = $insertObject; } if ($oid != $insertOid) { $orderedChildren[] = $curChild; } } // get the sortkey values of the objects before and after the insert position if ($isOrderBottom) { $orderedChildren[] = $insertObject; } $containerObject->setNodeOrder($orderedChildren, [$insertObject], $role); } }
php
protected function doInsertBefore() { $request = $this->getRequest(); $persistenceFacade = $this->getPersistenceFacade(); $isOrderBottom = $this->isOrderBotton($request); // load the moved object, the reference object and the conainer object $insertOid = ObjectId::parse($request->getValue('insertOid')); $referenceOid = ObjectId::parse($request->getValue('referenceOid')); $containerOid = ObjectId::parse($request->getValue('containerOid')); $insertObject = $persistenceFacade->load($insertOid); $referenceObject = $isOrderBottom ? new NullNode() : $persistenceFacade->load($referenceOid); $containerObject = $persistenceFacade->load($containerOid); // check object existence $objectMap = ['insertOid' => $insertObject, 'referenceOid' => $referenceObject, 'containerOid' => $containerObject]; if ($this->checkObjects($objectMap)) { $role = $request->getValue('role'); $originalChildren = $containerObject->getValue($role); // add the new node to the container, if it is not yet $nodeExists = sizeof(Node::filter($originalChildren, $insertOid)) == 1; if (!$nodeExists) { $containerObject->addNode($insertObject, $role); } // reorder the children list $orderedChildren = []; foreach ($originalChildren as $curChild) { $oid = $curChild->getOID(); if ($oid == $referenceOid) { $orderedChildren[] = $insertObject; } if ($oid != $insertOid) { $orderedChildren[] = $curChild; } } // get the sortkey values of the objects before and after the insert position if ($isOrderBottom) { $orderedChildren[] = $insertObject; } $containerObject->setNodeOrder($orderedChildren, [$insertObject], $role); } }
[ "protected", "function", "doInsertBefore", "(", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "$", "isOrderBottom", "=", "$", "this", ...
Execute the insertBefore action
[ "Execute", "the", "insertBefore", "action" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SortController.php#L197-L240
train
iherwig/wcmf
src/wcmf/application/controller/SortController.php
SortController.loadPreviousObject
protected function loadPreviousObject($type, $sortkeyName, $sortkeyValue, $sortDirection) { $query = new ObjectQuery($type); $tpl = $query->getObjectTemplate($type); $tpl->setValue($sortkeyName, Criteria::asValue($sortDirection == 'ASC' ? '<' : '>', $sortkeyValue), true); $pagingInfo = new PagingInfo(1, true); $objects = $query->execute(BuildDepth::SINGLE, [$sortkeyName." ".($sortDirection == 'ASC' ? 'DESC' : 'ASC')], $pagingInfo); return sizeof($objects) > 0 ? $objects[0] : null; }
php
protected function loadPreviousObject($type, $sortkeyName, $sortkeyValue, $sortDirection) { $query = new ObjectQuery($type); $tpl = $query->getObjectTemplate($type); $tpl->setValue($sortkeyName, Criteria::asValue($sortDirection == 'ASC' ? '<' : '>', $sortkeyValue), true); $pagingInfo = new PagingInfo(1, true); $objects = $query->execute(BuildDepth::SINGLE, [$sortkeyName." ".($sortDirection == 'ASC' ? 'DESC' : 'ASC')], $pagingInfo); return sizeof($objects) > 0 ? $objects[0] : null; }
[ "protected", "function", "loadPreviousObject", "(", "$", "type", ",", "$", "sortkeyName", ",", "$", "sortkeyValue", ",", "$", "sortDirection", ")", "{", "$", "query", "=", "new", "ObjectQuery", "(", "$", "type", ")", ";", "$", "tpl", "=", "$", "query", ...
Load the object which order position is before the given sort value @param $type The type of objects @param $sortkeyName The name of the sortkey attribute @param $sortkeyValue The reference sortkey value @param $sortDirection The sort direction used with the sort key
[ "Load", "the", "object", "which", "order", "position", "is", "before", "the", "given", "sort", "value" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SortController.php#L249-L256
train
iherwig/wcmf
src/wcmf/application/controller/SortController.php
SortController.loadLastObject
protected function loadLastObject($type, $sortkeyName, $sortDirection) { $query = new ObjectQuery($type); $pagingInfo = new PagingInfo(1, true); $invSortDir = $sortDirection == 'ASC' ? 'DESC' : 'ASC'; $objects = $query->execute(BuildDepth::SINGLE, [$sortkeyName." ".$invSortDir], $pagingInfo); return sizeof($objects) > 0 ? $objects[0] : null; }
php
protected function loadLastObject($type, $sortkeyName, $sortDirection) { $query = new ObjectQuery($type); $pagingInfo = new PagingInfo(1, true); $invSortDir = $sortDirection == 'ASC' ? 'DESC' : 'ASC'; $objects = $query->execute(BuildDepth::SINGLE, [$sortkeyName." ".$invSortDir], $pagingInfo); return sizeof($objects) > 0 ? $objects[0] : null; }
[ "protected", "function", "loadLastObject", "(", "$", "type", ",", "$", "sortkeyName", ",", "$", "sortDirection", ")", "{", "$", "query", "=", "new", "ObjectQuery", "(", "$", "type", ")", ";", "$", "pagingInfo", "=", "new", "PagingInfo", "(", "1", ",", ...
Load the last object regarding the given sort key @param $type The type of objects @param $sortkeyName The name of the sortkey attribute @param $sortDirection The sort direction used with the sort key
[ "Load", "the", "last", "object", "regarding", "the", "given", "sort", "key" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SortController.php#L264-L270
train
iherwig/wcmf
src/wcmf/application/controller/SortController.php
SortController.checkObjects
protected function checkObjects($objectMap) { $response = $this->getResponse(); $invalidOids = []; foreach ($objectMap as $parameterName => $object) { if ($object == null) { $invalidOids[] = $parameterName; } } if (sizeof($invalidOids) > 0) { $response->addError(ApplicationError::get('OID_INVALID', ['invalidOids' => $invalidOids])); return false; } return true; }
php
protected function checkObjects($objectMap) { $response = $this->getResponse(); $invalidOids = []; foreach ($objectMap as $parameterName => $object) { if ($object == null) { $invalidOids[] = $parameterName; } } if (sizeof($invalidOids) > 0) { $response->addError(ApplicationError::get('OID_INVALID', ['invalidOids' => $invalidOids])); return false; } return true; }
[ "protected", "function", "checkObjects", "(", "$", "objectMap", ")", "{", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "$", "invalidOids", "=", "[", "]", ";", "foreach", "(", "$", "objectMap", "as", "$", "parameterName", "=>", ...
Check if all objects in the given array are not null and add an OID_INVALID error to the response, if at least one is @param $objectMap An associative array with the controller parameter names as keys and the objects to check as values @return Boolean
[ "Check", "if", "all", "objects", "in", "the", "given", "array", "are", "not", "null", "and", "add", "an", "OID_INVALID", "error", "to", "the", "response", "if", "at", "least", "one", "is" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SortController.php#L279-L293
train
iherwig/wcmf
src/wcmf/application/controller/SortController.php
SortController.getSortkeyValue
protected function getSortkeyValue($object, $valueName) { $value = $object->getValue($valueName); if ($value == null) { $value = $object->getOID()->getFirstId(); } return $value; }
php
protected function getSortkeyValue($object, $valueName) { $value = $object->getValue($valueName); if ($value == null) { $value = $object->getOID()->getFirstId(); } return $value; }
[ "protected", "function", "getSortkeyValue", "(", "$", "object", ",", "$", "valueName", ")", "{", "$", "value", "=", "$", "object", "->", "getValue", "(", "$", "valueName", ")", ";", "if", "(", "$", "value", "==", "null", ")", "{", "$", "value", "=", ...
Get the sortkey value of an object. Defaults to the object's id, if the value is null @param $object The object @param $valueName The name of the sortkey attribute @return String
[ "Get", "the", "sortkey", "value", "of", "an", "object", ".", "Defaults", "to", "the", "object", "s", "id", "if", "the", "value", "is", "null" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SortController.php#L311-L317
train
iherwig/wcmf
src/wcmf/lib/persistence/ObjectComparator.php
ObjectComparator.compare
public function compare(PersistentObject $a, PersistentObject $b) { // we compare for each criteria and sum the results for $a, $b // afterwards we compare the sums and return -1,0,1 appropriate $sumA = 0; $sumB = 0; $maxWeight = sizeOf($this->sortCriteria); $i = 0; foreach ($this->sortCriteria as $criteria => $sortType) { $weightedValue = ($maxWeight-$i)*($maxWeight-$i); $aGreaterB = 0; // sort by id if ($criteria == self::ATTRIB_OID) { if ($a->getOID() != $b->getOID()) { ($a->getOID() > $b->getOID()) ? $aGreaterB = 1 : $aGreaterB = -1; } } // sort by type else if ($criteria == self::ATTRIB_TYPE) { if ($a->getType() != $b->getType()) { ($a->getType() > $b->getType()) ? $aGreaterB = 1 : $aGreaterB = -1; } } // sort by value else if($a->getValue($criteria) != null || $b->getValue($criteria) != null) { $aValue = strToLower($a->getValue($criteria)); $bValue = strToLower($b->getValue($criteria)); if ($aValue != $bValue) { ($aValue > $bValue) ? $aGreaterB = 1 : $aGreaterB = -1; } } // sort by property else if($a->getProperty($criteria) != null || $b->getProperty($criteria) != null) { $aProperty = strToLower($a->getProperty($criteria)); $bProperty = strToLower($b->getProperty($criteria)); if ($aProperty != $bProperty) { ($aProperty > $bProperty) ? $aGreaterB = 1 : $aGreaterB = -1; } } // calculate result of current criteria depending on current sorttype if ($sortType == self::SORTTYPE_ASC) { if ($aGreaterB == 1) { $sumA += $weightedValue; } else if ($aGreaterB == -1) { $sumB += $weightedValue; } } else if ($sortType == self::SORTTYPE_DESC) { if ($aGreaterB == 1) { $sumB += $weightedValue; } else if ($aGreaterB == -1) { $sumA += $weightedValue; } } else { throw new IllegalArgumentException("Unknown SORTTYPE."); } $i++; } if ($sumA == $sumB) { return 0; } return ($sumA > $sumB) ? 1 : -1; }
php
public function compare(PersistentObject $a, PersistentObject $b) { // we compare for each criteria and sum the results for $a, $b // afterwards we compare the sums and return -1,0,1 appropriate $sumA = 0; $sumB = 0; $maxWeight = sizeOf($this->sortCriteria); $i = 0; foreach ($this->sortCriteria as $criteria => $sortType) { $weightedValue = ($maxWeight-$i)*($maxWeight-$i); $aGreaterB = 0; // sort by id if ($criteria == self::ATTRIB_OID) { if ($a->getOID() != $b->getOID()) { ($a->getOID() > $b->getOID()) ? $aGreaterB = 1 : $aGreaterB = -1; } } // sort by type else if ($criteria == self::ATTRIB_TYPE) { if ($a->getType() != $b->getType()) { ($a->getType() > $b->getType()) ? $aGreaterB = 1 : $aGreaterB = -1; } } // sort by value else if($a->getValue($criteria) != null || $b->getValue($criteria) != null) { $aValue = strToLower($a->getValue($criteria)); $bValue = strToLower($b->getValue($criteria)); if ($aValue != $bValue) { ($aValue > $bValue) ? $aGreaterB = 1 : $aGreaterB = -1; } } // sort by property else if($a->getProperty($criteria) != null || $b->getProperty($criteria) != null) { $aProperty = strToLower($a->getProperty($criteria)); $bProperty = strToLower($b->getProperty($criteria)); if ($aProperty != $bProperty) { ($aProperty > $bProperty) ? $aGreaterB = 1 : $aGreaterB = -1; } } // calculate result of current criteria depending on current sorttype if ($sortType == self::SORTTYPE_ASC) { if ($aGreaterB == 1) { $sumA += $weightedValue; } else if ($aGreaterB == -1) { $sumB += $weightedValue; } } else if ($sortType == self::SORTTYPE_DESC) { if ($aGreaterB == 1) { $sumB += $weightedValue; } else if ($aGreaterB == -1) { $sumA += $weightedValue; } } else { throw new IllegalArgumentException("Unknown SORTTYPE."); } $i++; } if ($sumA == $sumB) { return 0; } return ($sumA > $sumB) ? 1 : -1; }
[ "public", "function", "compare", "(", "PersistentObject", "$", "a", ",", "PersistentObject", "$", "b", ")", "{", "// we compare for each criteria and sum the results for $a, $b", "// afterwards we compare the sums and return -1,0,1 appropriate", "$", "sumA", "=", "0", ";", "$...
Compare function for sorting PersitentObject instances by the list of criterias @param $a First PersitentObject instance @param $b First PersitentObject instance @return -1, 0 or 1 whether a is less, equal or greater than b in respect of the criteria
[ "Compare", "function", "for", "sorting", "PersitentObject", "instances", "by", "the", "list", "of", "criterias" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/ObjectComparator.php#L85-L139
train
iherwig/wcmf
src/wcmf/lib/model/visitor/LayoutVisitor.php
LayoutVisitor.calculatePosition
private function calculatePosition($obj) { $parent = & $obj->getParent(); if (!$parent) { // start here $position = new Position(0, 0, 0); } else { $position = new Position(0, 0, 0); $parentPos = $this->map[$parent->getOID()]; $position->y = $parentPos->y + 1; $position->z = $parentPos->z + 1; $siblings = $parent->getChildren(); if ($siblings[0]->getOID() == $obj->getOID()) { $position->x = $parentPos->x; } else { // find leftmost sibling of object for ($i=0; $i<sizeOf($siblings); $i++) { if ($siblings[$i]->getOID() == $obj->getOID()) { $leftSibling = & $siblings[$i-1]; } } // find x-coordinate of rightmost descendant of leftmost sibling $maxX = 0; $nIter = new NodeIterator($leftSibling); foreach($nIter as $oid => $curObject) { $curPosition = $this->map[$curObject->getOID()]; if ($curPosition->x >= $maxX) { $maxX = $curPosition->x; } } $position->x = $maxX+2; // reposition parents while ($parent != null) { $this->map[$parent->getOID()]->x += 1; $parent = $parent->getParent(); } } } return $position; }
php
private function calculatePosition($obj) { $parent = & $obj->getParent(); if (!$parent) { // start here $position = new Position(0, 0, 0); } else { $position = new Position(0, 0, 0); $parentPos = $this->map[$parent->getOID()]; $position->y = $parentPos->y + 1; $position->z = $parentPos->z + 1; $siblings = $parent->getChildren(); if ($siblings[0]->getOID() == $obj->getOID()) { $position->x = $parentPos->x; } else { // find leftmost sibling of object for ($i=0; $i<sizeOf($siblings); $i++) { if ($siblings[$i]->getOID() == $obj->getOID()) { $leftSibling = & $siblings[$i-1]; } } // find x-coordinate of rightmost descendant of leftmost sibling $maxX = 0; $nIter = new NodeIterator($leftSibling); foreach($nIter as $oid => $curObject) { $curPosition = $this->map[$curObject->getOID()]; if ($curPosition->x >= $maxX) { $maxX = $curPosition->x; } } $position->x = $maxX+2; // reposition parents while ($parent != null) { $this->map[$parent->getOID()]->x += 1; $parent = $parent->getParent(); } } } return $position; }
[ "private", "function", "calculatePosition", "(", "$", "obj", ")", "{", "$", "parent", "=", "&", "$", "obj", "->", "getParent", "(", ")", ";", "if", "(", "!", "$", "parent", ")", "{", "// start here", "$", "position", "=", "new", "Position", "(", "0",...
Calculate the object's position using the described algorithm. @param $obj PersistentObject instance
[ "Calculate", "the", "object", "s", "position", "using", "the", "described", "algorithm", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/visitor/LayoutVisitor.php#L75-L116
train
iherwig/wcmf
src/wcmf/lib/util/DBUtil.php
DBUtil.executeScript
public static function executeScript($file, $initSection) { $logger = LogManager::getLogger(__CLASS__); if (file_exists($file)) { $logger->info('Executing SQL script '.$file.' ...'); // find init params $config = ObjectFactory::getInstance('configuration'); if (($connectionParams = $config->getSection($initSection)) === false) { throw new ConfigurationException("No '".$initSection."' section given in configfile."); } // connect to the database $conn = self::createConnection($connectionParams); $logger->debug('Starting transaction ...'); $conn->beginTransaction(); $exception = null; $fh = fopen($file, 'r'); if ($fh) { while (!feof($fh)) { $command = fgets($fh, 8192); if (strlen(trim($command)) > 0) { $logger->debug('Executing command: '.preg_replace('/[\n]+$/', '', $command)); try { $conn->query($command); } catch(\Exception $ex) { $exception = $ex; break; } } } fclose($fh); } if ($exception == null) { $logger->debug('Execution succeeded, committing ...'); $conn->commit(); } else { $logger->error('Execution failed. Reason'.$exception->getMessage()); $logger->debug('Rolling back ...'); $conn->rollBack(); } $logger->debug('Finished SQL script '.$file.'.'); } else { $logger->error('SQL script '.$file.' not found.'); } }
php
public static function executeScript($file, $initSection) { $logger = LogManager::getLogger(__CLASS__); if (file_exists($file)) { $logger->info('Executing SQL script '.$file.' ...'); // find init params $config = ObjectFactory::getInstance('configuration'); if (($connectionParams = $config->getSection($initSection)) === false) { throw new ConfigurationException("No '".$initSection."' section given in configfile."); } // connect to the database $conn = self::createConnection($connectionParams); $logger->debug('Starting transaction ...'); $conn->beginTransaction(); $exception = null; $fh = fopen($file, 'r'); if ($fh) { while (!feof($fh)) { $command = fgets($fh, 8192); if (strlen(trim($command)) > 0) { $logger->debug('Executing command: '.preg_replace('/[\n]+$/', '', $command)); try { $conn->query($command); } catch(\Exception $ex) { $exception = $ex; break; } } } fclose($fh); } if ($exception == null) { $logger->debug('Execution succeeded, committing ...'); $conn->commit(); } else { $logger->error('Execution failed. Reason'.$exception->getMessage()); $logger->debug('Rolling back ...'); $conn->rollBack(); } $logger->debug('Finished SQL script '.$file.'.'); } else { $logger->error('SQL script '.$file.' not found.'); } }
[ "public", "static", "function", "executeScript", "(", "$", "file", ",", "$", "initSection", ")", "{", "$", "logger", "=", "LogManager", "::", "getLogger", "(", "__CLASS__", ")", ";", "if", "(", "file_exists", "(", "$", "file", ")", ")", "{", "$", "logg...
Execute a sql script. Execution is done inside a transaction, which is rolled back in case of failure. @param $file The filename of the sql script @param $initSection The name of the configuration section that defines the database connection @return Boolean whether execution succeeded or not.
[ "Execute", "a", "sql", "script", ".", "Execution", "is", "done", "inside", "a", "transaction", "which", "is", "rolled", "back", "in", "case", "of", "failure", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DBUtil.php#L88-L136
train
iherwig/wcmf
src/wcmf/lib/util/DBUtil.php
DBUtil.createDatabase
public static function createDatabase($name, $server, $user, $password) { $created = false; if($name && $server && $user) { // setup connection $conn =null; try { $conn = new PDO("mysql:host=$server", $user, $password); } catch(\Exception $ex) { throw new PersistenceException("Couldn't connect to MySql: ".$ex->getMessage()); } // create database $sqlStmt = "CREATE DATABASE IF NOT EXISTS ".$name; $result = $conn->query($sqlStmt); if ($result) { $created = true; } if (!$created) { throw new PersistenceException("Couldn't create database: ".$conn->errorInfo()); } } }
php
public static function createDatabase($name, $server, $user, $password) { $created = false; if($name && $server && $user) { // setup connection $conn =null; try { $conn = new PDO("mysql:host=$server", $user, $password); } catch(\Exception $ex) { throw new PersistenceException("Couldn't connect to MySql: ".$ex->getMessage()); } // create database $sqlStmt = "CREATE DATABASE IF NOT EXISTS ".$name; $result = $conn->query($sqlStmt); if ($result) { $created = true; } if (!$created) { throw new PersistenceException("Couldn't create database: ".$conn->errorInfo()); } } }
[ "public", "static", "function", "createDatabase", "(", "$", "name", ",", "$", "server", ",", "$", "user", ",", "$", "password", ")", "{", "$", "created", "=", "false", ";", "if", "(", "$", "name", "&&", "$", "server", "&&", "$", "user", ")", "{", ...
Crate a database on the server. This works only for MySQL databases. @param $name The name of the source database @param $server The name of the database server @param $user The user name @param $password The password
[ "Crate", "a", "database", "on", "the", "server", ".", "This", "works", "only", "for", "MySQL", "databases", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/DBUtil.php#L194-L215
train
GW2Treasures/gw2api
src/V2/Pagination/PaginatedEndpoint.php
PaginatedEndpoint.all
public function all() { $size = $this->maxPageSize(); $firstPageResponse = $this->request( $this->createPaginatedRequestQuery( 0, $size ) ); $header_values = $firstPageResponse->getResponse()->getHeader('X-Result-Total'); $total = array_shift($header_values); $result = $firstPageResponse->json(); if( $total <= $size ) { return $result; } $requests = []; for( $page = 1; $page < ceil( $total / $size ); $page++ ) { $requests[] = $this->createPaginatedRequestQuery( $page, $size ); } $responses = $this->requestMany( $requests ); foreach( $responses as $response ) { $result = array_merge( $result, $response->json() ); } return $result; }
php
public function all() { $size = $this->maxPageSize(); $firstPageResponse = $this->request( $this->createPaginatedRequestQuery( 0, $size ) ); $header_values = $firstPageResponse->getResponse()->getHeader('X-Result-Total'); $total = array_shift($header_values); $result = $firstPageResponse->json(); if( $total <= $size ) { return $result; } $requests = []; for( $page = 1; $page < ceil( $total / $size ); $page++ ) { $requests[] = $this->createPaginatedRequestQuery( $page, $size ); } $responses = $this->requestMany( $requests ); foreach( $responses as $response ) { $result = array_merge( $result, $response->json() ); } return $result; }
[ "public", "function", "all", "(", ")", "{", "$", "size", "=", "$", "this", "->", "maxPageSize", "(", ")", ";", "$", "firstPageResponse", "=", "$", "this", "->", "request", "(", "$", "this", "->", "createPaginatedRequestQuery", "(", "0", ",", "$", "size...
All entries. @return array
[ "All", "entries", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Pagination/PaginatedEndpoint.php#L27-L52
train
GW2Treasures/gw2api
src/V2/Pagination/PaginatedEndpoint.php
PaginatedEndpoint.page
public function page( $page, $size = null ) { if( is_null( $size )) { $size = $this->maxPageSize(); } if( $size > $this->maxPageSize() || $size <= 0 ) { throw new OutOfRangeException('$size has to be between 0 and ' . $this->maxPageSize() . ', was ' . $size ); } if( $page < 0 ) { throw new OutOfRangeException('$page has to be 0 or greater'); } return $this->request( $this->createPaginatedRequestQuery( $page, $size ) )->json(); }
php
public function page( $page, $size = null ) { if( is_null( $size )) { $size = $this->maxPageSize(); } if( $size > $this->maxPageSize() || $size <= 0 ) { throw new OutOfRangeException('$size has to be between 0 and ' . $this->maxPageSize() . ', was ' . $size ); } if( $page < 0 ) { throw new OutOfRangeException('$page has to be 0 or greater'); } return $this->request( $this->createPaginatedRequestQuery( $page, $size ) )->json(); }
[ "public", "function", "page", "(", "$", "page", ",", "$", "size", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "size", ")", ")", "{", "$", "size", "=", "$", "this", "->", "maxPageSize", "(", ")", ";", "}", "if", "(", "$", "size", ">...
Get a single page. @param int $page @param int $size @return mixed
[ "Get", "a", "single", "page", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Pagination/PaginatedEndpoint.php#L61-L75
train
GW2Treasures/gw2api
src/V2/Pagination/PaginatedEndpoint.php
PaginatedEndpoint.batch
public function batch( $parallelRequests = null, callable $callback = null ) { /** @noinspection PhpParamsInspection */ if( !isset( $callback ) && is_callable( $parallelRequests )) { $callback = $parallelRequests; $parallelRequests = null; } if( is_null( $parallelRequests )) { $parallelRequests = 6; } $size = $this->maxPageSize(); $firstPageResponse = $this->request( $this->createPaginatedRequestQuery( 0, $size ) ); $header_values = $firstPageResponse->getResponse()->getHeader('X-Result-Total'); $total = array_shift($header_values); call_user_func( $callback, $firstPageResponse->json() ); unset( $firstPageResponse ); $lastPage = ceil( $total / $size ); for( $page = 1; $page < $lastPage; ) { $batchRequests = []; for( $batchPage = 0; $batchPage < $parallelRequests && $page + $batchPage < $lastPage; $batchPage++ ) { $batchRequests[] = $this->createPaginatedRequestQuery( $page + $batchPage, $size ); } $responses = $this->requestMany( $batchRequests ); foreach( $responses as $response ) { call_user_func( $callback, $response->json() ); } unset( $responses ); $page += $parallelRequests; } }
php
public function batch( $parallelRequests = null, callable $callback = null ) { /** @noinspection PhpParamsInspection */ if( !isset( $callback ) && is_callable( $parallelRequests )) { $callback = $parallelRequests; $parallelRequests = null; } if( is_null( $parallelRequests )) { $parallelRequests = 6; } $size = $this->maxPageSize(); $firstPageResponse = $this->request( $this->createPaginatedRequestQuery( 0, $size ) ); $header_values = $firstPageResponse->getResponse()->getHeader('X-Result-Total'); $total = array_shift($header_values); call_user_func( $callback, $firstPageResponse->json() ); unset( $firstPageResponse ); $lastPage = ceil( $total / $size ); for( $page = 1; $page < $lastPage; ) { $batchRequests = []; for( $batchPage = 0; $batchPage < $parallelRequests && $page + $batchPage < $lastPage; $batchPage++ ) { $batchRequests[] = $this->createPaginatedRequestQuery( $page + $batchPage, $size ); } $responses = $this->requestMany( $batchRequests ); foreach( $responses as $response ) { call_user_func( $callback, $response->json() ); } unset( $responses ); $page += $parallelRequests; } }
[ "public", "function", "batch", "(", "$", "parallelRequests", "=", "null", ",", "callable", "$", "callback", "=", "null", ")", "{", "/** @noinspection PhpParamsInspection */", "if", "(", "!", "isset", "(", "$", "callback", ")", "&&", "is_callable", "(", "$", ...
Get all entries in multiple small batches. @param int|null $parallelRequests [optional] @param callable $callback @return void
[ "Get", "all", "entries", "in", "multiple", "small", "batches", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Pagination/PaginatedEndpoint.php#L84-L123
train
iherwig/wcmf
src/wcmf/lib/presentation/format/impl/HtmlFormat.php
HtmlFormat.getValueDefFromInputControlName
protected static function getValueDefFromInputControlName($name) { if (strpos($name, 'value') !== 0) { return null; } $def = []; $fieldDelimiter = StringUtil::escapeForRegex(self::$inputFieldNameDelimiter); $pieces = preg_split('/'.$fieldDelimiter.'/', $name); if (sizeof($pieces) != 4) { return null; } array_shift($pieces); $def['language'] = array_shift($pieces); $def['name'] = array_shift($pieces); $def['oid'] = array_shift($pieces); return $def; }
php
protected static function getValueDefFromInputControlName($name) { if (strpos($name, 'value') !== 0) { return null; } $def = []; $fieldDelimiter = StringUtil::escapeForRegex(self::$inputFieldNameDelimiter); $pieces = preg_split('/'.$fieldDelimiter.'/', $name); if (sizeof($pieces) != 4) { return null; } array_shift($pieces); $def['language'] = array_shift($pieces); $def['name'] = array_shift($pieces); $def['oid'] = array_shift($pieces); return $def; }
[ "protected", "static", "function", "getValueDefFromInputControlName", "(", "$", "name", ")", "{", "if", "(", "strpos", "(", "$", "name", ",", "'value'", ")", "!==", "0", ")", "{", "return", "null", ";", "}", "$", "def", "=", "[", "]", ";", "$", "fiel...
Get the object value definition from a HTML input field name. @param $name The name of input field in the format value-`language`-`name`-`oid`, where name is the name of the attribute belonging to the node defined by oid @return An associative array with keys 'oid', 'language', 'name' or null if the name is not valid
[ "Get", "the", "object", "value", "definition", "from", "a", "HTML", "input", "field", "name", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/HtmlFormat.php#L130-L146
train
iherwig/wcmf
src/wcmf/lib/presentation/format/impl/HtmlFormat.php
HtmlFormat.getTemplateFile
protected function getTemplateFile(Response $response) { if (self::$sharedView == null) { self::$sharedView = ObjectFactory::getInstance('view'); } // check if a view template is defined $viewTpl = self::$sharedView->getTemplate($response->getSender(), $response->getContext(), $response->getAction()); if (!$viewTpl) { throw new ConfigurationException("View definition missing for ". "response: ".$response->__toString()); } // check for html_format property in response // and add the suffix if existing $viewTplFile = WCMF_BASE.$viewTpl; $format = $response->getProperty('html_tpl_format'); if (isset($format)) { $ext = pathinfo($viewTplFile, PATHINFO_EXTENSION); $formatViewTplFile = dirname($viewTplFile).'/'.basename($viewTplFile, ".$ext").'-'.$format.'.'.$ext; } // give precedence to format specific file $finalTplFile = isset($formatViewTplFile) && file_exists($formatViewTplFile) ? $formatViewTplFile : $viewTplFile; return $finalTplFile; }
php
protected function getTemplateFile(Response $response) { if (self::$sharedView == null) { self::$sharedView = ObjectFactory::getInstance('view'); } // check if a view template is defined $viewTpl = self::$sharedView->getTemplate($response->getSender(), $response->getContext(), $response->getAction()); if (!$viewTpl) { throw new ConfigurationException("View definition missing for ". "response: ".$response->__toString()); } // check for html_format property in response // and add the suffix if existing $viewTplFile = WCMF_BASE.$viewTpl; $format = $response->getProperty('html_tpl_format'); if (isset($format)) { $ext = pathinfo($viewTplFile, PATHINFO_EXTENSION); $formatViewTplFile = dirname($viewTplFile).'/'.basename($viewTplFile, ".$ext").'-'.$format.'.'.$ext; } // give precedence to format specific file $finalTplFile = isset($formatViewTplFile) && file_exists($formatViewTplFile) ? $formatViewTplFile : $viewTplFile; return $finalTplFile; }
[ "protected", "function", "getTemplateFile", "(", "Response", "$", "response", ")", "{", "if", "(", "self", "::", "$", "sharedView", "==", "null", ")", "{", "self", "::", "$", "sharedView", "=", "ObjectFactory", "::", "getInstance", "(", "'view'", ")", ";",...
Get the template file for the given response @param $response
[ "Get", "the", "template", "file", "for", "the", "given", "response" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/HtmlFormat.php#L152-L177
train
iherwig/wcmf
src/wcmf/lib/persistence/ObjectId.php
ObjectId.parse
public static function parse($oid) { // fast checks first if ($oid instanceof ObjectId) { return $oid; } $oidParts = self::parseOidString($oid); $type = $oidParts['type']; $ids = $oidParts['id']; $prefix = $oidParts['prefix']; // check the type if (!ObjectFactory::getInstance('persistenceFacade')->isKnownType($type)) { return null; } // check if number of ids match the type $numPks = self::getNumberOfPKs($type); if ($numPks == null || $numPks != sizeof($ids)) { return null; } return new ObjectID($type, $ids, $prefix); }
php
public static function parse($oid) { // fast checks first if ($oid instanceof ObjectId) { return $oid; } $oidParts = self::parseOidString($oid); $type = $oidParts['type']; $ids = $oidParts['id']; $prefix = $oidParts['prefix']; // check the type if (!ObjectFactory::getInstance('persistenceFacade')->isKnownType($type)) { return null; } // check if number of ids match the type $numPks = self::getNumberOfPKs($type); if ($numPks == null || $numPks != sizeof($ids)) { return null; } return new ObjectID($type, $ids, $prefix); }
[ "public", "static", "function", "parse", "(", "$", "oid", ")", "{", "// fast checks first", "if", "(", "$", "oid", "instanceof", "ObjectId", ")", "{", "return", "$", "oid", ";", "}", "$", "oidParts", "=", "self", "::", "parseOidString", "(", "$", "oid", ...
Parse a serialized object id string into an ObjectId instance. @param $oid The string @return ObjectId or null, if the id cannot be parsed
[ "Parse", "a", "serialized", "object", "id", "string", "into", "an", "ObjectId", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/ObjectId.php#L134-L157
train
iherwig/wcmf
src/wcmf/lib/persistence/ObjectId.php
ObjectId.parseOidString
private static function parseOidString($oid) { if (strlen($oid) == 0) { return null; } $oidParts = preg_split(self::getDelimiterPattern(), $oid); if (sizeof($oidParts) < 2) { return null; } if (self::$idPattern == null) { self::$idPattern = '/^[0-9]*$|^'.self::$dummyIdPattern.'$/'; } // get the ids from the oid $ids = []; $nextPart = array_pop($oidParts); while($nextPart !== null && preg_match(self::$idPattern, $nextPart) == 1) { $intNextPart = (int)$nextPart; if ($nextPart == (string)$intNextPart) { $ids[] = $intNextPart; } else { $ids[] = $nextPart; } $nextPart = array_pop($oidParts); } $ids = array_reverse($ids); // get the type $type = $nextPart; // get the prefix $prefix = join(self::DELIMITER, $oidParts); return [ 'type' => $type, 'id' => $ids, 'prefix' => $prefix ]; }
php
private static function parseOidString($oid) { if (strlen($oid) == 0) { return null; } $oidParts = preg_split(self::getDelimiterPattern(), $oid); if (sizeof($oidParts) < 2) { return null; } if (self::$idPattern == null) { self::$idPattern = '/^[0-9]*$|^'.self::$dummyIdPattern.'$/'; } // get the ids from the oid $ids = []; $nextPart = array_pop($oidParts); while($nextPart !== null && preg_match(self::$idPattern, $nextPart) == 1) { $intNextPart = (int)$nextPart; if ($nextPart == (string)$intNextPart) { $ids[] = $intNextPart; } else { $ids[] = $nextPart; } $nextPart = array_pop($oidParts); } $ids = array_reverse($ids); // get the type $type = $nextPart; // get the prefix $prefix = join(self::DELIMITER, $oidParts); return [ 'type' => $type, 'id' => $ids, 'prefix' => $prefix ]; }
[ "private", "static", "function", "parseOidString", "(", "$", "oid", ")", "{", "if", "(", "strlen", "(", "$", "oid", ")", "==", "0", ")", "{", "return", "null", ";", "}", "$", "oidParts", "=", "preg_split", "(", "self", "::", "getDelimiterPattern", "(",...
Parse the given object id string into it's parts @param $oid The string @return Associative array with keys 'type', 'id', 'prefix'
[ "Parse", "the", "given", "object", "id", "string", "into", "it", "s", "parts" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/ObjectId.php#L164-L204
train
iherwig/wcmf
src/wcmf/lib/persistence/ObjectId.php
ObjectId.containsDummyIds
public function containsDummyIds() { foreach ($this->getId() as $id) { if (self::isDummyId($id)) { return true; } } return false; }
php
public function containsDummyIds() { foreach ($this->getId() as $id) { if (self::isDummyId($id)) { return true; } } return false; }
[ "public", "function", "containsDummyIds", "(", ")", "{", "foreach", "(", "$", "this", "->", "getId", "(", ")", "as", "$", "id", ")", "{", "if", "(", "self", "::", "isDummyId", "(", "$", "id", ")", ")", "{", "return", "true", ";", "}", "}", "retur...
Check if this object id contains a dummy id. @return Boolean
[ "Check", "if", "this", "object", "id", "contains", "a", "dummy", "id", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/ObjectId.php#L242-L249
train
iherwig/wcmf
src/wcmf/lib/persistence/ObjectId.php
ObjectId.getNumberOfPKs
private static function getNumberOfPKs($type) { if (!isset(self::$numPkKeys[$type])) { $numPKs = 1; $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); if ($persistenceFacade->isKnownType($type)) { $mapper = $persistenceFacade->getMapper($type); $numPKs = sizeof($mapper->getPKNames()); } self::$numPkKeys[$type] = $numPKs; } return self::$numPkKeys[$type]; }
php
private static function getNumberOfPKs($type) { if (!isset(self::$numPkKeys[$type])) { $numPKs = 1; $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); if ($persistenceFacade->isKnownType($type)) { $mapper = $persistenceFacade->getMapper($type); $numPKs = sizeof($mapper->getPKNames()); } self::$numPkKeys[$type] = $numPKs; } return self::$numPkKeys[$type]; }
[ "private", "static", "function", "getNumberOfPKs", "(", "$", "type", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "numPkKeys", "[", "$", "type", "]", ")", ")", "{", "$", "numPKs", "=", "1", ";", "$", "persistenceFacade", "=", "ObjectFac...
Get the number of primary keys a type has. @param $type The type @return Integer (1 if the type is unknown)
[ "Get", "the", "number", "of", "primary", "keys", "a", "type", "has", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/ObjectId.php#L256-L267
train
skie/plum_search
src/View/Helper/SearchHelper.php
SearchHelper.input
public function input(BaseParameter $param, $options = []) { $input = $this->_defaultInput($param); $this->_setValue($input, $param); $this->_setOptions($input, $param); $this->_applyAutocompleteOptions($input, $param); $input = Hash::merge($input, $options); return $input; }
php
public function input(BaseParameter $param, $options = []) { $input = $this->_defaultInput($param); $this->_setValue($input, $param); $this->_setOptions($input, $param); $this->_applyAutocompleteOptions($input, $param); $input = Hash::merge($input, $options); return $input; }
[ "public", "function", "input", "(", "BaseParameter", "$", "param", ",", "$", "options", "=", "[", "]", ")", "{", "$", "input", "=", "$", "this", "->", "_defaultInput", "(", "$", "param", ")", ";", "$", "this", "->", "_setValue", "(", "$", "input", ...
Generates input for parameter @param BaseParameter $param Form parameter. @param array $options Additional input options. @return array
[ "Generates", "input", "for", "parameter" ]
24d981e240bff7c15731981d6f9b3056abdaf80e
https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/View/Helper/SearchHelper.php#L64-L73
train
skie/plum_search
src/View/Helper/SearchHelper.php
SearchHelper._defaultInput
protected function _defaultInput($param) { $input = $param->formInputConfig(); $name = $param->config('name'); $input += [ 'type' => 'text', 'required' => false, 'label' => Inflector::humanize(preg_replace('/_id$/', '', $name)), ]; if (!$param->visible()) { $input['type'] = 'hidden'; } return $input; }
php
protected function _defaultInput($param) { $input = $param->formInputConfig(); $name = $param->config('name'); $input += [ 'type' => 'text', 'required' => false, 'label' => Inflector::humanize(preg_replace('/_id$/', '', $name)), ]; if (!$param->visible()) { $input['type'] = 'hidden'; } return $input; }
[ "protected", "function", "_defaultInput", "(", "$", "param", ")", "{", "$", "input", "=", "$", "param", "->", "formInputConfig", "(", ")", ";", "$", "name", "=", "$", "param", "->", "config", "(", "'name'", ")", ";", "$", "input", "+=", "[", "'type'"...
Generates default input for parameter @param BaseParameter $param Form parameter. @return array
[ "Generates", "default", "input", "for", "parameter" ]
24d981e240bff7c15731981d6f9b3056abdaf80e
https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/View/Helper/SearchHelper.php#L81-L95
train
skie/plum_search
src/View/Helper/SearchHelper.php
SearchHelper._setValue
protected function _setValue(&$input, $param) { $value = $param->value(); if (!$param->isEmpty()) { $input['value'] = $value; } else { $input['value'] = ''; } return $input; }
php
protected function _setValue(&$input, $param) { $value = $param->value(); if (!$param->isEmpty()) { $input['value'] = $value; } else { $input['value'] = ''; } return $input; }
[ "protected", "function", "_setValue", "(", "&", "$", "input", ",", "$", "param", ")", "{", "$", "value", "=", "$", "param", "->", "value", "(", ")", ";", "if", "(", "!", "$", "param", "->", "isEmpty", "(", ")", ")", "{", "$", "input", "[", "'va...
Set value for field @param array $input Field options. @param BaseParameter $param Form parameter. @return array
[ "Set", "value", "for", "field" ]
24d981e240bff7c15731981d6f9b3056abdaf80e
https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/View/Helper/SearchHelper.php#L104-L114
train
skie/plum_search
src/View/Helper/SearchHelper.php
SearchHelper._setOptions
protected function _setOptions(&$input, $param) { if ($param->hasOptions() && !isset($input['empty'])) { $input['empty'] = true; } return $input; }
php
protected function _setOptions(&$input, $param) { if ($param->hasOptions() && !isset($input['empty'])) { $input['empty'] = true; } return $input; }
[ "protected", "function", "_setOptions", "(", "&", "$", "input", ",", "$", "param", ")", "{", "if", "(", "$", "param", "->", "hasOptions", "(", ")", "&&", "!", "isset", "(", "$", "input", "[", "'empty'", "]", ")", ")", "{", "$", "input", "[", "'em...
Set options for field @param array $input Field options. @param BaseParameter $param Form parameter. @return array
[ "Set", "options", "for", "field" ]
24d981e240bff7c15731981d6f9b3056abdaf80e
https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/View/Helper/SearchHelper.php#L123-L130
train
skie/plum_search
src/View/Helper/SearchHelper.php
SearchHelper._applyAutocompleteOptions
protected function _applyAutocompleteOptions(&$input, $param) { if ($param instanceof AutocompleteParameter) { $input['data-url'] = $param->autocompleteUrl(); $input['class'] = 'autocomplete'; $input['data-name'] = $param->config('name'); } return $input; }
php
protected function _applyAutocompleteOptions(&$input, $param) { if ($param instanceof AutocompleteParameter) { $input['data-url'] = $param->autocompleteUrl(); $input['class'] = 'autocomplete'; $input['data-name'] = $param->config('name'); } return $input; }
[ "protected", "function", "_applyAutocompleteOptions", "(", "&", "$", "input", ",", "$", "param", ")", "{", "if", "(", "$", "param", "instanceof", "AutocompleteParameter", ")", "{", "$", "input", "[", "'data-url'", "]", "=", "$", "param", "->", "autocompleteU...
Set autocomplete settings for field @param array $input Field options. @param BaseParameter $param Form parameter. @return array
[ "Set", "autocomplete", "settings", "for", "field" ]
24d981e240bff7c15731981d6f9b3056abdaf80e
https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/View/Helper/SearchHelper.php#L139-L148
train
iherwig/wcmf
src/wcmf/lib/i18n/impl/DefaultLocalization.php
DefaultLocalization.loadTranslationImpl
protected function loadTranslationImpl(PersistentObject $object, $lang, $useDefaults=true) { if ($object == null) { throw new IllegalArgumentException('Cannot load translation for null'); } $oidStr = $object->getOID()->__toString(); $cacheKey = $oidStr.'.'.$lang.'.'.$useDefaults; if (!isset($this->translatedObjects[$cacheKey])) { $translatedObject = $object; // load the translations and translate the object for any language // different to the default language // NOTE: the original object will be detached from the transaction if ($lang != $this->getDefaultLanguage()) { $transaction = $this->persistenceFacade->getTransaction(); $transaction->detach($translatedObject->getOID()); $translatedObject = clone $object; $query = new ObjectQuery($this->translationType, __CLASS__.'load_save'); $tpl = $query->getObjectTemplate($this->translationType); $tpl->setValue('objectid', Criteria::asValue('=', $oidStr)); $tpl->setValue('language', Criteria::asValue('=', $lang)); $translationInstances = $query->execute(BuildDepth::SINGLE); // create map for faster access $translations = []; foreach ($translationInstances as $translationInstance) { $translations[$translationInstance->getValue('attribute')] = $translationInstance->getValue('translation'); } // set the translated values in the object $iter = new NodeValueIterator($object, false); for($iter->rewind(); $iter->valid(); $iter->next()) { $valueName = $iter->key(); $translation = isset($translations[$valueName]) ? $translations[$valueName] : ''; $this->setTranslatedValue($translatedObject, $valueName, $translation, $useDefaults); } } $this->translatedObjects[$cacheKey] = $translatedObject; } return $this->translatedObjects[$cacheKey]; }
php
protected function loadTranslationImpl(PersistentObject $object, $lang, $useDefaults=true) { if ($object == null) { throw new IllegalArgumentException('Cannot load translation for null'); } $oidStr = $object->getOID()->__toString(); $cacheKey = $oidStr.'.'.$lang.'.'.$useDefaults; if (!isset($this->translatedObjects[$cacheKey])) { $translatedObject = $object; // load the translations and translate the object for any language // different to the default language // NOTE: the original object will be detached from the transaction if ($lang != $this->getDefaultLanguage()) { $transaction = $this->persistenceFacade->getTransaction(); $transaction->detach($translatedObject->getOID()); $translatedObject = clone $object; $query = new ObjectQuery($this->translationType, __CLASS__.'load_save'); $tpl = $query->getObjectTemplate($this->translationType); $tpl->setValue('objectid', Criteria::asValue('=', $oidStr)); $tpl->setValue('language', Criteria::asValue('=', $lang)); $translationInstances = $query->execute(BuildDepth::SINGLE); // create map for faster access $translations = []; foreach ($translationInstances as $translationInstance) { $translations[$translationInstance->getValue('attribute')] = $translationInstance->getValue('translation'); } // set the translated values in the object $iter = new NodeValueIterator($object, false); for($iter->rewind(); $iter->valid(); $iter->next()) { $valueName = $iter->key(); $translation = isset($translations[$valueName]) ? $translations[$valueName] : ''; $this->setTranslatedValue($translatedObject, $valueName, $translation, $useDefaults); } } $this->translatedObjects[$cacheKey] = $translatedObject; } return $this->translatedObjects[$cacheKey]; }
[ "protected", "function", "loadTranslationImpl", "(", "PersistentObject", "$", "object", ",", "$", "lang", ",", "$", "useDefaults", "=", "true", ")", "{", "if", "(", "$", "object", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "'Can...
Load a translation of a single entity for a specific language. @param $object PersistentObject instance to load the translation into. The object is supposed to have it's values in the default language. @param $lang The language of the translation to load. @param $useDefaults Boolean whether to use the default language values for untranslated/empty values or not. Optional, default is true. @return PersistentObject instance @throws IllegalArgumentException
[ "Load", "a", "translation", "of", "a", "single", "entity", "for", "a", "specific", "language", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/i18n/impl/DefaultLocalization.php#L220-L262
train
iherwig/wcmf
src/wcmf/lib/i18n/impl/DefaultLocalization.php
DefaultLocalization.saveTranslationImpl
protected function saveTranslationImpl(PersistentObject $object, $lang) { // if the requested language is the default language, do nothing if ($lang == $this->getDefaultLanguage()) { // nothing to do } // save the translations for any other language else { $object->beforeUpdate(); // get the existing translations for the requested language $query = new ObjectQuery($this->translationType, __CLASS__.'load_save'); $tpl = $query->getObjectTemplate($this->translationType); $tpl->setValue('objectid', Criteria::asValue('=', $object->getOID()->__toString())); $tpl->setValue('language', Criteria::asValue('=', $lang)); $translationInstances = $query->execute(BuildDepth::SINGLE); // create map for faster access $translations = []; foreach ($translationInstances as $translationInstance) { $translations[$translationInstance->getValue('attribute')] = $translationInstance; } // save the translations, ignore pk values $pkNames = $object->getMapper()->getPkNames(); $iter = new NodeValueIterator($object, false); for($iter->rewind(); $iter->valid(); $iter->next()) { $valueName = $iter->key(); if (!in_array($valueName, $pkNames)) { $curIterNode = $iter->currentNode(); $translation = isset($translations[$valueName]) ? $translations[$valueName] : null; $this->saveTranslatedValue($curIterNode, $valueName, $translation, $lang); } } } }
php
protected function saveTranslationImpl(PersistentObject $object, $lang) { // if the requested language is the default language, do nothing if ($lang == $this->getDefaultLanguage()) { // nothing to do } // save the translations for any other language else { $object->beforeUpdate(); // get the existing translations for the requested language $query = new ObjectQuery($this->translationType, __CLASS__.'load_save'); $tpl = $query->getObjectTemplate($this->translationType); $tpl->setValue('objectid', Criteria::asValue('=', $object->getOID()->__toString())); $tpl->setValue('language', Criteria::asValue('=', $lang)); $translationInstances = $query->execute(BuildDepth::SINGLE); // create map for faster access $translations = []; foreach ($translationInstances as $translationInstance) { $translations[$translationInstance->getValue('attribute')] = $translationInstance; } // save the translations, ignore pk values $pkNames = $object->getMapper()->getPkNames(); $iter = new NodeValueIterator($object, false); for($iter->rewind(); $iter->valid(); $iter->next()) { $valueName = $iter->key(); if (!in_array($valueName, $pkNames)) { $curIterNode = $iter->currentNode(); $translation = isset($translations[$valueName]) ? $translations[$valueName] : null; $this->saveTranslatedValue($curIterNode, $valueName, $translation, $lang); } } } }
[ "protected", "function", "saveTranslationImpl", "(", "PersistentObject", "$", "object", ",", "$", "lang", ")", "{", "// if the requested language is the default language, do nothing", "if", "(", "$", "lang", "==", "$", "this", "->", "getDefaultLanguage", "(", ")", ")"...
Save a translation of a single entity for a specific language. Only the values that have a non-empty value are considered as translations and stored. @param $object An instance of the entity type that holds the translations as values. @param $lang The language of the translation.
[ "Save", "a", "translation", "of", "a", "single", "entity", "for", "a", "specific", "language", ".", "Only", "the", "values", "that", "have", "a", "non", "-", "empty", "value", "are", "considered", "as", "translations", "and", "stored", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/i18n/impl/DefaultLocalization.php#L291-L325
train
iherwig/wcmf
src/wcmf/lib/i18n/impl/DefaultLocalization.php
DefaultLocalization.setTranslatedValue
private function setTranslatedValue(PersistentObject $object, $valueName, $translation, $useDefaults) { $mapper = $object->getMapper(); $isTranslatable = $mapper != null && $mapper->hasAttribute($valueName) ? $mapper->getAttribute($valueName)->hasTag('TRANSLATABLE') : false; if ($isTranslatable) { // empty the value, if the default language values should not be used if (!$useDefaults) { $object->setValue($valueName, null, true); } // translate the value if (!($useDefaults && strlen($translation) == 0)) { $object->setValue($valueName, $translation, true); } } }
php
private function setTranslatedValue(PersistentObject $object, $valueName, $translation, $useDefaults) { $mapper = $object->getMapper(); $isTranslatable = $mapper != null && $mapper->hasAttribute($valueName) ? $mapper->getAttribute($valueName)->hasTag('TRANSLATABLE') : false; if ($isTranslatable) { // empty the value, if the default language values should not be used if (!$useDefaults) { $object->setValue($valueName, null, true); } // translate the value if (!($useDefaults && strlen($translation) == 0)) { $object->setValue($valueName, $translation, true); } } }
[ "private", "function", "setTranslatedValue", "(", "PersistentObject", "$", "object", ",", "$", "valueName", ",", "$", "translation", ",", "$", "useDefaults", ")", "{", "$", "mapper", "=", "$", "object", "->", "getMapper", "(", ")", ";", "$", "isTranslatable"...
Set a translated value in the given PersistentObject instance. @param $object The object to set the value on. The object is supposed to have it's values in the default language. @param $valueName The name of the value to translate @param $translation Translation for the value. @param $useDefaults Boolean whether to use the default language if no translation is found or not.
[ "Set", "a", "translated", "value", "in", "the", "given", "PersistentObject", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/i18n/impl/DefaultLocalization.php#L385-L398
train
iherwig/wcmf
src/wcmf/lib/i18n/impl/DefaultLocalization.php
DefaultLocalization.saveTranslatedValue
private function saveTranslatedValue(PersistentObject $object, $valueName, $existingTranslation, $lang) { $mapper = $object->getMapper(); $isTranslatable = $mapper != null && $mapper->hasAttribute($valueName) ? $mapper->getAttribute($valueName)->hasTag('TRANSLATABLE') : false; if ($isTranslatable) { $value = $object->getValue($valueName); $translation = $existingTranslation; $valueIsEmpty = $value === null || $value === ''; // if no translation exists and the value is not empty, create a new translation if ($translation == null && !$valueIsEmpty) { $translation = $this->persistenceFacade->create($this->translationType); } // if a translation exists and the value is empty, remove the existing translation if ($translation != null && $valueIsEmpty) { $translation->delete(); $translation = null; } if ($translation) { // set all required properties $oid = $object->getOID()->__toString(); $translation->setValue('objectid', $oid); $translation->setValue('attribute', $valueName); $translation->setValue('translation', $value); $translation->setValue('language', $lang); // store translation for oid update if necessary (see afterCreate()) if (!isset($this->createdTranslations[$oid])) { $this->createdTranslations[$oid] = []; } $this->createdTranslations[$oid][] = $translation; } } }
php
private function saveTranslatedValue(PersistentObject $object, $valueName, $existingTranslation, $lang) { $mapper = $object->getMapper(); $isTranslatable = $mapper != null && $mapper->hasAttribute($valueName) ? $mapper->getAttribute($valueName)->hasTag('TRANSLATABLE') : false; if ($isTranslatable) { $value = $object->getValue($valueName); $translation = $existingTranslation; $valueIsEmpty = $value === null || $value === ''; // if no translation exists and the value is not empty, create a new translation if ($translation == null && !$valueIsEmpty) { $translation = $this->persistenceFacade->create($this->translationType); } // if a translation exists and the value is empty, remove the existing translation if ($translation != null && $valueIsEmpty) { $translation->delete(); $translation = null; } if ($translation) { // set all required properties $oid = $object->getOID()->__toString(); $translation->setValue('objectid', $oid); $translation->setValue('attribute', $valueName); $translation->setValue('translation', $value); $translation->setValue('language', $lang); // store translation for oid update if necessary (see afterCreate()) if (!isset($this->createdTranslations[$oid])) { $this->createdTranslations[$oid] = []; } $this->createdTranslations[$oid][] = $translation; } } }
[ "private", "function", "saveTranslatedValue", "(", "PersistentObject", "$", "object", ",", "$", "valueName", ",", "$", "existingTranslation", ",", "$", "lang", ")", "{", "$", "mapper", "=", "$", "object", "->", "getMapper", "(", ")", ";", "$", "isTranslatabl...
Save translated values for the given object @param $object The object to save the translations on @param $valueName The name of the value to translate @param $existingTranslation Existing translation instance for the value (might be null). @param $lang The language of the translations.
[ "Save", "translated", "values", "for", "the", "given", "object" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/i18n/impl/DefaultLocalization.php#L407-L441
train
iherwig/wcmf
src/wcmf/lib/i18n/impl/DefaultLocalization.php
DefaultLocalization.afterCreate
public function afterCreate(PersistenceEvent $event) { if ($event->getAction() == PersistenceAction::CREATE) { $oldOid = $event->getOldOid(); $oldOidStr = $oldOid != null ? $oldOid->__toString() : null; if ($oldOidStr != null && isset($this->createdTranslations[$oldOidStr])) { foreach ($this->createdTranslations[$oldOidStr] as $translation) { $translation->setValue('objectid', $event->getObject()->getOID()->__toString()); } } } }
php
public function afterCreate(PersistenceEvent $event) { if ($event->getAction() == PersistenceAction::CREATE) { $oldOid = $event->getOldOid(); $oldOidStr = $oldOid != null ? $oldOid->__toString() : null; if ($oldOidStr != null && isset($this->createdTranslations[$oldOidStr])) { foreach ($this->createdTranslations[$oldOidStr] as $translation) { $translation->setValue('objectid', $event->getObject()->getOID()->__toString()); } } } }
[ "public", "function", "afterCreate", "(", "PersistenceEvent", "$", "event", ")", "{", "if", "(", "$", "event", "->", "getAction", "(", ")", "==", "PersistenceAction", "::", "CREATE", ")", "{", "$", "oldOid", "=", "$", "event", "->", "getOldOid", "(", ")"...
Update oids after create @param $event
[ "Update", "oids", "after", "create" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/i18n/impl/DefaultLocalization.php#L447-L457
train
iherwig/wcmf
src/wcmf/lib/security/impl/DefaultPermissionManager.php
DefaultPermissionManager.setPermissionType
public function setPermissionType($permissionType) { $this->permissionType = $permissionType; $this->actionKeyProvider->setEntityType($this->permissionType); }
php
public function setPermissionType($permissionType) { $this->permissionType = $permissionType; $this->actionKeyProvider->setEntityType($this->permissionType); }
[ "public", "function", "setPermissionType", "(", "$", "permissionType", ")", "{", "$", "this", "->", "permissionType", "=", "$", "permissionType", ";", "$", "this", "->", "actionKeyProvider", "->", "setEntityType", "(", "$", "this", "->", "permissionType", ")", ...
Set the entity type name of Permission instances. @param $permissionType String
[ "Set", "the", "entity", "type", "name", "of", "Permission", "instances", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/DefaultPermissionManager.php#L63-L66
train
iherwig/wcmf
src/wcmf/lib/security/impl/DefaultPermissionManager.php
DefaultPermissionManager.getPermissionInstance
protected function getPermissionInstance($resource, $context, $action) { $query = new ObjectQuery($this->permissionType, __CLASS__.__METHOD__); $tpl = $query->getObjectTemplate($this->permissionType); $tpl->setValue('resource', Criteria::asValue('=', $resource)); $tpl->setValue('context', Criteria::asValue('=', $context)); $tpl->setValue('action', Criteria::asValue('=', $action)); $permissions = $query->execute(BuildDepth::SINGLE); return (sizeof($permissions) > 0) ? $permissions[0] : null; }
php
protected function getPermissionInstance($resource, $context, $action) { $query = new ObjectQuery($this->permissionType, __CLASS__.__METHOD__); $tpl = $query->getObjectTemplate($this->permissionType); $tpl->setValue('resource', Criteria::asValue('=', $resource)); $tpl->setValue('context', Criteria::asValue('=', $context)); $tpl->setValue('action', Criteria::asValue('=', $action)); $permissions = $query->execute(BuildDepth::SINGLE); return (sizeof($permissions) > 0) ? $permissions[0] : null; }
[ "protected", "function", "getPermissionInstance", "(", "$", "resource", ",", "$", "context", ",", "$", "action", ")", "{", "$", "query", "=", "new", "ObjectQuery", "(", "$", "this", "->", "permissionType", ",", "__CLASS__", ".", "__METHOD__", ")", ";", "$"...
Get the permission object that matches the given parameters @param $resource Resource @param $context Context @param $action Action @return Instance of _permissionType or null
[ "Get", "the", "permission", "object", "that", "matches", "the", "given", "parameters" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/DefaultPermissionManager.php#L168-L176
train
iherwig/wcmf
src/wcmf/lib/security/impl/DefaultPermissionManager.php
DefaultPermissionManager.createPermissionObject
protected function createPermissionObject($resource, $context, $action, $roles) { $permission = $this->persistenceFacade->create($this->permissionType); $permission->setValue('resource', $resource); $permission->setValue('context', $context); $permission->setValue('action', $action); $permission->setValue('roles', $roles); return $permission; }
php
protected function createPermissionObject($resource, $context, $action, $roles) { $permission = $this->persistenceFacade->create($this->permissionType); $permission->setValue('resource', $resource); $permission->setValue('context', $context); $permission->setValue('action', $action); $permission->setValue('roles', $roles); return $permission; }
[ "protected", "function", "createPermissionObject", "(", "$", "resource", ",", "$", "context", ",", "$", "action", ",", "$", "roles", ")", "{", "$", "permission", "=", "$", "this", "->", "persistenceFacade", "->", "create", "(", "$", "this", "->", "permissi...
Create a permission object with the given parameters @param $resource Resource @param $context Context @param $action Action @param $roles String representing the permissions as returned from serializePermissions() @return Instance of _permissionType
[ "Create", "a", "permission", "object", "with", "the", "given", "parameters" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/security/impl/DefaultPermissionManager.php#L186-L193
train
iherwig/wcmf
src/wcmf/lib/util/StringUtil.php
StringUtil.getUrls
public static function getUrls($string) { preg_match_all("/<a[^>]+href=\"([^\">]+)/i", $string, $links); // find urls in javascript popup links for ($i=0; $i<sizeof($links[1]); $i++) { if (preg_match_all("/javascript:.*window.open[\(]*'([^']+)/i", $links[1][$i], $popups)) { $links[1][$i] = $popups[1][0]; } } // remove mailto links for ($i=0; $i<sizeof($links[1]); $i++) { if (preg_match("/^mailto:/i", $links[1][$i])) { unset($links[1][$i]); } } preg_match_all("/<img[^>]+src=\"([^\">]+)/i", $string, $images); preg_match_all("/<video[^>]+src=\"([^\">]+)/i", $string, $videos); preg_match_all("/<audios[^>]+src=\"([^\">]+)/i", $string, $audios); preg_match_all("/<input[^>]+src=\"([^\">]+)/i", $string, $buttons); preg_match_all("/<form[^>]+action=\"([^\">]+)/i", $string, $actions); preg_match_all("/<link[^>]+href=\"([^\">]+)/i", $string, $css); preg_match_all("/<script[^>]+src=\"([^\">]+)/i", $string, $scripts); return array_merge($links[1], $images[1], $videos[1], $audios[1], $buttons[1], $actions[1], $css[1], $scripts[1]); }
php
public static function getUrls($string) { preg_match_all("/<a[^>]+href=\"([^\">]+)/i", $string, $links); // find urls in javascript popup links for ($i=0; $i<sizeof($links[1]); $i++) { if (preg_match_all("/javascript:.*window.open[\(]*'([^']+)/i", $links[1][$i], $popups)) { $links[1][$i] = $popups[1][0]; } } // remove mailto links for ($i=0; $i<sizeof($links[1]); $i++) { if (preg_match("/^mailto:/i", $links[1][$i])) { unset($links[1][$i]); } } preg_match_all("/<img[^>]+src=\"([^\">]+)/i", $string, $images); preg_match_all("/<video[^>]+src=\"([^\">]+)/i", $string, $videos); preg_match_all("/<audios[^>]+src=\"([^\">]+)/i", $string, $audios); preg_match_all("/<input[^>]+src=\"([^\">]+)/i", $string, $buttons); preg_match_all("/<form[^>]+action=\"([^\">]+)/i", $string, $actions); preg_match_all("/<link[^>]+href=\"([^\">]+)/i", $string, $css); preg_match_all("/<script[^>]+src=\"([^\">]+)/i", $string, $scripts); return array_merge($links[1], $images[1], $videos[1], $audios[1], $buttons[1], $actions[1], $css[1], $scripts[1]); }
[ "public", "static", "function", "getUrls", "(", "$", "string", ")", "{", "preg_match_all", "(", "\"/<a[^>]+href=\\\"([^\\\">]+)/i\"", ",", "$", "string", ",", "$", "links", ")", ";", "// find urls in javascript popup links", "for", "(", "$", "i", "=", "0", ";", ...
Extraxt urls from a string. @param $string The string to search in @return An array with urls @note This method searches for occurences of <a..href="xxx"..>, <img..src="xxx"..>, <video..src="xxx"..>, <audio..src="xxx"..>, <input..src="xxx"..>, <form..action="xxx"..>, <link..href="xxx"..>, <script..src="xxx"..> and extracts xxx.
[ "Extraxt", "urls", "from", "a", "string", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/StringUtil.php#L231-L254
train
iherwig/wcmf
src/wcmf/lib/util/StringUtil.php
StringUtil.getBoolean
public static function getBoolean($string) { $val = filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if ($val === null) { return $string; } return $val; }
php
public static function getBoolean($string) { $val = filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); if ($val === null) { return $string; } return $val; }
[ "public", "static", "function", "getBoolean", "(", "$", "string", ")", "{", "$", "val", "=", "filter_var", "(", "$", "string", ",", "FILTER_VALIDATE_BOOLEAN", ",", "FILTER_NULL_ON_FAILURE", ")", ";", "if", "(", "$", "val", "===", "null", ")", "{", "return"...
Get the boolean value of a string @param $string @return Boolean or the string, if it does not represent a boolean.
[ "Get", "the", "boolean", "value", "of", "a", "string" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/util/StringUtil.php#L401-L407
train
GW2Treasures/gw2api
src/V2/Localization/LocalizationHandler.php
LocalizationHandler.onRequest
public function onRequest( RequestInterface $request ) { $localizedUri = Uri::withQueryValue( $request->getUri(), 'lang', $this->getEndpoint()->getLang() ); return $request->withUri($localizedUri); }
php
public function onRequest( RequestInterface $request ) { $localizedUri = Uri::withQueryValue( $request->getUri(), 'lang', $this->getEndpoint()->getLang() ); return $request->withUri($localizedUri); }
[ "public", "function", "onRequest", "(", "RequestInterface", "$", "request", ")", "{", "$", "localizedUri", "=", "Uri", "::", "withQueryValue", "(", "$", "request", "->", "getUri", "(", ")", ",", "'lang'", ",", "$", "this", "->", "getEndpoint", "(", ")", ...
Adds the `lang` query parameter to the request for localized endpoints. @param RequestInterface $request @return \Psr\Http\Message\RequestInterface
[ "Adds", "the", "lang", "query", "parameter", "to", "the", "request", "for", "localized", "endpoints", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Localization/LocalizationHandler.php#L26-L29
train
iherwig/wcmf
src/wcmf/lib/model/output/ImageOutputStrategy.php
ImageOutputStrategy.drawConnectionLine
protected function drawConnectionLine($poid, $oid) { list($start, $end) = $this->calculateEndPoints($poid, $oid); if($this->lineType == self::LINETYPE_DIRECT) { $this->drawDirectLine($start, $end); } else if($this->lineType == self::LINETYPE_ROUTED) { $this->drawRoutedLine($start, $end); } }
php
protected function drawConnectionLine($poid, $oid) { list($start, $end) = $this->calculateEndPoints($poid, $oid); if($this->lineType == self::LINETYPE_DIRECT) { $this->drawDirectLine($start, $end); } else if($this->lineType == self::LINETYPE_ROUTED) { $this->drawRoutedLine($start, $end); } }
[ "protected", "function", "drawConnectionLine", "(", "$", "poid", ",", "$", "oid", ")", "{", "list", "(", "$", "start", ",", "$", "end", ")", "=", "$", "this", "->", "calculateEndPoints", "(", "$", "poid", ",", "$", "oid", ")", ";", "if", "(", "$", ...
Draw connection line. @param $poid The parent object's object id. @param $oid The object's object id.
[ "Draw", "connection", "line", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/output/ImageOutputStrategy.php#L196-L204
train