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
vufind-org/vufindharvest
src/OaiPmh/RecordXmlFormatter.php
RecordXmlFormatter.getHeaderAdditions
protected function getHeaderAdditions($header) { $insert = ''; if ($this->injectDate) { $insert .= $this ->createTag($this->injectDate, (string)$header->datestamp); } if (isset($header->setSpec) && ($this->injectSetSpec || $this->injectSetName) ) { $insert .= $this->getHeaderSetAdditions($header->setSpec); } if ($this->injectHeaderElements) { foreach ($this->injectHeaderElements as $element) { if (isset($header->$element)) { $insert .= $header->$element->asXML(); } } } return $insert; }
php
protected function getHeaderAdditions($header) { $insert = ''; if ($this->injectDate) { $insert .= $this ->createTag($this->injectDate, (string)$header->datestamp); } if (isset($header->setSpec) && ($this->injectSetSpec || $this->injectSetName) ) { $insert .= $this->getHeaderSetAdditions($header->setSpec); } if ($this->injectHeaderElements) { foreach ($this->injectHeaderElements as $element) { if (isset($header->$element)) { $insert .= $header->$element->asXML(); } } } return $insert; }
[ "protected", "function", "getHeaderAdditions", "(", "$", "header", ")", "{", "$", "insert", "=", "''", ";", "if", "(", "$", "this", "->", "injectDate", ")", "{", "$", "insert", ".=", "$", "this", "->", "createTag", "(", "$", "this", "->", "injectDate",...
Format header elements as XML tags for inclusion in final record. @param object $header Header element (in SimpleXML format). @return string
[ "Format", "header", "elements", "as", "XML", "tags", "for", "inclusion", "in", "final", "record", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/RecordXmlFormatter.php#L203-L223
train
vufind-org/vufindharvest
src/OaiPmh/RecordXmlFormatter.php
RecordXmlFormatter.performGlobalReplace
protected function performGlobalReplace($xml) { return empty($this->globalSearch) ? $xml : preg_replace($this->globalSearch, $this->globalReplace, $xml); }
php
protected function performGlobalReplace($xml) { return empty($this->globalSearch) ? $xml : preg_replace($this->globalSearch, $this->globalReplace, $xml); }
[ "protected", "function", "performGlobalReplace", "(", "$", "xml", ")", "{", "return", "empty", "(", "$", "this", "->", "globalSearch", ")", "?", "$", "xml", ":", "preg_replace", "(", "$", "this", "->", "globalSearch", ",", "$", "this", "->", "globalReplace...
Perform global search and replace. @param string $xml XML to update. @return string
[ "Perform", "global", "search", "and", "replace", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/RecordXmlFormatter.php#L266-L271
train
vufind-org/vufindharvest
src/OaiPmh/RecordXmlFormatter.php
RecordXmlFormatter.format
public function format($id, $recordObj) { if (!isset($recordObj->metadata)) { throw new \Exception("Unexpected missing record metadata."); } $raw = trim($recordObj->metadata->asXML()); // Extract the actual metadata from inside the <metadata></metadata> tags; // there is probably a cleaner way to do this, but this simple method avoids // the complexity of dealing with namespaces in SimpleXML. // // We should also apply global search and replace at this time, if // applicable. $record = $this->performGlobalReplace( preg_replace('/(^<metadata[^\>]*>)|(<\/metadata>$)/m', '', $raw) ); // Collect attributes (for proper namespace resolution): $metadataAttributes = $this->extractMetadataAttributes($raw, $record); // If we are supposed to inject any values, do so now inside the first // tag of the file: $insert = $this->getIdAdditions($id) . $this->getHeaderAdditions($recordObj->header); $xml = !empty($insert) ? preg_replace('/>/', '>' . $insert, $record, 1) : $record; // Build the final record: return trim( $this->fixNamespaces( $xml, $recordObj->getDocNamespaces(), $metadataAttributes ) ); }
php
public function format($id, $recordObj) { if (!isset($recordObj->metadata)) { throw new \Exception("Unexpected missing record metadata."); } $raw = trim($recordObj->metadata->asXML()); // Extract the actual metadata from inside the <metadata></metadata> tags; // there is probably a cleaner way to do this, but this simple method avoids // the complexity of dealing with namespaces in SimpleXML. // // We should also apply global search and replace at this time, if // applicable. $record = $this->performGlobalReplace( preg_replace('/(^<metadata[^\>]*>)|(<\/metadata>$)/m', '', $raw) ); // Collect attributes (for proper namespace resolution): $metadataAttributes = $this->extractMetadataAttributes($raw, $record); // If we are supposed to inject any values, do so now inside the first // tag of the file: $insert = $this->getIdAdditions($id) . $this->getHeaderAdditions($recordObj->header); $xml = !empty($insert) ? preg_replace('/>/', '>' . $insert, $record, 1) : $record; // Build the final record: return trim( $this->fixNamespaces( $xml, $recordObj->getDocNamespaces(), $metadataAttributes ) ); }
[ "public", "function", "format", "(", "$", "id", ",", "$", "recordObj", ")", "{", "if", "(", "!", "isset", "(", "$", "recordObj", "->", "metadata", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Unexpected missing record metadata.\"", ")", ";", ...
Save a record to disk. @param string $id ID of record to save. @param object $recordObj Record to save (in SimpleXML format). @return string
[ "Save", "a", "record", "to", "disk", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/RecordXmlFormatter.php#L281-L315
train
iherwig/wcmf
src/wcmf/lib/presentation/control/ValueListProvider.php
ValueListProvider.getListStrategy
protected static function getListStrategy($listType) { // get list strategies if (self::$listStrategies == null) { self::$listStrategies = ObjectFactory::getInstance('listStrategies'); } $strategy = null; // search strategy if (isset(self::$listStrategies[$listType])) { $strategy = self::$listStrategies[$listType]; } else { throw new ConfigurationException('No ListStrategy implementation registered for '.$listType); } return $strategy; }
php
protected static function getListStrategy($listType) { // get list strategies if (self::$listStrategies == null) { self::$listStrategies = ObjectFactory::getInstance('listStrategies'); } $strategy = null; // search strategy if (isset(self::$listStrategies[$listType])) { $strategy = self::$listStrategies[$listType]; } else { throw new ConfigurationException('No ListStrategy implementation registered for '.$listType); } return $strategy; }
[ "protected", "static", "function", "getListStrategy", "(", "$", "listType", ")", "{", "// get list strategies", "if", "(", "self", "::", "$", "listStrategies", "==", "null", ")", "{", "self", "::", "$", "listStrategies", "=", "ObjectFactory", "::", "getInstance"...
Get the ListStrategy instance for a given list type @param $listType The list type @return ListStrategy instance @throws ConfigurationException
[ "Get", "the", "ListStrategy", "instance", "for", "a", "given", "list", "type" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/control/ValueListProvider.php#L124-L140
train
iherwig/wcmf
src/wcmf/lib/presentation/control/ValueListProvider.php
ValueListProvider.getItemValue
protected static function getItemValue($list, $key) { foreach ($list as $item) { // strict comparison for null value if (($key === null && $item['key'] === $key) || ($key !== null && strval($item['key']) === strval($key))) { return $item['value']; } } return $key; }
php
protected static function getItemValue($list, $key) { foreach ($list as $item) { // strict comparison for null value if (($key === null && $item['key'] === $key) || ($key !== null && strval($item['key']) === strval($key))) { return $item['value']; } } return $key; }
[ "protected", "static", "function", "getItemValue", "(", "$", "list", ",", "$", "key", ")", "{", "foreach", "(", "$", "list", "as", "$", "item", ")", "{", "// strict comparison for null value", "if", "(", "(", "$", "key", "===", "null", "&&", "$", "item",...
Get the value of the item with the given key. Returns the key, if it does not exist in the list. @param $list Array of associative arrays with keys 'key' and 'value' @param $key The key to search @return String
[ "Get", "the", "value", "of", "the", "item", "with", "the", "given", "key", ".", "Returns", "the", "key", "if", "it", "does", "not", "exist", "in", "the", "list", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/control/ValueListProvider.php#L149-L157
train
iherwig/wcmf
src/wcmf/lib/persistence/ReferenceDescription.php
ReferenceDescription.getReferencedAttribute
private function getReferencedAttribute() { $mapper = ObjectFactory::getInstance('persistenceFacade')->getMapper($this->otherType); return $mapper->getAttribute($this->otherName); }
php
private function getReferencedAttribute() { $mapper = ObjectFactory::getInstance('persistenceFacade')->getMapper($this->otherType); return $mapper->getAttribute($this->otherName); }
[ "private", "function", "getReferencedAttribute", "(", ")", "{", "$", "mapper", "=", "ObjectFactory", "::", "getInstance", "(", "'persistenceFacade'", ")", "->", "getMapper", "(", "$", "this", "->", "otherType", ")", ";", "return", "$", "mapper", "->", "getAttr...
Get the referenced attribute @return AttributeDescription instance
[ "Get", "the", "referenced", "attribute" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/ReferenceDescription.php#L137-L140
train
iherwig/wcmf
src/wcmf/lib/persistence/PersistentObjectProxy.php
PersistentObjectProxy.fromObject
public static function fromObject($object) { if ($object instanceof PersistentObjectProxy) { return $object; } else if ($object instanceof PersistentObject) { $proxy = new PersistentObjectProxy($object->getOID()); $proxy->realSubject = $object; return $proxy; } else { throw new IllegalArgumentException("Cannot create proxy from unknown object"); } }
php
public static function fromObject($object) { if ($object instanceof PersistentObjectProxy) { return $object; } else if ($object instanceof PersistentObject) { $proxy = new PersistentObjectProxy($object->getOID()); $proxy->realSubject = $object; return $proxy; } else { throw new IllegalArgumentException("Cannot create proxy from unknown object"); } }
[ "public", "static", "function", "fromObject", "(", "$", "object", ")", "{", "if", "(", "$", "object", "instanceof", "PersistentObjectProxy", ")", "{", "return", "$", "object", ";", "}", "else", "if", "(", "$", "object", "instanceof", "PersistentObject", ")",...
Create a PersistenceProxy instance from a PersistentObject. This is useful if you want to prevent automatic loading of the subject if it is already loaded. Returns the argument, if already an PersistentObjectProxy instance. @param $object The PersistentObject or PersistentObjectProxy @return PersistentObjectProxy
[ "Create", "a", "PersistenceProxy", "instance", "from", "a", "PersistentObject", ".", "This", "is", "useful", "if", "you", "want", "to", "prevent", "automatic", "loading", "of", "the", "subject", "if", "it", "is", "already", "loaded", ".", "Returns", "the", "...
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/PersistentObjectProxy.php#L44-L56
train
iherwig/wcmf
src/wcmf/lib/persistence/PersistentObjectProxy.php
PersistentObjectProxy.getValue
public function getValue($name) { // return pk values as they are parts of the oid $mapper = ObjectFactory::getInstance('persistenceFacade')->getMapper($this->getType()); $pkNames = $mapper->getPkNames(); for ($i=0, $count=sizeof($pkNames); $i<$count; $i++) { if ($name == $pkNames[$i]) { $ids = $this->oid->getId(); return $ids[$i]; } } return $this->__call(__FUNCTION__, [$name]); }
php
public function getValue($name) { // return pk values as they are parts of the oid $mapper = ObjectFactory::getInstance('persistenceFacade')->getMapper($this->getType()); $pkNames = $mapper->getPkNames(); for ($i=0, $count=sizeof($pkNames); $i<$count; $i++) { if ($name == $pkNames[$i]) { $ids = $this->oid->getId(); return $ids[$i]; } } return $this->__call(__FUNCTION__, [$name]); }
[ "public", "function", "getValue", "(", "$", "name", ")", "{", "// return pk values as they are parts of the oid", "$", "mapper", "=", "ObjectFactory", "::", "getInstance", "(", "'persistenceFacade'", ")", "->", "getMapper", "(", "$", "this", "->", "getType", "(", ...
Get the value of a named item. @param $name The name of the item to query. @return The value of the item / null if it doesn't exits.
[ "Get", "the", "value", "of", "a", "named", "item", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/PersistentObjectProxy.php#L239-L250
train
heyday/silverstripe-versioneddataobjects
code/VersionedGridFieldOrderableRows.php
VersionedGridFieldOrderableRows.handleMoveToPage
public function handleMoveToPage(GridField $grid, $request) { if (!$paginator = $grid->getConfig()->getComponentByType('GridFieldPaginator')) { $this->httpError(404, 'Paginator component not found'); } $move = $request->postVar('move'); $field = $this->getSortField(); $list = $grid->getList(); $manip = $grid->getManipulatedList(); $existing = $manip->map('ID', $field)->toArray(); $values = $existing; $order = array(); $id = isset($move['id']) ? (int)$move['id'] : null; $to = isset($move['page']) ? $move['page'] : null; if (!isset($values[$id])) { $this->httpError(400, 'Invalid item ID'); } $this->populateSortValues($list); $page = ((int)$grid->getState()->GridFieldPaginator->currentPage) ?: 1; $per = $paginator->getItemsPerPage(); if ($to == 'prev') { $swap = $list->limit(1, ($page - 1) * $per - 1)->first(); $values[$swap->ID] = $swap->$field; $order[] = $id; $order[] = $swap->ID; foreach ($existing as $_id => $sort) { if ($id != $_id) $order[] = $_id; } } elseif ($to == 'next') { $swap = $list->limit(1, $page * $per)->first(); $values[$swap->ID] = $swap->$field; foreach ($existing as $_id => $sort) { if ($id != $_id) $order[] = $_id; } $order[] = $swap->ID; $order[] = $id; } else { $this->httpError(400, 'Invalid page target'); } $this->reorderItems($list, $values, $order); return $grid->FieldHolder(); }
php
public function handleMoveToPage(GridField $grid, $request) { if (!$paginator = $grid->getConfig()->getComponentByType('GridFieldPaginator')) { $this->httpError(404, 'Paginator component not found'); } $move = $request->postVar('move'); $field = $this->getSortField(); $list = $grid->getList(); $manip = $grid->getManipulatedList(); $existing = $manip->map('ID', $field)->toArray(); $values = $existing; $order = array(); $id = isset($move['id']) ? (int)$move['id'] : null; $to = isset($move['page']) ? $move['page'] : null; if (!isset($values[$id])) { $this->httpError(400, 'Invalid item ID'); } $this->populateSortValues($list); $page = ((int)$grid->getState()->GridFieldPaginator->currentPage) ?: 1; $per = $paginator->getItemsPerPage(); if ($to == 'prev') { $swap = $list->limit(1, ($page - 1) * $per - 1)->first(); $values[$swap->ID] = $swap->$field; $order[] = $id; $order[] = $swap->ID; foreach ($existing as $_id => $sort) { if ($id != $_id) $order[] = $_id; } } elseif ($to == 'next') { $swap = $list->limit(1, $page * $per)->first(); $values[$swap->ID] = $swap->$field; foreach ($existing as $_id => $sort) { if ($id != $_id) $order[] = $_id; } $order[] = $swap->ID; $order[] = $id; } else { $this->httpError(400, 'Invalid page target'); } $this->reorderItems($list, $values, $order); return $grid->FieldHolder(); }
[ "public", "function", "handleMoveToPage", "(", "GridField", "$", "grid", ",", "$", "request", ")", "{", "if", "(", "!", "$", "paginator", "=", "$", "grid", "->", "getConfig", "(", ")", "->", "getComponentByType", "(", "'GridFieldPaginator'", ")", ")", "{",...
Handles requests to move an item to the previous or next page. @param GridField $grid @param $request @return mixed
[ "Handles", "requests", "to", "move", "an", "item", "to", "the", "previous", "or", "next", "page", "." ]
30a07d976abd17baba9d9194ca176c82d72323ac
https://github.com/heyday/silverstripe-versioneddataobjects/blob/30a07d976abd17baba9d9194ca176c82d72323ac/code/VersionedGridFieldOrderableRows.php#L294-L349
train
iherwig/wcmf
src/wcmf/lib/presentation/view/impl/SmartyView.php
SmartyView.setCaching
public function setCaching($caching) { $this->view->caching = $caching ? \Smarty::CACHING_LIFETIME_CURRENT : \Smarty::CACHING_OFF; }
php
public function setCaching($caching) { $this->view->caching = $caching ? \Smarty::CACHING_LIFETIME_CURRENT : \Smarty::CACHING_OFF; }
[ "public", "function", "setCaching", "(", "$", "caching", ")", "{", "$", "this", "->", "view", "->", "caching", "=", "$", "caching", "?", "\\", "Smarty", "::", "CACHING_LIFETIME_CURRENT", ":", "\\", "Smarty", "::", "CACHING_OFF", ";", "}" ]
Set whether views should be cached @param $caching Boolean
[ "Set", "whether", "views", "should", "be", "cached" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/view/impl/SmartyView.php#L84-L86
train
iherwig/wcmf
src/wcmf/lib/presentation/view/impl/SmartyView.php
SmartyView.setCacheDir
public function setCacheDir($cacheDir) { $this->view->setCompileDir(WCMF_BASE.$cacheDir.'templates_c/'); $this->view->setCacheDir(WCMF_BASE.$cacheDir.'cache/'); $fileUtil = new FileUtil(); $fileUtil->mkdirRec($this->view->getCompileDir()); $fileUtil->mkdirRec($this->view->getCacheDir()); }
php
public function setCacheDir($cacheDir) { $this->view->setCompileDir(WCMF_BASE.$cacheDir.'templates_c/'); $this->view->setCacheDir(WCMF_BASE.$cacheDir.'cache/'); $fileUtil = new FileUtil(); $fileUtil->mkdirRec($this->view->getCompileDir()); $fileUtil->mkdirRec($this->view->getCacheDir()); }
[ "public", "function", "setCacheDir", "(", "$", "cacheDir", ")", "{", "$", "this", "->", "view", "->", "setCompileDir", "(", "WCMF_BASE", ".", "$", "cacheDir", ".", "'templates_c/'", ")", ";", "$", "this", "->", "view", "->", "setCacheDir", "(", "WCMF_BASE"...
Set the caching directory If not existing, the directory will be created relative to WCMF_BASE. @param $cacheDir String
[ "Set", "the", "caching", "directory", "If", "not", "existing", "the", "directory", "will", "be", "created", "relative", "to", "WCMF_BASE", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/view/impl/SmartyView.php#L101-L108
train
iherwig/wcmf
src/wcmf/application/controller/UserController.php
UserController.changePassword
public function changePassword() { $this->requireTransaction(); $session = $this->getSession(); $permissionManager = $this->getPermissionManager(); $request = $this->getRequest(); $response = $this->getResponse(); // load model $authUser = $this->principalFactory->getUser($session->getAuthUser()); if ($authUser) { // add permissions for this operation $oidStr = $authUser->getOID()->__toString(); $this->tempPermissions[] = $permissionManager->addTempPermission($oidStr, '', PersistenceAction::READ); $this->tempPermissions[] = $permissionManager->addTempPermission($oidStr.'.password', '', PersistenceAction::UPDATE); $this->changePasswordImpl($authUser, $request->getValue('oldpassword'), $request->getValue('newpassword1'), $request->getValue('newpassword2')); } // success $response->setAction('ok'); }
php
public function changePassword() { $this->requireTransaction(); $session = $this->getSession(); $permissionManager = $this->getPermissionManager(); $request = $this->getRequest(); $response = $this->getResponse(); // load model $authUser = $this->principalFactory->getUser($session->getAuthUser()); if ($authUser) { // add permissions for this operation $oidStr = $authUser->getOID()->__toString(); $this->tempPermissions[] = $permissionManager->addTempPermission($oidStr, '', PersistenceAction::READ); $this->tempPermissions[] = $permissionManager->addTempPermission($oidStr.'.password', '', PersistenceAction::UPDATE); $this->changePasswordImpl($authUser, $request->getValue('oldpassword'), $request->getValue('newpassword1'), $request->getValue('newpassword2')); } // success $response->setAction('ok'); }
[ "public", "function", "changePassword", "(", ")", "{", "$", "this", "->", "requireTransaction", "(", ")", ";", "$", "session", "=", "$", "this", "->", "getSession", "(", ")", ";", "$", "permissionManager", "=", "$", "this", "->", "getPermissionManager", "(...
Change the user's password | Parameter | Description |---------------------|---------------------- | _in_ `oldpassword` | The old password | _in_ `newpassword1` | The new password | _in_ `newpassword2` | The new password
[ "Change", "the", "user", "s", "password" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/UserController.php#L94-L114
train
iherwig/wcmf
src/wcmf/application/controller/UserController.php
UserController.setConfigValue
public function setConfigValue() { $this->requireTransaction(); $session = $this->getSession(); $request = $this->getRequest(); $response = $this->getResponse(); $persistenceFacade = $this->getPersistenceFacade(); // load model $authUser = $this->principalFactory->getUser($session->getAuthUser()); if ($authUser) { $configKey = $request->getValue('name'); $configValue = $request->getValue('value'); // find configuration $configObj = null; $configList = Node::filter($authUser->getValue('UserConfig'), null, null, ['name' => $configKey]); if (sizeof($configList) > 0) { $configObj = $configList[0]; } else { $configObj = $persistenceFacade->create('UserConfig'); $configObj->setValue('name', $configKey); $authUser->addNode($configObj); } // set value if ($configObj != null) { $configObj->setValue('value', $configValue); } } // success $response->setAction('ok'); }
php
public function setConfigValue() { $this->requireTransaction(); $session = $this->getSession(); $request = $this->getRequest(); $response = $this->getResponse(); $persistenceFacade = $this->getPersistenceFacade(); // load model $authUser = $this->principalFactory->getUser($session->getAuthUser()); if ($authUser) { $configKey = $request->getValue('name'); $configValue = $request->getValue('value'); // find configuration $configObj = null; $configList = Node::filter($authUser->getValue('UserConfig'), null, null, ['name' => $configKey]); if (sizeof($configList) > 0) { $configObj = $configList[0]; } else { $configObj = $persistenceFacade->create('UserConfig'); $configObj->setValue('name', $configKey); $authUser->addNode($configObj); } // set value if ($configObj != null) { $configObj->setValue('value', $configValue); } } // success $response->setAction('ok'); }
[ "public", "function", "setConfigValue", "(", ")", "{", "$", "this", "->", "requireTransaction", "(", ")", ";", "$", "session", "=", "$", "this", "->", "getSession", "(", ")", ";", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "...
Set a configuration for the user | Parameter | Description |--------------|----------------------------- | _in_ `name` | The configuration name | _in_ `value` | The configuration value
[ "Set", "a", "configuration", "for", "the", "user" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/UserController.php#L124-L158
train
iherwig/wcmf
src/wcmf/application/controller/UserController.php
UserController.getConfigValue
public function getConfigValue() { $session = $this->getSession(); $request = $this->getRequest(); $response = $this->getResponse(); // load model $value = null; $authUser = $this->principalFactory->getUser($session->getAuthUser()); if ($authUser) { $configKey = $request->getValue('name'); // find configuration $configObj = null; $configList = Node::filter($authUser->getValue('UserConfig'), null, null, ['name' => $configKey]); $value = sizeof($configList) > 0 ? $configObj = $configList[0]->getValue('value') : null; } $response->setValue('value', $value); // success $response->setAction('ok'); }
php
public function getConfigValue() { $session = $this->getSession(); $request = $this->getRequest(); $response = $this->getResponse(); // load model $value = null; $authUser = $this->principalFactory->getUser($session->getAuthUser()); if ($authUser) { $configKey = $request->getValue('name'); // find configuration $configObj = null; $configList = Node::filter($authUser->getValue('UserConfig'), null, null, ['name' => $configKey]); $value = sizeof($configList) > 0 ? $configObj = $configList[0]->getValue('value') : null; } $response->setValue('value', $value); // success $response->setAction('ok'); }
[ "public", "function", "getConfigValue", "(", ")", "{", "$", "session", "=", "$", "this", "->", "getSession", "(", ")", ";", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "response", "=", "$", "this", "->", "getResponse", "...
Get a configuration for the user | Parameter | Description |---------------|---------------------------- | _in_ `name` | The configuration name | _out_ `value` | The configuration value
[ "Get", "a", "configuration", "for", "the", "user" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/UserController.php#L168-L190
train
iherwig/wcmf
src/wcmf/application/controller/UserController.php
UserController.changePasswordImpl
protected function changePasswordImpl(User $user, $oldPassword, $newPassword, $newPasswordRepeated) { $message = $this->getMessage(); // check old password if (!$user->verifyPassword($oldPassword)) { throw new IllegalArgumentException($message->getText("The old password is incorrect")); } if (strlen($newPassword) == 0) { throw new IllegalArgumentException($message->getText("The password can't be empty")); } if ($newPassword != $newPasswordRepeated) { throw new IllegalArgumentException($message->getText("The given passwords don't match")); } // set password $user->setPassword($newPassword); }
php
protected function changePasswordImpl(User $user, $oldPassword, $newPassword, $newPasswordRepeated) { $message = $this->getMessage(); // check old password if (!$user->verifyPassword($oldPassword)) { throw new IllegalArgumentException($message->getText("The old password is incorrect")); } if (strlen($newPassword) == 0) { throw new IllegalArgumentException($message->getText("The password can't be empty")); } if ($newPassword != $newPasswordRepeated) { throw new IllegalArgumentException($message->getText("The given passwords don't match")); } // set password $user->setPassword($newPassword); }
[ "protected", "function", "changePasswordImpl", "(", "User", "$", "user", ",", "$", "oldPassword", ",", "$", "newPassword", ",", "$", "newPasswordRepeated", ")", "{", "$", "message", "=", "$", "this", "->", "getMessage", "(", ")", ";", "// check old password", ...
Change a users password. @param $user The User instance @param $oldPassword The old password of the user @param $newPassword The new password for the user @param $newPasswordRepeated The new password of the user again
[ "Change", "a", "users", "password", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/UserController.php#L199-L213
train
iherwig/wcmf
src/wcmf/application/controller/UserController.php
UserController.afterCommit
public function afterCommit(TransactionEvent $event) { if ($event->getPhase() == TransactionEvent::AFTER_COMMIT) { // remove temporary permissions $permissionManager = $this->getPermissionManager(); foreach ($this->tempPermissions as $permission) { $permissionManager->removeTempPermission($permission); } } }
php
public function afterCommit(TransactionEvent $event) { if ($event->getPhase() == TransactionEvent::AFTER_COMMIT) { // remove temporary permissions $permissionManager = $this->getPermissionManager(); foreach ($this->tempPermissions as $permission) { $permissionManager->removeTempPermission($permission); } } }
[ "public", "function", "afterCommit", "(", "TransactionEvent", "$", "event", ")", "{", "if", "(", "$", "event", "->", "getPhase", "(", ")", "==", "TransactionEvent", "::", "AFTER_COMMIT", ")", "{", "// remove temporary permissions", "$", "permissionManager", "=", ...
Remove temporary permissions after commit @param $event
[ "Remove", "temporary", "permissions", "after", "commit" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/UserController.php#L219-L227
train
iherwig/wcmf
src/wcmf/lib/service/RemotingServer.php
RemotingServer.doCall
public function doCall($serverKey, $request) { $client = $this->getClient($serverKey); if ($client) { $response = $client->call($request); return $response; } return ObjectFactory::getNewInstance('response'); }
php
public function doCall($serverKey, $request) { $client = $this->getClient($serverKey); if ($client) { $response = $client->call($request); return $response; } return ObjectFactory::getNewInstance('response'); }
[ "public", "function", "doCall", "(", "$", "serverKey", ",", "$", "request", ")", "{", "$", "client", "=", "$", "this", "->", "getClient", "(", "$", "serverKey", ")", ";", "if", "(", "$", "client", ")", "{", "$", "response", "=", "$", "client", "->"...
Send a request to the server identified by serverKey. @param $serverKey An entry in the configuration section 'remoteserver' @param $request A Request instance @return A Response instance
[ "Send", "a", "request", "to", "the", "server", "identified", "by", "serverKey", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/RemotingServer.php#L51-L58
train
iherwig/wcmf
src/wcmf/lib/service/RemotingServer.php
RemotingServer.getClient
private function getClient($serverKey) { if (!isset($this->clients[$serverKey])) { $config = ObjectFactory::getInstance('configuration'); $serverDef = $config->getValue($serverKey, 'remoteserver'); // get remote the user $user = $this->getRemoteUser($serverKey); $client = null; if (strpos($serverDef, 'http://') === 0 || strpos($serverDef, 'https://') === 0) { $client = new HTTPClient($serverDef, $user); } else { $client = new RPCClient($serverDef, $user); } $this->clients[$serverKey] = $client; } return $this->clients[$serverKey]; }
php
private function getClient($serverKey) { if (!isset($this->clients[$serverKey])) { $config = ObjectFactory::getInstance('configuration'); $serverDef = $config->getValue($serverKey, 'remoteserver'); // get remote the user $user = $this->getRemoteUser($serverKey); $client = null; if (strpos($serverDef, 'http://') === 0 || strpos($serverDef, 'https://') === 0) { $client = new HTTPClient($serverDef, $user); } else { $client = new RPCClient($serverDef, $user); } $this->clients[$serverKey] = $client; } return $this->clients[$serverKey]; }
[ "private", "function", "getClient", "(", "$", "serverKey", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "clients", "[", "$", "serverKey", "]", ")", ")", "{", "$", "config", "=", "ObjectFactory", "::", "getInstance", "(", "'configuration'", ...
Get a client instance for a given server key @param $serverKey An entry in the configuration section 'remoteserver' @return A client instance or null
[ "Get", "a", "client", "instance", "for", "a", "given", "server", "key" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/RemotingServer.php#L65-L82
train
iherwig/wcmf
src/wcmf/lib/service/RemotingServer.php
RemotingServer.getRemoteUser
private function getRemoteUser($serverKey) { if (!isset($this->users[$serverKey])) { $config = ObjectFactory::getInstance('configuration'); $remoteUser = $config->getValue($serverKey, 'remoteuser'); if (is_array($remoteUser) && sizeof($remoteUser) == 2) { $this->users[$serverKey] = [ 'login' => $remoteUser[0], 'password' => $remoteUser[1] ]; } else { throw new IllegialConfigurationException( "Remote user definition of '".$serverKey. "' must be an array of login and password." ); } } return $this->users[$serverKey]; }
php
private function getRemoteUser($serverKey) { if (!isset($this->users[$serverKey])) { $config = ObjectFactory::getInstance('configuration'); $remoteUser = $config->getValue($serverKey, 'remoteuser'); if (is_array($remoteUser) && sizeof($remoteUser) == 2) { $this->users[$serverKey] = [ 'login' => $remoteUser[0], 'password' => $remoteUser[1] ]; } else { throw new IllegialConfigurationException( "Remote user definition of '".$serverKey. "' must be an array of login and password." ); } } return $this->users[$serverKey]; }
[ "private", "function", "getRemoteUser", "(", "$", "serverKey", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "users", "[", "$", "serverKey", "]", ")", ")", "{", "$", "config", "=", "ObjectFactory", "::", "getInstance", "(", "'configuration'"...
Get the remote user login and password for a given server key @param $serverKey An entry in the configuration section 'remoteuser' @return Array with keys 'login', 'password'
[ "Get", "the", "remote", "user", "login", "and", "password", "for", "a", "given", "server", "key" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/RemotingServer.php#L89-L107
train
iherwig/wcmf
src/wcmf/lib/model/AbstractQuery.php
AbstractQuery.getQueryString
public function getQueryString($buildDepth=BuildDepth::SINGLE, $orderby=null) { $selectStmt = $this->buildQuery($buildDepth, $orderby); $str = $selectStmt->__toString(); $mapper = self::getMapper($selectStmt->getType()); foreach ($selectStmt->getParameters() as $key => $value) { $value = is_string($value) ? $mapper->quoteValue($value) : $value; $str = preg_replace('/'.$key.'/', $value, $str, 1); } return $str; }
php
public function getQueryString($buildDepth=BuildDepth::SINGLE, $orderby=null) { $selectStmt = $this->buildQuery($buildDepth, $orderby); $str = $selectStmt->__toString(); $mapper = self::getMapper($selectStmt->getType()); foreach ($selectStmt->getParameters() as $key => $value) { $value = is_string($value) ? $mapper->quoteValue($value) : $value; $str = preg_replace('/'.$key.'/', $value, $str, 1); } return $str; }
[ "public", "function", "getQueryString", "(", "$", "buildDepth", "=", "BuildDepth", "::", "SINGLE", ",", "$", "orderby", "=", "null", ")", "{", "$", "selectStmt", "=", "$", "this", "->", "buildQuery", "(", "$", "buildDepth", ",", "$", "orderby", ")", ";",...
Get the query serialized to a string. Placeholder are replaced with quoted values. @param $buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to load (except BuildDepth::REQUIRED) or false if only object ids should be returned (optional, default: _BuildDepth::SINGLE_) @param $orderby An array holding names of attributes to order by, maybe appended with 'ASC', 'DESC' (optional, default: _null_) @return String
[ "Get", "the", "query", "serialized", "to", "a", "string", ".", "Placeholder", "are", "replaced", "with", "quoted", "values", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/AbstractQuery.php#L73-L82
train
iherwig/wcmf
src/wcmf/lib/model/AbstractQuery.php
AbstractQuery.executeInternal
protected function executeInternal(SelectStatement $selectStmt, $buildDepth, PagingInfo $pagingInfo=null) { $type = $this->getQueryType(); $mapper = self::getMapper($type); $permissionManager = ObjectFactory::getInstance('permissionManager'); $loadOidsOnly = ($buildDepth === false); // execute the query $result = []; if ($loadOidsOnly) { $data = $mapper->select($selectStmt, $pagingInfo); // collect oids for ($i=0, $count=sizeof($data); $i<$count; $i++) { $oid = $mapper->constructOID($data[$i]); if ($permissionManager->authorize($oid, '', PersistenceAction::READ)) { $result[] = $oid; } } } else { $objects = $mapper->loadObjectsFromSQL($selectStmt, $buildDepth, $pagingInfo); // remove objects for which the user is not authorized $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $tx = $persistenceFacade->getTransaction(); // remove objects for which the user is not authorized for ($i=0, $count=sizeof($objects); $i<$count; $i++) { $object = $objects[$i]; $oid = $object->getOID(); if ($permissionManager->authorize($oid, '', PersistenceAction::READ)) { // call lifecycle callback $object->afterLoad(); $result[] = $object; } else { $tx->detach($oid); } // TODO remove attribute values for which the user is not authorized // should use some pre-check if restrictions on the entity type exist } } return $result; }
php
protected function executeInternal(SelectStatement $selectStmt, $buildDepth, PagingInfo $pagingInfo=null) { $type = $this->getQueryType(); $mapper = self::getMapper($type); $permissionManager = ObjectFactory::getInstance('permissionManager'); $loadOidsOnly = ($buildDepth === false); // execute the query $result = []; if ($loadOidsOnly) { $data = $mapper->select($selectStmt, $pagingInfo); // collect oids for ($i=0, $count=sizeof($data); $i<$count; $i++) { $oid = $mapper->constructOID($data[$i]); if ($permissionManager->authorize($oid, '', PersistenceAction::READ)) { $result[] = $oid; } } } else { $objects = $mapper->loadObjectsFromSQL($selectStmt, $buildDepth, $pagingInfo); // remove objects for which the user is not authorized $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); $tx = $persistenceFacade->getTransaction(); // remove objects for which the user is not authorized for ($i=0, $count=sizeof($objects); $i<$count; $i++) { $object = $objects[$i]; $oid = $object->getOID(); if ($permissionManager->authorize($oid, '', PersistenceAction::READ)) { // call lifecycle callback $object->afterLoad(); $result[] = $object; } else { $tx->detach($oid); } // TODO remove attribute values for which the user is not authorized // should use some pre-check if restrictions on the entity type exist } } return $result; }
[ "protected", "function", "executeInternal", "(", "SelectStatement", "$", "selectStmt", ",", "$", "buildDepth", ",", "PagingInfo", "$", "pagingInfo", "=", "null", ")", "{", "$", "type", "=", "$", "this", "->", "getQueryType", "(", ")", ";", "$", "mapper", "...
Execute the query and return the results. @param $selectStmt A SelectStatement instance @param $buildDepth One of the BUILDDEPTH constants or a number describing the number of generations to load (except BuildDepth::REQUIRED) or false if only object ids should be returned @param $pagingInfo A reference paging info instance (default: _null_) @return A list of objects that match the given conditions or a list of object ids
[ "Execute", "the", "query", "and", "return", "the", "results", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/AbstractQuery.php#L113-L156
train
iherwig/wcmf
src/wcmf/lib/model/AbstractQuery.php
AbstractQuery.getConnection
protected static function getConnection($type) { $mapper = self::getMapper($type); $conn = $mapper->getConnection(); return $conn; }
php
protected static function getConnection($type) { $mapper = self::getMapper($type); $conn = $mapper->getConnection(); return $conn; }
[ "protected", "static", "function", "getConnection", "(", "$", "type", ")", "{", "$", "mapper", "=", "self", "::", "getMapper", "(", "$", "type", ")", ";", "$", "conn", "=", "$", "mapper", "->", "getConnection", "(", ")", ";", "return", "$", "conn", "...
Get the database connection of the given node type. @param $type The node type to get the connection from connection @return The connection
[ "Get", "the", "database", "connection", "of", "the", "given", "node", "type", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/AbstractQuery.php#L163-L167
train
iherwig/wcmf
src/wcmf/application/controller/SaveController.php
SaveController.saveUploadFile
protected function saveUploadFile(ObjectId $oid, $valueName, array $data) { if ($data['name'] != '') { $response = $this->getResponse(); $message = $this->getMessage(); $fileUtil = $this->getFileUtil(); // upload request -> see if upload was succesfull if ($data['tmp_name'] == 'none') { $response->addError(ApplicationError::get('GENERAL_ERROR', ['message' => $message->getText("Upload failed for %0%.", [$data['name']])])); return null; } // check if file was actually uploaded if (!is_uploaded_file($data['tmp_name'])) { $message = $message->getText("Possible file upload attack: filename %0%.", [$data['name']]); $response->addError(ApplicationError::get('GENERAL_ERROR', ['message' => $message])); return null; } // get upload directory $uploadDir = $this->getUploadDir($oid, $valueName); // get the name for the uploaded file $uploadFilename = $uploadDir.$this->getUploadFilename($oid, $valueName, $data['name']); // check file validity if (!$this->checkFile($oid, $valueName, $uploadFilename, $data['type'])) { return null; } // get upload parameters $override = $this->shouldOverride($oid, $valueName, $uploadFilename); // upload file (mimeTypes parameter is set to null, because the mime type is already checked by checkFile method) try { return $fileUtil->uploadFile($data, $uploadFilename, null, $override); } catch (\Exception $ex) { $response->addError(ApplicationError::fromException($ex)); return null; } } return null; }
php
protected function saveUploadFile(ObjectId $oid, $valueName, array $data) { if ($data['name'] != '') { $response = $this->getResponse(); $message = $this->getMessage(); $fileUtil = $this->getFileUtil(); // upload request -> see if upload was succesfull if ($data['tmp_name'] == 'none') { $response->addError(ApplicationError::get('GENERAL_ERROR', ['message' => $message->getText("Upload failed for %0%.", [$data['name']])])); return null; } // check if file was actually uploaded if (!is_uploaded_file($data['tmp_name'])) { $message = $message->getText("Possible file upload attack: filename %0%.", [$data['name']]); $response->addError(ApplicationError::get('GENERAL_ERROR', ['message' => $message])); return null; } // get upload directory $uploadDir = $this->getUploadDir($oid, $valueName); // get the name for the uploaded file $uploadFilename = $uploadDir.$this->getUploadFilename($oid, $valueName, $data['name']); // check file validity if (!$this->checkFile($oid, $valueName, $uploadFilename, $data['type'])) { return null; } // get upload parameters $override = $this->shouldOverride($oid, $valueName, $uploadFilename); // upload file (mimeTypes parameter is set to null, because the mime type is already checked by checkFile method) try { return $fileUtil->uploadFile($data, $uploadFilename, null, $override); } catch (\Exception $ex) { $response->addError(ApplicationError::fromException($ex)); return null; } } return null; }
[ "protected", "function", "saveUploadFile", "(", "ObjectId", "$", "oid", ",", "$", "valueName", ",", "array", "$", "data", ")", "{", "if", "(", "$", "data", "[", "'name'", "]", "!=", "''", ")", "{", "$", "response", "=", "$", "this", "->", "getRespons...
Save uploaded file. This method calls checkFile which will prevent upload if returning false. @param $oid The ObjectId of the object to which the file is associated @param $valueName The name of the value to which the file is associated @param $data An associative array with keys 'name', 'type', 'tmp_name' as contained in the php $_FILES array. @return The final filename if the upload was successful, null on error
[ "Save", "uploaded", "file", ".", "This", "method", "calls", "checkFile", "which", "will", "prevent", "upload", "if", "returning", "false", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/SaveController.php#L344-L387
train
iherwig/wcmf
src/wcmf/lib/presentation/link/InternalLink.php
InternalLink.makeAnchorLink
public static function makeAnchorLink(ObjectId $oid, ObjectId $anchorOID, $anchorName=null) { $str = self::makeLink($oid)."/".$anchorOID->__toString(); if ($anchorName != null) { $str .= "#".$anchorName; } return $str; }
php
public static function makeAnchorLink(ObjectId $oid, ObjectId $anchorOID, $anchorName=null) { $str = self::makeLink($oid)."/".$anchorOID->__toString(); if ($anchorName != null) { $str .= "#".$anchorName; } return $str; }
[ "public", "static", "function", "makeAnchorLink", "(", "ObjectId", "$", "oid", ",", "ObjectId", "$", "anchorOID", ",", "$", "anchorName", "=", "null", ")", "{", "$", "str", "=", "self", "::", "makeLink", "(", "$", "oid", ")", ".", "\"/\"", ".", "$", ...
Make an internal link to an object @param $oid The object id of the object to link to @param $anchorOID The object id of the subobject to link to @param $anchorName The name inside the subobject to link to (null, if the object itself should be linked) (default: _null_) @return The link
[ "Make", "an", "internal", "link", "to", "an", "object" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/link/InternalLink.php#L42-L48
train
iherwig/wcmf
src/wcmf/lib/presentation/link/InternalLink.php
InternalLink.getReferencedOID
public static function getReferencedOID($link) { preg_match_all("/([A-Za-z0-9]+(:[0-9]+)+)/", $link, $matches); if (sizeof($matches) > 0 && sizeof($matches[1]) > 0) { $oid = $matches[1][0]; return ObjectId::parse($oid); } return null; }
php
public static function getReferencedOID($link) { preg_match_all("/([A-Za-z0-9]+(:[0-9]+)+)/", $link, $matches); if (sizeof($matches) > 0 && sizeof($matches[1]) > 0) { $oid = $matches[1][0]; return ObjectId::parse($oid); } return null; }
[ "public", "static", "function", "getReferencedOID", "(", "$", "link", ")", "{", "preg_match_all", "(", "\"/([A-Za-z0-9]+(:[0-9]+)+)/\"", ",", "$", "link", ",", "$", "matches", ")", ";", "if", "(", "sizeof", "(", "$", "matches", ")", ">", "0", "&&", "sizeof...
Get the oid of the referenced object @param $link The link to process @return The oid or null if no valid oid is referenced
[ "Get", "the", "oid", "of", "the", "referenced", "object" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/link/InternalLink.php#L64-L71
train
iherwig/wcmf
src/wcmf/lib/presentation/link/InternalLink.php
InternalLink.getAnchorName
public static function getAnchorName($link) { preg_match_all("/#(.+)$/", $link, $matches); if (sizeof($matches) > 0 && sizeof($matches[1]) > 0) { $name = $matches[1][0]; return $name; } return null; }
php
public static function getAnchorName($link) { preg_match_all("/#(.+)$/", $link, $matches); if (sizeof($matches) > 0 && sizeof($matches[1]) > 0) { $name = $matches[1][0]; return $name; } return null; }
[ "public", "static", "function", "getAnchorName", "(", "$", "link", ")", "{", "preg_match_all", "(", "\"/#(.+)$/\"", ",", "$", "link", ",", "$", "matches", ")", ";", "if", "(", "sizeof", "(", "$", "matches", ")", ">", "0", "&&", "sizeof", "(", "$", "m...
Get the name of the anchor inside the referenced subobject if any @param $link The link to process @return The name or null if no anchor name is defined
[ "Get", "the", "name", "of", "the", "anchor", "inside", "the", "referenced", "subobject", "if", "any" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/link/InternalLink.php#L92-L99
train
iherwig/wcmf
src/wcmf/lib/core/impl/AuthTokenSession.php
AuthTokenSession.isTokenValid
protected function isTokenValid() { if ($this->isTokenValid) { // already validated return true; } $request = ObjectFactory::getInstance('request'); $token = $request->hasHeader(self::TOKEN_HEADER) ? $request->getHeader(self::TOKEN_HEADER) : $request->getValue(self::TOKEN_HEADER, null); $this->isTokenValid = $token != null && $token == $_COOKIE[$this->tokenName]; return $this->isTokenValid; }
php
protected function isTokenValid() { if ($this->isTokenValid) { // already validated return true; } $request = ObjectFactory::getInstance('request'); $token = $request->hasHeader(self::TOKEN_HEADER) ? $request->getHeader(self::TOKEN_HEADER) : $request->getValue(self::TOKEN_HEADER, null); $this->isTokenValid = $token != null && $token == $_COOKIE[$this->tokenName]; return $this->isTokenValid; }
[ "protected", "function", "isTokenValid", "(", ")", "{", "if", "(", "$", "this", "->", "isTokenValid", ")", "{", "// already validated", "return", "true", ";", "}", "$", "request", "=", "ObjectFactory", "::", "getInstance", "(", "'request'", ")", ";", "$", ...
Check if the request contains a valid token
[ "Check", "if", "the", "request", "contains", "a", "valid", "token" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/core/impl/AuthTokenSession.php#L88-L98
train
Aerendir/PHPValueObjects
src/Vat/VatNumber.php
VatNumber.setVatNumber
protected function setVatNumber(string $vatNumber): void { if ( ! is_string($vatNumber)) { throw new \InvalidArgumentException( sprintf('The VAT Number MUST be a string. "%s" passed.', gettype($vatNumber)) ); } $this->vatNumber = $vatNumber; }
php
protected function setVatNumber(string $vatNumber): void { if ( ! is_string($vatNumber)) { throw new \InvalidArgumentException( sprintf('The VAT Number MUST be a string. "%s" passed.', gettype($vatNumber)) ); } $this->vatNumber = $vatNumber; }
[ "protected", "function", "setVatNumber", "(", "string", "$", "vatNumber", ")", ":", "void", "{", "if", "(", "!", "is_string", "(", "$", "vatNumber", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'The VAT Number MUST be ...
Method to set the full VAT Number. @param string $vatNumber The full VAT number, with country ISO code
[ "Method", "to", "set", "the", "full", "VAT", "Number", "." ]
5ef646e593e411bf1b678755ff552a00a245d4c9
https://github.com/Aerendir/PHPValueObjects/blob/5ef646e593e411bf1b678755ff552a00a245d4c9/src/Vat/VatNumber.php#L94-L102
train
iherwig/wcmf
src/wcmf/lib/presentation/ApplicationError.php
ApplicationError.get
public static function get($code, $data=null) { self::predefine(); if (defined($code)) { $def = unserialize(constant($code)); $error = new ApplicationError($def[0], $def[1], $def[2], $def[3], $data); return $error; } else { throw new IllegalArgumentException("The error code '".$code."' is not defined"); } }
php
public static function get($code, $data=null) { self::predefine(); if (defined($code)) { $def = unserialize(constant($code)); $error = new ApplicationError($def[0], $def[1], $def[2], $def[3], $data); return $error; } else { throw new IllegalArgumentException("The error code '".$code."' is not defined"); } }
[ "public", "static", "function", "get", "(", "$", "code", ",", "$", "data", "=", "null", ")", "{", "self", "::", "predefine", "(", ")", ";", "if", "(", "defined", "(", "$", "code", ")", ")", "{", "$", "def", "=", "unserialize", "(", "constant", "(...
Factory method for retrieving a predefined error instance. @param $code An error code @param $data Some error codes required to transmit further information to the client (optional, default: _null_) @return ApplicationError
[ "Factory", "method", "for", "retrieving", "a", "predefined", "error", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/ApplicationError.php#L144-L154
train
iherwig/wcmf
src/wcmf/lib/presentation/ApplicationError.php
ApplicationError.getGeneral
public static function getGeneral($message, $statusCode=self::DEFAULT_ERROR_STATUS) { $error = new ApplicationError('GENERAL_ERROR', ApplicationError::LEVEL_ERROR, $statusCode, $message); return $error; }
php
public static function getGeneral($message, $statusCode=self::DEFAULT_ERROR_STATUS) { $error = new ApplicationError('GENERAL_ERROR', ApplicationError::LEVEL_ERROR, $statusCode, $message); return $error; }
[ "public", "static", "function", "getGeneral", "(", "$", "message", ",", "$", "statusCode", "=", "self", "::", "DEFAULT_ERROR_STATUS", ")", "{", "$", "error", "=", "new", "ApplicationError", "(", "'GENERAL_ERROR'", ",", "ApplicationError", "::", "LEVEL_ERROR", ",...
Factory method for creating a general error instance. @param $message Error message @param $statusCode HTTP status code (optional, default: _DEFAULT_ERROR_STATUS_) @return ApplicationError
[ "Factory", "method", "for", "creating", "a", "general", "error", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/ApplicationError.php#L162-L165
train
iherwig/wcmf
src/wcmf/lib/presentation/ApplicationError.php
ApplicationError.fromException
public static function fromException(\Exception $ex) { if ($ex instanceof ApplicationException) { return $ex->getError(); } if ($ex instanceof AuthorizationException) { return self::get(PERMISSION_DENIED); } return self::getGeneral($ex->getMessage()); }
php
public static function fromException(\Exception $ex) { if ($ex instanceof ApplicationException) { return $ex->getError(); } if ($ex instanceof AuthorizationException) { return self::get(PERMISSION_DENIED); } return self::getGeneral($ex->getMessage()); }
[ "public", "static", "function", "fromException", "(", "\\", "Exception", "$", "ex", ")", "{", "if", "(", "$", "ex", "instanceof", "ApplicationException", ")", "{", "return", "$", "ex", "->", "getError", "(", ")", ";", "}", "if", "(", "$", "ex", "instan...
Factory method for transforming an exception into an ApplicationError instance. @param $ex Exception @return ApplicationError
[ "Factory", "method", "for", "transforming", "an", "exception", "into", "an", "ApplicationError", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/ApplicationError.php#L172-L180
train
iherwig/wcmf
src/wcmf/application/controller/ListController.php
ListController.getObjects
protected function getObjects($type, $queryCondition, $sortArray, $pagingInfo) { $persistenceFacade = $this->getPersistenceFacade(); if (!$persistenceFacade->isKnownType($type)) { return []; } $request = $this->getRequest(); $response = $this->getResponse(); $query = new StringQuery($type); $query->setRQLConditionString($queryCondition); try { $objects = $query->execute(BuildDepth::SINGLE, $sortArray, $pagingInfo); } catch (UnknownFieldException $ex) { if ($ex->getField() == $request->getValue('sortFieldName')) { $response->addError(ApplicationError::get('SORT_FIELD_UNKNOWN')); } } if ($this->getLogger()->isDebugEnabled()) { $this->getLogger()->debug("Load objects with query: ".$query->getLastQueryString()); } return $objects; }
php
protected function getObjects($type, $queryCondition, $sortArray, $pagingInfo) { $persistenceFacade = $this->getPersistenceFacade(); if (!$persistenceFacade->isKnownType($type)) { return []; } $request = $this->getRequest(); $response = $this->getResponse(); $query = new StringQuery($type); $query->setRQLConditionString($queryCondition); try { $objects = $query->execute(BuildDepth::SINGLE, $sortArray, $pagingInfo); } catch (UnknownFieldException $ex) { if ($ex->getField() == $request->getValue('sortFieldName')) { $response->addError(ApplicationError::get('SORT_FIELD_UNKNOWN')); } } if ($this->getLogger()->isDebugEnabled()) { $this->getLogger()->debug("Load objects with query: ".$query->getLastQueryString()); } return $objects; }
[ "protected", "function", "getObjects", "(", "$", "type", ",", "$", "queryCondition", ",", "$", "sortArray", ",", "$", "pagingInfo", ")", "{", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "if", "(", "!", "$", "p...
Get the object to display. The default implementation uses a StringQuery instance for the object retrieval. Subclasses may override this. If filter is an empty string, all nodes of the given type will be selected. @param $type The object type @param $queryCondition The query condition passed from the view (to be used with StringQuery). @param $sortArray An array of attributes to order by (with an optional ASC|DESC appended) @param $pagingInfo The current PagingInfo instance @return Array of Node instances
[ "Get", "the", "object", "to", "display", ".", "The", "default", "implementation", "uses", "a", "StringQuery", "instance", "for", "the", "object", "retrieval", ".", "Subclasses", "may", "override", "this", ".", "If", "filter", "is", "an", "empty", "string", "...
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/ListController.php#L160-L182
train
iherwig/wcmf
src/wcmf/application/controller/ListController.php
ListController.modifyModel
protected function modifyModel(&$nodes) { $request = $this->getRequest(); // TODO: put this into subclass ListController // remove all attributes except for display values if ($request->getBooleanValue('completeObjects', false) == false) { for($i=0,$count=sizeof($nodes); $i<$count; $i++) { $node = $nodes[$i]; $displayValues = $request->hasValue('values') ? array_map('trim', explode(',', $request->getValue('values'))) : $node->getProperty('displayValues'); $valueNames = array_merge($node->getValueNames(), $node->getRelationNames()); foreach($valueNames as $name) { if (!in_array($name, $displayValues)) { $node->removeValue($name); } } } } // render values if ($request->getBooleanValue('translateValues', false) == true) { NodeUtil::translateValues($nodes); } }
php
protected function modifyModel(&$nodes) { $request = $this->getRequest(); // TODO: put this into subclass ListController // remove all attributes except for display values if ($request->getBooleanValue('completeObjects', false) == false) { for($i=0,$count=sizeof($nodes); $i<$count; $i++) { $node = $nodes[$i]; $displayValues = $request->hasValue('values') ? array_map('trim', explode(',', $request->getValue('values'))) : $node->getProperty('displayValues'); $valueNames = array_merge($node->getValueNames(), $node->getRelationNames()); foreach($valueNames as $name) { if (!in_array($name, $displayValues)) { $node->removeValue($name); } } } } // render values if ($request->getBooleanValue('translateValues', false) == true) { NodeUtil::translateValues($nodes); } }
[ "protected", "function", "modifyModel", "(", "&", "$", "nodes", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "// TODO: put this into subclass ListController", "// remove all attributes except for display values", "if", "(", "$", "requ...
Modify the model passed to the view. @note subclasses will override this to implement special application requirements. @param $nodes A reference to the array of Node instances passed to the view
[ "Modify", "the", "model", "passed", "to", "the", "view", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/ListController.php#L189-L211
train
GW2Treasures/gw2api
src/V2/Authentication/AuthenticationHandler.php
AuthenticationHandler.onRequest
public function onRequest( RequestInterface $request ) { $apiKey = $this->getEndpoint()->getApiKey(); if($apiKey !== null) { $request = $request->withHeader( 'Authorization', 'Bearer '.$apiKey); } return $request; }
php
public function onRequest( RequestInterface $request ) { $apiKey = $this->getEndpoint()->getApiKey(); if($apiKey !== null) { $request = $request->withHeader( 'Authorization', 'Bearer '.$apiKey); } return $request; }
[ "public", "function", "onRequest", "(", "RequestInterface", "$", "request", ")", "{", "$", "apiKey", "=", "$", "this", "->", "getEndpoint", "(", ")", "->", "getApiKey", "(", ")", ";", "if", "(", "$", "apiKey", "!==", "null", ")", "{", "$", "request", ...
Add the API key as Authorization header. @param RequestInterface $request @return MessageInterface|RequestInterface
[ "Add", "the", "API", "key", "as", "Authorization", "header", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Authentication/AuthenticationHandler.php#L27-L35
train
vufind-org/vufindharvest
src/RecordWriterStrategy/CombinedRecordWriterStrategy.php
CombinedRecordWriterStrategy.getCombinedXML
protected function getCombinedXML($innerXML) { // Determine start and end tags from configuration: $start = $this->wrappingTag; $tmp = explode(' ', $start); $end = '</' . str_replace(['<', '>'], '', $tmp[0]) . '>'; // Assemble the document: return $start . $innerXML . $end; }
php
protected function getCombinedXML($innerXML) { // Determine start and end tags from configuration: $start = $this->wrappingTag; $tmp = explode(' ', $start); $end = '</' . str_replace(['<', '>'], '', $tmp[0]) . '>'; // Assemble the document: return $start . $innerXML . $end; }
[ "protected", "function", "getCombinedXML", "(", "$", "innerXML", ")", "{", "// Determine start and end tags from configuration:", "$", "start", "=", "$", "this", "->", "wrappingTag", ";", "$", "tmp", "=", "explode", "(", "' '", ",", "$", "start", ")", ";", "$"...
Support method for building combined XML document. @param string $innerXML XML for inside of document. @return string
[ "Support", "method", "for", "building", "combined", "XML", "document", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/RecordWriterStrategy/CombinedRecordWriterStrategy.php#L91-L100
train
vufind-org/vufindharvest
src/RecordWriterStrategy/CombinedRecordWriterStrategy.php
CombinedRecordWriterStrategy.addRecord
public function addRecord($id, $record) { $this->innerXML .= $record; if (false === $this->firstHarvestedId) { $this->firstHarvestedId = $id; } }
php
public function addRecord($id, $record) { $this->innerXML .= $record; if (false === $this->firstHarvestedId) { $this->firstHarvestedId = $id; } }
[ "public", "function", "addRecord", "(", "$", "id", ",", "$", "record", ")", "{", "$", "this", "->", "innerXML", ".=", "$", "record", ";", "if", "(", "false", "===", "$", "this", "->", "firstHarvestedId", ")", "{", "$", "this", "->", "firstHarvestedId",...
Add a non-deleted record. @param string $id ID @param string $record Record XML @return void
[ "Add", "a", "non", "-", "deleted", "record", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/RecordWriterStrategy/CombinedRecordWriterStrategy.php#L134-L140
train
vufind-org/vufindharvest
src/RecordWriterStrategy/CombinedRecordWriterStrategy.php
CombinedRecordWriterStrategy.endWrite
public function endWrite() { if (false !== $this->firstHarvestedId) { $this->saveFile( $this->firstHarvestedId, $this->getCombinedXML($this->innerXML) ); } if (!empty($this->deletedIds)) { $this->saveDeletedRecords($this->deletedIds); } }
php
public function endWrite() { if (false !== $this->firstHarvestedId) { $this->saveFile( $this->firstHarvestedId, $this->getCombinedXML($this->innerXML) ); } if (!empty($this->deletedIds)) { $this->saveDeletedRecords($this->deletedIds); } }
[ "public", "function", "endWrite", "(", ")", "{", "if", "(", "false", "!==", "$", "this", "->", "firstHarvestedId", ")", "{", "$", "this", "->", "saveFile", "(", "$", "this", "->", "firstHarvestedId", ",", "$", "this", "->", "getCombinedXML", "(", "$", ...
Close out the writing process. @return void
[ "Close", "out", "the", "writing", "process", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/RecordWriterStrategy/CombinedRecordWriterStrategy.php#L147-L158
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.getCachedImage
public static function getCachedImage($location, $returnLocation=false, $callback=null) { $location = rawurldecode($location); // strip the cache base from the location $cacheLocation = substr($location, strlen(self::IMAGE_CACHE_SECTION.'/')); // determine the width and source file from the location // the location is supposed to follow the pattern directory/{width}-basename $width = null; $basename = FileUtil::basename($cacheLocation); if (preg_match('/^([0-9]+)-/', $basename, $matches)) { // get required width from location and remove it from location $width = $matches[1]; $basename = preg_replace('/^'.$width.'-/', '', $basename); } $sourceFile = self::getSourceDir($cacheLocation).$basename; // create the resized image file, if not existing $resizedFile = self::getCacheRoot().$cacheLocation; if (FileUtil::fileExists($sourceFile) && !FileUtil::fileExists($resizedFile)) { FileUtil::mkdirRec(pathinfo($resizedFile, PATHINFO_DIRNAME)); $fixedFile = FileUtil::fixFilename($sourceFile); if ($width !== null) { self::resizeImage($fixedFile, $resizedFile, $width); } else { // just copy in case of undefined width copy($fixedFile, $resizedFile); } if (is_callable($callback)) { $callback($fixedFile, $resizedFile); } } // return the image file $file = FileUtil::fileExists($resizedFile) ? $resizedFile : (FileUtil::fileExists($sourceFile) ? $sourceFile : null); if ($returnLocation) { return $file; } $imageInfo = getimagesize($file); $image = file_get_contents($file); header('Content-type: '.$imageInfo['mime'].';'); header("Content-Length: ".strlen($image)); echo $image; }
php
public static function getCachedImage($location, $returnLocation=false, $callback=null) { $location = rawurldecode($location); // strip the cache base from the location $cacheLocation = substr($location, strlen(self::IMAGE_CACHE_SECTION.'/')); // determine the width and source file from the location // the location is supposed to follow the pattern directory/{width}-basename $width = null; $basename = FileUtil::basename($cacheLocation); if (preg_match('/^([0-9]+)-/', $basename, $matches)) { // get required width from location and remove it from location $width = $matches[1]; $basename = preg_replace('/^'.$width.'-/', '', $basename); } $sourceFile = self::getSourceDir($cacheLocation).$basename; // create the resized image file, if not existing $resizedFile = self::getCacheRoot().$cacheLocation; if (FileUtil::fileExists($sourceFile) && !FileUtil::fileExists($resizedFile)) { FileUtil::mkdirRec(pathinfo($resizedFile, PATHINFO_DIRNAME)); $fixedFile = FileUtil::fixFilename($sourceFile); if ($width !== null) { self::resizeImage($fixedFile, $resizedFile, $width); } else { // just copy in case of undefined width copy($fixedFile, $resizedFile); } if (is_callable($callback)) { $callback($fixedFile, $resizedFile); } } // return the image file $file = FileUtil::fileExists($resizedFile) ? $resizedFile : (FileUtil::fileExists($sourceFile) ? $sourceFile : null); if ($returnLocation) { return $file; } $imageInfo = getimagesize($file); $image = file_get_contents($file); header('Content-type: '.$imageInfo['mime'].';'); header("Content-Length: ".strlen($image)); echo $image; }
[ "public", "static", "function", "getCachedImage", "(", "$", "location", ",", "$", "returnLocation", "=", "false", ",", "$", "callback", "=", "null", ")", "{", "$", "location", "=", "rawurldecode", "(", "$", "location", ")", ";", "// strip the cache base from t...
Output the cached image for the given cache location @param $location @param $returnLocation Boolean indicating if only the file location should be returned (optional) @param $callback Function called, after the cached image is created, receives the original and cached image as parameters (optional) @return String, if returnLocation is true
[ "Output", "the", "cached", "image", "for", "the", "given", "cache", "location" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L155-L199
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.getCacheLocation
public static function getCacheLocation($imageFile, $width) { // get file name and cache directory $baseName = FileUtil::basename($imageFile); $directory = self::getCacheDir($imageFile); return self::makeRelative($directory.(strlen($width) > 0 ? $width.'-' : '').$baseName); }
php
public static function getCacheLocation($imageFile, $width) { // get file name and cache directory $baseName = FileUtil::basename($imageFile); $directory = self::getCacheDir($imageFile); return self::makeRelative($directory.(strlen($width) > 0 ? $width.'-' : '').$baseName); }
[ "public", "static", "function", "getCacheLocation", "(", "$", "imageFile", ",", "$", "width", ")", "{", "// get file name and cache directory", "$", "baseName", "=", "FileUtil", "::", "basename", "(", "$", "imageFile", ")", ";", "$", "directory", "=", "self", ...
Get the cache location for the given image and width @param $imageFile Image file located inside the upload directory of the application given as path relative to WCMF_BASE @param $width @return String
[ "Get", "the", "cache", "location", "for", "the", "given", "image", "and", "width" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L207-L212
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.invalidateCache
public static function invalidateCache($imageFile) { if (strlen($imageFile) > 0) { $imageFile = URIUtil::makeRelative($imageFile, self::getMediaRootRelative()); $fixedFile = FileUtil::fixFilename($imageFile); // get file name and cache directory $baseName = FileUtil::basename($imageFile); $directory = self::getCacheDir($imageFile); // delete matches of the form ([0-9]+)-$fixedFile if (is_dir($directory)) { foreach (FileUtil::getFiles($directory) as $file) { $matches = []; if (preg_match('/^([0-9]+)-/', $file, $matches) && $matches[1].'-'.$baseName === $file) { unlink($directory.$file); } } } } }
php
public static function invalidateCache($imageFile) { if (strlen($imageFile) > 0) { $imageFile = URIUtil::makeRelative($imageFile, self::getMediaRootRelative()); $fixedFile = FileUtil::fixFilename($imageFile); // get file name and cache directory $baseName = FileUtil::basename($imageFile); $directory = self::getCacheDir($imageFile); // delete matches of the form ([0-9]+)-$fixedFile if (is_dir($directory)) { foreach (FileUtil::getFiles($directory) as $file) { $matches = []; if (preg_match('/^([0-9]+)-/', $file, $matches) && $matches[1].'-'.$baseName === $file) { unlink($directory.$file); } } } } }
[ "public", "static", "function", "invalidateCache", "(", "$", "imageFile", ")", "{", "if", "(", "strlen", "(", "$", "imageFile", ")", ">", "0", ")", "{", "$", "imageFile", "=", "URIUtil", "::", "makeRelative", "(", "$", "imageFile", ",", "self", "::", "...
Delete the cached images for the given image file @param $imageFile Image file located inside the upload directory of the application given as path relative to WCMF_BASE
[ "Delete", "the", "cached", "images", "for", "the", "given", "image", "file" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L218-L237
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.getCacheDir
private static function getCacheDir($imageFile) { $mediaRoot = self::getMediaRootRelative(); return self::getCacheRoot().dirname(substr($imageFile, strlen($mediaRoot))).'/'; }
php
private static function getCacheDir($imageFile) { $mediaRoot = self::getMediaRootRelative(); return self::getCacheRoot().dirname(substr($imageFile, strlen($mediaRoot))).'/'; }
[ "private", "static", "function", "getCacheDir", "(", "$", "imageFile", ")", "{", "$", "mediaRoot", "=", "self", "::", "getMediaRootRelative", "(", ")", ";", "return", "self", "::", "getCacheRoot", "(", ")", ".", "dirname", "(", "substr", "(", "$", "imageFi...
Get the cache directory for the given source image file @param $imageFile @return String
[ "Get", "the", "cache", "directory", "for", "the", "given", "source", "image", "file" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L244-L247
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.getMediaRootRelative
private static function getMediaRootRelative() { $config = ObjectFactory::getInstance('configuration'); $mediaRootAbs = $config->getDirectoryValue('uploadDir', 'Media'); return self::makeRelative($mediaRootAbs); }
php
private static function getMediaRootRelative() { $config = ObjectFactory::getInstance('configuration'); $mediaRootAbs = $config->getDirectoryValue('uploadDir', 'Media'); return self::makeRelative($mediaRootAbs); }
[ "private", "static", "function", "getMediaRootRelative", "(", ")", "{", "$", "config", "=", "ObjectFactory", "::", "getInstance", "(", "'configuration'", ")", ";", "$", "mediaRootAbs", "=", "$", "config", "->", "getDirectoryValue", "(", "'uploadDir'", ",", "'Med...
Get the media root directory relative to the executed script @return String
[ "Get", "the", "media", "root", "directory", "relative", "to", "the", "executed", "script" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L271-L275
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.makeRelative
private static function makeRelative($location) { if (self::$scriptDirAbs == null) { self::$scriptDirAbs = dirname(FileUtil::realpath($_SERVER['SCRIPT_FILENAME'])).'/'; } return URIUtil::makeRelative($location, self::$scriptDirAbs); }
php
private static function makeRelative($location) { if (self::$scriptDirAbs == null) { self::$scriptDirAbs = dirname(FileUtil::realpath($_SERVER['SCRIPT_FILENAME'])).'/'; } return URIUtil::makeRelative($location, self::$scriptDirAbs); }
[ "private", "static", "function", "makeRelative", "(", "$", "location", ")", "{", "if", "(", "self", "::", "$", "scriptDirAbs", "==", "null", ")", "{", "self", "::", "$", "scriptDirAbs", "=", "dirname", "(", "FileUtil", "::", "realpath", "(", "$", "_SERVE...
Make the current location relative to the executed script @param $location @return String
[ "Make", "the", "current", "location", "relative", "to", "the", "executed", "script" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L282-L287
train
iherwig/wcmf
src/wcmf/lib/io/ImageUtil.php
ImageUtil.resizeImage
private static function resizeImage($sourceFile, $destFile, $width) { $image = new \Gumlet\ImageResize($sourceFile); $image->resizeToWidth($width); $image->save($destFile); }
php
private static function resizeImage($sourceFile, $destFile, $width) { $image = new \Gumlet\ImageResize($sourceFile); $image->resizeToWidth($width); $image->save($destFile); }
[ "private", "static", "function", "resizeImage", "(", "$", "sourceFile", ",", "$", "destFile", ",", "$", "width", ")", "{", "$", "image", "=", "new", "\\", "Gumlet", "\\", "ImageResize", "(", "$", "sourceFile", ")", ";", "$", "image", "->", "resizeToWidth...
Resize the given image to the given width @param $sourceFile @param $destFile @param $width
[ "Resize", "the", "given", "image", "to", "the", "given", "width" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/io/ImageUtil.php#L295-L299
train
iherwig/wcmf
src/wcmf/lib/persistence/RelationDescription.php
RelationDescription.isMultiValued
public function isMultiValued() { if ($this->isMultiValued == null) { $maxMultiplicity = $this->getOtherMaxMultiplicity(); $this->isMultiValued = ($maxMultiplicity > 1 || $maxMultiplicity == 'unbounded'); } return $this->isMultiValued; }
php
public function isMultiValued() { if ($this->isMultiValued == null) { $maxMultiplicity = $this->getOtherMaxMultiplicity(); $this->isMultiValued = ($maxMultiplicity > 1 || $maxMultiplicity == 'unbounded'); } return $this->isMultiValued; }
[ "public", "function", "isMultiValued", "(", ")", "{", "if", "(", "$", "this", "->", "isMultiValued", "==", "null", ")", "{", "$", "maxMultiplicity", "=", "$", "this", "->", "getOtherMaxMultiplicity", "(", ")", ";", "$", "this", "->", "isMultiValued", "=", ...
Determine if there may more than one objects at the other side of the relation @return Boolean
[ "Determine", "if", "there", "may", "more", "than", "one", "objects", "at", "the", "other", "side", "of", "the", "relation" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/RelationDescription.php#L86-L92
train
vufind-org/vufindharvest
src/RecordWriterStrategy/AbstractRecordWriterStrategy.php
AbstractRecordWriterStrategy.saveDeletedRecords
protected function saveDeletedRecords($ids) { $ids = (array)$ids; // make sure input is array format $filename = $this->getFilename($ids[0], 'delete'); file_put_contents($filename, implode("\n", $ids)); }
php
protected function saveDeletedRecords($ids) { $ids = (array)$ids; // make sure input is array format $filename = $this->getFilename($ids[0], 'delete'); file_put_contents($filename, implode("\n", $ids)); }
[ "protected", "function", "saveDeletedRecords", "(", "$", "ids", ")", "{", "$", "ids", "=", "(", "array", ")", "$", "ids", ";", "// make sure input is array format", "$", "filename", "=", "$", "this", "->", "getFilename", "(", "$", "ids", "[", "0", "]", "...
Create a tracking file to record the deletion of a record. @param string|array $ids ID(s) of deleted record(s). @return void
[ "Create", "a", "tracking", "file", "to", "record", "the", "deletion", "of", "a", "record", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/RecordWriterStrategy/AbstractRecordWriterStrategy.php#L91-L96
train
iherwig/wcmf
src/wcmf/lib/validation/Validator.php
Validator.validate
public static function validate($value, $validateDesc, $context=null) { // get validator list $validators = []; // split validateTypeDesc by commas and colons (separates validateType from options) $validateDescParts = []; preg_match_all('/\{(?:[^{}]|(?R))+\}|[^{}:,\s]+/', $validateDesc, $validateDescParts); // combine validateType and options again foreach ($validateDescParts[0] as $validateDescPart) { if (preg_match('/^\{.*?\}$/', $validateDescPart)) { // options of preceding validator $numValidators = sizeof($validators); if ($numValidators > 0) { $validators[$numValidators-1] .= ':'.$validateDescPart; } } else { $validators[] = $validateDescPart; } } // validate against each validator foreach ($validators as $validator) { list($validateTypeName, $validateOptions) = array_pad(preg_split('/:/', $validator, 2), 2, null); // get the validator that should be used for this value $validatorInstance = self::getValidateType($validateTypeName); if ($validateOptions !== null) { $decodedOptions = json_decode($validateOptions, true); if ($decodedOptions === null) { throw new ConfigurationException("No valid JSON format: ".$validateOptions); } $validateOptions = $decodedOptions; } if (!$validatorInstance->validate($value, $validateOptions, $context)) { return false; } } // all validators passed return true; }
php
public static function validate($value, $validateDesc, $context=null) { // get validator list $validators = []; // split validateTypeDesc by commas and colons (separates validateType from options) $validateDescParts = []; preg_match_all('/\{(?:[^{}]|(?R))+\}|[^{}:,\s]+/', $validateDesc, $validateDescParts); // combine validateType and options again foreach ($validateDescParts[0] as $validateDescPart) { if (preg_match('/^\{.*?\}$/', $validateDescPart)) { // options of preceding validator $numValidators = sizeof($validators); if ($numValidators > 0) { $validators[$numValidators-1] .= ':'.$validateDescPart; } } else { $validators[] = $validateDescPart; } } // validate against each validator foreach ($validators as $validator) { list($validateTypeName, $validateOptions) = array_pad(preg_split('/:/', $validator, 2), 2, null); // get the validator that should be used for this value $validatorInstance = self::getValidateType($validateTypeName); if ($validateOptions !== null) { $decodedOptions = json_decode($validateOptions, true); if ($decodedOptions === null) { throw new ConfigurationException("No valid JSON format: ".$validateOptions); } $validateOptions = $decodedOptions; } if (!$validatorInstance->validate($value, $validateOptions, $context)) { return false; } } // all validators passed return true; }
[ "public", "static", "function", "validate", "(", "$", "value", ",", "$", "validateDesc", ",", "$", "context", "=", "null", ")", "{", "// get validator list", "$", "validators", "=", "[", "]", ";", "// split validateTypeDesc by commas and colons (separates validateType...
Validate the given value against the given validateType description. @param $value The value to validate @param $validateDesc A string in the form validateTypeA,validateTypeB:optionsB, where validateType is a key in the configuration section 'validators' and options is a JSON encoded object as used in the 'validate_type' definition @param $context An associative array describing the validation context which will be passed to the ValidateType::validate() method (optional) @return Boolean
[ "Validate", "the", "given", "value", "against", "the", "given", "validateType", "description", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/validation/Validator.php#L35-L77
train
iherwig/wcmf
src/wcmf/lib/validation/Validator.php
Validator.getValidateType
protected static function getValidateType($validateTypeName) { $validatorTypes = ObjectFactory::getInstance('validators'); if (!isset($validatorTypes[$validateTypeName])) { throw new ConfigurationException("Configuration section 'Validators' does not contain a validator named: ".$validateTypeName); } return $validatorTypes[$validateTypeName]; }
php
protected static function getValidateType($validateTypeName) { $validatorTypes = ObjectFactory::getInstance('validators'); if (!isset($validatorTypes[$validateTypeName])) { throw new ConfigurationException("Configuration section 'Validators' does not contain a validator named: ".$validateTypeName); } return $validatorTypes[$validateTypeName]; }
[ "protected", "static", "function", "getValidateType", "(", "$", "validateTypeName", ")", "{", "$", "validatorTypes", "=", "ObjectFactory", "::", "getInstance", "(", "'validators'", ")", ";", "if", "(", "!", "isset", "(", "$", "validatorTypes", "[", "$", "valid...
Get the ValidateType instance for the given name. @param $validateTypeName The validate type's name @return ValidateType instance
[ "Get", "the", "ValidateType", "instance", "for", "the", "given", "name", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/validation/Validator.php#L84-L90
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.registerLoaded
protected function registerLoaded(PersistentObject $object) { $oid = $object->getOID(); $key = $oid->__toString(); if (self::$isDebugEnabled) { self::$logger->debug("New Data:\n".$object->dump()); self::$logger->debug("Registry before:\n".$this->dump()); } // register the object if it is newly loaded or // merge the attributes, if it is already loaded $registeredObject = null; if (isset($this->loadedObjects[$key])) { $registeredObject = $this->loadedObjects[$key]; // merge existing attributes with new attributes if (self::$isDebugEnabled) { self::$logger->debug("Merging data of ".$key); } $registeredObject->mergeValues($object); } else { if (self::$isDebugEnabled) { self::$logger->debug("Register loaded object: ".$key); } $this->loadedObjects[$key] = $object; // start to listen to changes if the transaction is active if ($this->isActive) { if (self::$isDebugEnabled) { self::$logger->debug("Start listening to: ".$key); } $this->observedObjects[$key] = $object; } $registeredObject = $object; } if (self::$isDebugEnabled) { self::$logger->debug("Registry after:\n".$this->dump()); } return $registeredObject; }
php
protected function registerLoaded(PersistentObject $object) { $oid = $object->getOID(); $key = $oid->__toString(); if (self::$isDebugEnabled) { self::$logger->debug("New Data:\n".$object->dump()); self::$logger->debug("Registry before:\n".$this->dump()); } // register the object if it is newly loaded or // merge the attributes, if it is already loaded $registeredObject = null; if (isset($this->loadedObjects[$key])) { $registeredObject = $this->loadedObjects[$key]; // merge existing attributes with new attributes if (self::$isDebugEnabled) { self::$logger->debug("Merging data of ".$key); } $registeredObject->mergeValues($object); } else { if (self::$isDebugEnabled) { self::$logger->debug("Register loaded object: ".$key); } $this->loadedObjects[$key] = $object; // start to listen to changes if the transaction is active if ($this->isActive) { if (self::$isDebugEnabled) { self::$logger->debug("Start listening to: ".$key); } $this->observedObjects[$key] = $object; } $registeredObject = $object; } if (self::$isDebugEnabled) { self::$logger->debug("Registry after:\n".$this->dump()); } return $registeredObject; }
[ "protected", "function", "registerLoaded", "(", "PersistentObject", "$", "object", ")", "{", "$", "oid", "=", "$", "object", "->", "getOID", "(", ")", ";", "$", "key", "=", "$", "oid", "->", "__toString", "(", ")", ";", "if", "(", "self", "::", "$", ...
Register a loaded object. The returned object is the registered instance. @param $object PersistentObject instance @return PersistentObject instance
[ "Register", "a", "loaded", "object", ".", "The", "returned", "object", "is", "the", "registered", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L204-L240
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.registerNew
protected function registerNew(PersistentObject $object) { $key = $object->getOID()->__toString(); if (self::$isDebugEnabled) { self::$logger->debug("Register new object: ".$key); } $this->newObjects[$key] = $object; $this->observedObjects[$key] = $object; return $object; }
php
protected function registerNew(PersistentObject $object) { $key = $object->getOID()->__toString(); if (self::$isDebugEnabled) { self::$logger->debug("Register new object: ".$key); } $this->newObjects[$key] = $object; $this->observedObjects[$key] = $object; return $object; }
[ "protected", "function", "registerNew", "(", "PersistentObject", "$", "object", ")", "{", "$", "key", "=", "$", "object", "->", "getOID", "(", ")", "->", "__toString", "(", ")", ";", "if", "(", "self", "::", "$", "isDebugEnabled", ")", "{", "self", "::...
Register a newly created object. The returned object is the registered instance. @param $object PersistentObject instance
[ "Register", "a", "newly", "created", "object", ".", "The", "returned", "object", "is", "the", "registered", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L246-L254
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.registerDirty
protected function registerDirty(PersistentObject $object) { $key = $object->getOID()->__toString(); // if it was a new or deleted object, we return immediatly if (isset($this->newObjects[$key]) || isset($this->deletedObjects[$key])) { return $object; } if (self::$isDebugEnabled) { self::$logger->debug("Register dirty object: ".$key); } $this->dirtyObjects[$key] = $object; return $object; }
php
protected function registerDirty(PersistentObject $object) { $key = $object->getOID()->__toString(); // if it was a new or deleted object, we return immediatly if (isset($this->newObjects[$key]) || isset($this->deletedObjects[$key])) { return $object; } if (self::$isDebugEnabled) { self::$logger->debug("Register dirty object: ".$key); } $this->dirtyObjects[$key] = $object; return $object; }
[ "protected", "function", "registerDirty", "(", "PersistentObject", "$", "object", ")", "{", "$", "key", "=", "$", "object", "->", "getOID", "(", ")", "->", "__toString", "(", ")", ";", "// if it was a new or deleted object, we return immediatly", "if", "(", "isset...
Register a dirty object. The returned object is the registered instance. @param $object PersistentObject instance
[ "Register", "a", "dirty", "object", ".", "The", "returned", "object", "is", "the", "registered", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L260-L271
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.clear
protected function clear() { foreach ($this->newObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->newObjects = []; foreach ($this->dirtyObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->dirtyObjects = []; foreach ($this->deletedObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->deletedObjects = []; foreach ($this->loadedObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->loadedObjects = []; $this->detachedObjects = []; }
php
protected function clear() { foreach ($this->newObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->newObjects = []; foreach ($this->dirtyObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->dirtyObjects = []; foreach ($this->deletedObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->deletedObjects = []; foreach ($this->loadedObjects as $object) { unset($this->observedObjects[$object->getOID()->__toString()]); } $this->loadedObjects = []; $this->detachedObjects = []; }
[ "protected", "function", "clear", "(", ")", "{", "foreach", "(", "$", "this", "->", "newObjects", "as", "$", "object", ")", "{", "unset", "(", "$", "this", "->", "observedObjects", "[", "$", "object", "->", "getOID", "(", ")", "->", "__toString", "(", ...
Clear all internal
[ "Clear", "all", "internal" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L385-L407
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.processInserts
protected function processInserts() { $insertedOids = []; $pendingInserts = []; $insertOids = array_keys($this->newObjects); while (sizeof($insertOids) > 0) { $key = array_shift($insertOids); if (self::$isDebugEnabled) { self::$logger->debug("Process insert on object: ".$key); } $object = $this->newObjects[$key]; // postpone insert, if the object has required objects that are // not persisted yet $canInsert = true; $requiredObjects = $object->getIndispensableObjects(); foreach ($requiredObjects as $requiredObject) { if ($requiredObject->getState() == PersistentObject::STATE_NEW) { if (self::$isDebugEnabled) { self::$logger->debug("Postpone insert of object: ".$key.". Required objects are not saved yet."); } $pendingInserts[] = $object; $canInsert = false; break; } } if ($canInsert) { $oldOid = $object->getOID(); $object->getMapper()->save($object); $insertedOids[$oldOid->__toString()] = $object->getOID()->__toString(); } unset($this->newObjects[$key]); $insertOids = array_keys($this->newObjects); unset($this->observedObjects[$key]); $this->observedObjects[$object->getOID()->__toString()] = $object; } // re-add pending inserts foreach ($pendingInserts as $object) { $key = $object->getOID()->__toString(); $this->newObjects[$key] = $object; } return $insertedOids; }
php
protected function processInserts() { $insertedOids = []; $pendingInserts = []; $insertOids = array_keys($this->newObjects); while (sizeof($insertOids) > 0) { $key = array_shift($insertOids); if (self::$isDebugEnabled) { self::$logger->debug("Process insert on object: ".$key); } $object = $this->newObjects[$key]; // postpone insert, if the object has required objects that are // not persisted yet $canInsert = true; $requiredObjects = $object->getIndispensableObjects(); foreach ($requiredObjects as $requiredObject) { if ($requiredObject->getState() == PersistentObject::STATE_NEW) { if (self::$isDebugEnabled) { self::$logger->debug("Postpone insert of object: ".$key.". Required objects are not saved yet."); } $pendingInserts[] = $object; $canInsert = false; break; } } if ($canInsert) { $oldOid = $object->getOID(); $object->getMapper()->save($object); $insertedOids[$oldOid->__toString()] = $object->getOID()->__toString(); } unset($this->newObjects[$key]); $insertOids = array_keys($this->newObjects); unset($this->observedObjects[$key]); $this->observedObjects[$object->getOID()->__toString()] = $object; } // re-add pending inserts foreach ($pendingInserts as $object) { $key = $object->getOID()->__toString(); $this->newObjects[$key] = $object; } return $insertedOids; }
[ "protected", "function", "processInserts", "(", ")", "{", "$", "insertedOids", "=", "[", "]", ";", "$", "pendingInserts", "=", "[", "]", ";", "$", "insertOids", "=", "array_keys", "(", "$", "this", "->", "newObjects", ")", ";", "while", "(", "sizeof", ...
Process the new objects queue @return Map of oids of inserted objects (key: oid string before commit, value: oid string after commit)
[ "Process", "the", "new", "objects", "queue" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L413-L453
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.processUpdates
protected function processUpdates() { $updatedOids = []; $updateOids = array_keys($this->dirtyObjects); while (sizeof($updateOids) > 0) { $key = array_shift($updateOids); if (self::$isDebugEnabled) { self::$logger->debug("Process update on object: ".$key); } $object = $this->dirtyObjects[$key]; $object->getMapper()->save($object); unset($this->dirtyObjects[$key]); $updatedOids[] = $key; $updateOids = array_keys($this->dirtyObjects); } return $updatedOids; }
php
protected function processUpdates() { $updatedOids = []; $updateOids = array_keys($this->dirtyObjects); while (sizeof($updateOids) > 0) { $key = array_shift($updateOids); if (self::$isDebugEnabled) { self::$logger->debug("Process update on object: ".$key); } $object = $this->dirtyObjects[$key]; $object->getMapper()->save($object); unset($this->dirtyObjects[$key]); $updatedOids[] = $key; $updateOids = array_keys($this->dirtyObjects); } return $updatedOids; }
[ "protected", "function", "processUpdates", "(", ")", "{", "$", "updatedOids", "=", "[", "]", ";", "$", "updateOids", "=", "array_keys", "(", "$", "this", "->", "dirtyObjects", ")", ";", "while", "(", "sizeof", "(", "$", "updateOids", ")", ">", "0", ")"...
Process the dirty objects queue @return Array of oid strings of updated objects
[ "Process", "the", "dirty", "objects", "queue" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L459-L474
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.processDeletes
protected function processDeletes() { $deletedOids = []; $deleteOids = array_keys($this->deletedObjects); while (sizeof($deleteOids) > 0) { $key = array_shift($deleteOids); if (self::$isDebugEnabled) { self::$logger->debug("Process delete on object: ".$key); } $object = $this->deletedObjects[$key]; $object->getMapper()->delete($object); unset($this->deletedObjects[$key]); $deletedOids[] = $key; $deleteOids = array_keys($this->deletedObjects); } return $deletedOids; }
php
protected function processDeletes() { $deletedOids = []; $deleteOids = array_keys($this->deletedObjects); while (sizeof($deleteOids) > 0) { $key = array_shift($deleteOids); if (self::$isDebugEnabled) { self::$logger->debug("Process delete on object: ".$key); } $object = $this->deletedObjects[$key]; $object->getMapper()->delete($object); unset($this->deletedObjects[$key]); $deletedOids[] = $key; $deleteOids = array_keys($this->deletedObjects); } return $deletedOids; }
[ "protected", "function", "processDeletes", "(", ")", "{", "$", "deletedOids", "=", "[", "]", ";", "$", "deleteOids", "=", "array_keys", "(", "$", "this", "->", "deletedObjects", ")", ";", "while", "(", "sizeof", "(", "$", "deleteOids", ")", ">", "0", "...
Process the deleted objects queue @return Array of oid strings of deleted objects
[ "Process", "the", "deleted", "objects", "queue" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L480-L495
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultTransaction.php
DefaultTransaction.dump
protected function dump() { $str = ''; foreach (array_values($this->loadedObjects) as $curObject) { $str .= $curObject->dump(); } return $str; }
php
protected function dump() { $str = ''; foreach (array_values($this->loadedObjects) as $curObject) { $str .= $curObject->dump(); } return $str; }
[ "protected", "function", "dump", "(", ")", "{", "$", "str", "=", "''", ";", "foreach", "(", "array_values", "(", "$", "this", "->", "loadedObjects", ")", "as", "$", "curObject", ")", "{", "$", "str", ".=", "$", "curObject", "->", "dump", "(", ")", ...
Dump the registry content into a string @return String
[ "Dump", "the", "registry", "content", "into", "a", "string" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L535-L541
train
iherwig/wcmf
src/wcmf/lib/persistence/PagingInfo.php
PagingInfo.getPagination
public function getPagination($urlPattern, $maxDisplayPages=10) { if ($this->getPageCount() <= 1) { return null; } // calculate pages $getPage = function($val) use ($urlPattern) { return ['num' => $val, 'url' => str_replace('{page}', $val, $urlPattern)]; }; $first = 1; $last = $this->getPageCount(); $page = $this->getPage(); $halfRange = floor($maxDisplayPages/2); $startPage = ($page < $halfRange) ? $first : max([$page-$halfRange, $first]); $endPage = $maxDisplayPages-1 + $startPage; $endPage = ($last < $endPage) ? $last : $endPage; $diff = $startPage - $endPage + $maxDisplayPages-1; $startPage -= ($startPage - $diff > 0) ? $diff : 0; $pages = array_map($getPage, range($startPage, $endPage)); return [ 'first' => $getPage($first), 'last' => $getPage($last), 'current' => $getPage($page), 'prev' => $page > $startPage ? $getPage($page-1) : null, 'next' => $page < $endPage ? $getPage($page+1) : null, 'pages' => $pages, ]; }
php
public function getPagination($urlPattern, $maxDisplayPages=10) { if ($this->getPageCount() <= 1) { return null; } // calculate pages $getPage = function($val) use ($urlPattern) { return ['num' => $val, 'url' => str_replace('{page}', $val, $urlPattern)]; }; $first = 1; $last = $this->getPageCount(); $page = $this->getPage(); $halfRange = floor($maxDisplayPages/2); $startPage = ($page < $halfRange) ? $first : max([$page-$halfRange, $first]); $endPage = $maxDisplayPages-1 + $startPage; $endPage = ($last < $endPage) ? $last : $endPage; $diff = $startPage - $endPage + $maxDisplayPages-1; $startPage -= ($startPage - $diff > 0) ? $diff : 0; $pages = array_map($getPage, range($startPage, $endPage)); return [ 'first' => $getPage($first), 'last' => $getPage($last), 'current' => $getPage($page), 'prev' => $page > $startPage ? $getPage($page-1) : null, 'next' => $page < $endPage ? $getPage($page+1) : null, 'pages' => $pages, ]; }
[ "public", "function", "getPagination", "(", "$", "urlPattern", ",", "$", "maxDisplayPages", "=", "10", ")", "{", "if", "(", "$", "this", "->", "getPageCount", "(", ")", "<=", "1", ")", "{", "return", "null", ";", "}", "// calculate pages", "$", "getPage"...
Get the pages for a pagination navigation @param $urlPattern Url string to use containing literal {page}, that will be replaced @param $maxDisplayPages Maximum number of pages to display (optional, default: 10) @return Array with keys 'first', 'last', 'current', 'prev', 'next', 'pages' and arrays with 'url', 'num' as values or null, if page count <= 1
[ "Get", "the", "pages", "for", "a", "pagination", "navigation" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/PagingInfo.php#L140-L171
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.getManyToOneRelationSelectSQL
protected function getManyToOneRelationSelectSQL(RelationDescription $relationDescription, array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null, PagingInfo $pagingInfo=null) { $thisAttr = $this->getAttribute($relationDescription->getFkName()); $tableName = $this->getRealTableName(); // id parameters $parameters = []; $idPlaceholder = ':'.$tableName.'_'.$thisAttr->getName(); for ($i=0, $count=sizeof($otherObjectProxies); $i<$count; $i++) { $dbid = $otherObjectProxies[$i]->getValue($relationDescription->getIdName()); if ($dbid === null) { $dbid = SQLConst::NULL(); } $parameters[$idPlaceholder.$i] = $dbid; } // statement $selectStmt = $this->getRelationStatement($thisAttr, $parameters, $otherObjectProxies, $otherRole, $criteria, $orderby, $pagingInfo); return [$selectStmt, $relationDescription->getIdName(), $relationDescription->getFkName()]; }
php
protected function getManyToOneRelationSelectSQL(RelationDescription $relationDescription, array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null, PagingInfo $pagingInfo=null) { $thisAttr = $this->getAttribute($relationDescription->getFkName()); $tableName = $this->getRealTableName(); // id parameters $parameters = []; $idPlaceholder = ':'.$tableName.'_'.$thisAttr->getName(); for ($i=0, $count=sizeof($otherObjectProxies); $i<$count; $i++) { $dbid = $otherObjectProxies[$i]->getValue($relationDescription->getIdName()); if ($dbid === null) { $dbid = SQLConst::NULL(); } $parameters[$idPlaceholder.$i] = $dbid; } // statement $selectStmt = $this->getRelationStatement($thisAttr, $parameters, $otherObjectProxies, $otherRole, $criteria, $orderby, $pagingInfo); return [$selectStmt, $relationDescription->getIdName(), $relationDescription->getFkName()]; }
[ "protected", "function", "getManyToOneRelationSelectSQL", "(", "RelationDescription", "$", "relationDescription", ",", "array", "$", "otherObjectProxies", ",", "$", "otherRole", ",", "$", "criteria", "=", "null", ",", "$", "orderby", "=", "null", ",", "PagingInfo", ...
Get the statement for selecting a many-to-one relation @see RDBMapper::getRelationSelectSQL()
[ "Get", "the", "statement", "for", "selecting", "a", "many", "-", "to", "-", "one", "relation" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L306-L327
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.getRelationStatement
protected function getRelationStatement($thisAttr, $parameters, array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null, PagingInfo $pagingInfo=null) { $queryId = $this->getCacheKey($otherRole.sizeof($otherObjectProxies), null, $criteria, $orderby, $pagingInfo); $tableName = $this->getRealTableName(); $selectStmt = SelectStatement::get($this, $queryId); if (!$selectStmt->isCached()) { // initialize the statement $selectStmt->from($tableName, ''); $this->addColumns($selectStmt, $tableName); $selectStmt->where($this->quoteIdentifier($tableName).'.'. $this->quoteIdentifier($thisAttr->getColumn()).' IN('.join(',', array_keys($parameters)).')'); // order $this->addOrderBy($selectStmt, $orderby, $this->getType(), $tableName, $this->getDefaultOrder($otherRole)); // additional conditions $parameters = array_merge($parameters, $this->addCriteria($selectStmt, $criteria, $tableName)); // limit if ($pagingInfo != null) { $selectStmt->limit($pagingInfo->getPageSize()); } } else { // on used statements only set parameters $parameters = array_merge($parameters, $this->getParameters($criteria, $tableName)); } // set parameters $selectStmt->setParameters($parameters); // always update offset, since it's most likely not contained in the cache id if ($pagingInfo != null) { $selectStmt->offset($pagingInfo->getOffset()); } return $selectStmt; }
php
protected function getRelationStatement($thisAttr, $parameters, array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null, PagingInfo $pagingInfo=null) { $queryId = $this->getCacheKey($otherRole.sizeof($otherObjectProxies), null, $criteria, $orderby, $pagingInfo); $tableName = $this->getRealTableName(); $selectStmt = SelectStatement::get($this, $queryId); if (!$selectStmt->isCached()) { // initialize the statement $selectStmt->from($tableName, ''); $this->addColumns($selectStmt, $tableName); $selectStmt->where($this->quoteIdentifier($tableName).'.'. $this->quoteIdentifier($thisAttr->getColumn()).' IN('.join(',', array_keys($parameters)).')'); // order $this->addOrderBy($selectStmt, $orderby, $this->getType(), $tableName, $this->getDefaultOrder($otherRole)); // additional conditions $parameters = array_merge($parameters, $this->addCriteria($selectStmt, $criteria, $tableName)); // limit if ($pagingInfo != null) { $selectStmt->limit($pagingInfo->getPageSize()); } } else { // on used statements only set parameters $parameters = array_merge($parameters, $this->getParameters($criteria, $tableName)); } // set parameters $selectStmt->setParameters($parameters); // always update offset, since it's most likely not contained in the cache id if ($pagingInfo != null) { $selectStmt->offset($pagingInfo->getOffset()); } return $selectStmt; }
[ "protected", "function", "getRelationStatement", "(", "$", "thisAttr", ",", "$", "parameters", ",", "array", "$", "otherObjectProxies", ",", "$", "otherRole", ",", "$", "criteria", "=", "null", ",", "$", "orderby", "=", "null", ",", "PagingInfo", "$", "pagin...
Get the select statement for a many-to-one or one-to-many relation. This method is the common part used in both relations. @see RDBMapper::getRelationSelectSQL()
[ "Get", "the", "select", "statement", "for", "a", "many", "-", "to", "-", "one", "or", "one", "-", "to", "-", "many", "relation", ".", "This", "method", "is", "the", "common", "part", "used", "in", "both", "relations", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L362-L396
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.addColumns
protected function addColumns(SelectStatement $selectStmt, $tableName, $attributes=null) { // columns $attributeDescs = $this->getAttributes(); $columns = []; foreach($attributeDescs as $curAttributeDesc) { $name = $curAttributeDesc->getName(); if (($attributes == null || in_array($name, $attributes)) && $curAttributeDesc instanceof RDBAttributeDescription) { $columns[$curAttributeDesc->getName()] = $curAttributeDesc->getColumn(); } } $selectStmt->columns($columns, true); // references $selectStmt = $this->addReferences($selectStmt, $tableName); return $selectStmt; }
php
protected function addColumns(SelectStatement $selectStmt, $tableName, $attributes=null) { // columns $attributeDescs = $this->getAttributes(); $columns = []; foreach($attributeDescs as $curAttributeDesc) { $name = $curAttributeDesc->getName(); if (($attributes == null || in_array($name, $attributes)) && $curAttributeDesc instanceof RDBAttributeDescription) { $columns[$curAttributeDesc->getName()] = $curAttributeDesc->getColumn(); } } $selectStmt->columns($columns, true); // references $selectStmt = $this->addReferences($selectStmt, $tableName); return $selectStmt; }
[ "protected", "function", "addColumns", "(", "SelectStatement", "$", "selectStmt", ",", "$", "tableName", ",", "$", "attributes", "=", "null", ")", "{", "// columns", "$", "attributeDescs", "=", "$", "this", "->", "getAttributes", "(", ")", ";", "$", "columns...
Add the columns to a given select statement. @param $selectStmt The select statement (instance of SelectStatement) @param $tableName The table name @param $attributes Array of attribute names (optional) @return SelectStatement
[ "Add", "the", "columns", "to", "a", "given", "select", "statement", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L524-L539
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.addCriteria
protected function addCriteria(SelectStatement $selectStmt, $criteria, $tableName) { $parameters = []; if ($criteria != null) { foreach ($criteria as $criterion) { if ($criterion instanceof Criteria) { $placeholder = ':'.$tableName.'_'.$criterion->getAttribute(); list($criteriaCondition, $criteriaPlaceholder) = $this->renderCriteria($criterion, $placeholder, $tableName); $selectStmt->where($criteriaCondition, $criterion->getCombineOperator()); if ($criteriaPlaceholder) { $value = $criterion->getValue(); if (is_array($criteriaPlaceholder)) { $parameters = array_merge($parameters, array_combine($criteriaPlaceholder, $value)); } else { $parameters[$criteriaPlaceholder] = $value; } } } else { throw new IllegalArgumentException("The select condition must be an instance of Criteria"); } } } return $parameters; }
php
protected function addCriteria(SelectStatement $selectStmt, $criteria, $tableName) { $parameters = []; if ($criteria != null) { foreach ($criteria as $criterion) { if ($criterion instanceof Criteria) { $placeholder = ':'.$tableName.'_'.$criterion->getAttribute(); list($criteriaCondition, $criteriaPlaceholder) = $this->renderCriteria($criterion, $placeholder, $tableName); $selectStmt->where($criteriaCondition, $criterion->getCombineOperator()); if ($criteriaPlaceholder) { $value = $criterion->getValue(); if (is_array($criteriaPlaceholder)) { $parameters = array_merge($parameters, array_combine($criteriaPlaceholder, $value)); } else { $parameters[$criteriaPlaceholder] = $value; } } } else { throw new IllegalArgumentException("The select condition must be an instance of Criteria"); } } } return $parameters; }
[ "protected", "function", "addCriteria", "(", "SelectStatement", "$", "selectStmt", ",", "$", "criteria", ",", "$", "tableName", ")", "{", "$", "parameters", "=", "[", "]", ";", "if", "(", "$", "criteria", "!=", "null", ")", "{", "foreach", "(", "$", "c...
Add the given criteria to the select statement @param $selectStmt The select statement (instance of SelectStatement) @param $criteria An array of Criteria instances that define conditions on the object's attributes (maybe null) @param $tableName The table name @return Array of placeholder/value pairs
[ "Add", "the", "given", "criteria", "to", "the", "select", "statement" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L613-L638
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.addOrderBy
protected function addOrderBy(SelectStatement $selectStmt, $orderby, $orderType, $aliasName, $defaultOrder) { if ($orderby == null) { $orderby = []; // use default ordering if ($defaultOrder && sizeof($defaultOrder) > 0) { foreach ($defaultOrder as $orderDef) { $orderby[] = $orderDef['sortFieldName']." ".$orderDef['sortDirection']; $orderType = $orderDef['sortType']; } } } for ($i=0, $count=sizeof($orderby); $i<$count; $i++) { $curOrderBy = $orderby[$i]; $orderByParts = preg_split('/ /', $curOrderBy); $orderAttribute = $orderByParts[0]; $orderDirection = sizeof($orderByParts) > 1 ? $orderByParts[1] : 'ASC'; if (strpos($orderAttribute, '.') > 0) { // the type is included in the attribute $orderAttributeParts = preg_split('/\./', $orderAttribute); $orderAttribute = array_pop($orderAttributeParts); } $mapper = $orderType != null ? self::getMapper($orderType) : $this; $orderAttributeDesc = $mapper->getAttribute($orderAttribute); if ($orderAttributeDesc instanceof ReferenceDescription) { // add the referenced column without table name $mapper = self::getMapper($orderAttributeDesc->getOtherType()); $orderAttributeDesc = $mapper->getAttribute($orderAttributeDesc->getOtherName()); $orderColumnName = $orderAttributeDesc->getColumn(); } elseif ($orderAttributeDesc instanceof TransientAttributeDescription) { // skip, because no column exists continue; } else { // add the column with table name $tableName = $aliasName != null ? $aliasName : $mapper->getRealTableName(); $orderColumnName = $tableName.'.'.$orderAttributeDesc->getColumn(); } $selectStmt->order([$orderColumnName.' '.$orderDirection]); } }
php
protected function addOrderBy(SelectStatement $selectStmt, $orderby, $orderType, $aliasName, $defaultOrder) { if ($orderby == null) { $orderby = []; // use default ordering if ($defaultOrder && sizeof($defaultOrder) > 0) { foreach ($defaultOrder as $orderDef) { $orderby[] = $orderDef['sortFieldName']." ".$orderDef['sortDirection']; $orderType = $orderDef['sortType']; } } } for ($i=0, $count=sizeof($orderby); $i<$count; $i++) { $curOrderBy = $orderby[$i]; $orderByParts = preg_split('/ /', $curOrderBy); $orderAttribute = $orderByParts[0]; $orderDirection = sizeof($orderByParts) > 1 ? $orderByParts[1] : 'ASC'; if (strpos($orderAttribute, '.') > 0) { // the type is included in the attribute $orderAttributeParts = preg_split('/\./', $orderAttribute); $orderAttribute = array_pop($orderAttributeParts); } $mapper = $orderType != null ? self::getMapper($orderType) : $this; $orderAttributeDesc = $mapper->getAttribute($orderAttribute); if ($orderAttributeDesc instanceof ReferenceDescription) { // add the referenced column without table name $mapper = self::getMapper($orderAttributeDesc->getOtherType()); $orderAttributeDesc = $mapper->getAttribute($orderAttributeDesc->getOtherName()); $orderColumnName = $orderAttributeDesc->getColumn(); } elseif ($orderAttributeDesc instanceof TransientAttributeDescription) { // skip, because no column exists continue; } else { // add the column with table name $tableName = $aliasName != null ? $aliasName : $mapper->getRealTableName(); $orderColumnName = $tableName.'.'.$orderAttributeDesc->getColumn(); } $selectStmt->order([$orderColumnName.' '.$orderDirection]); } }
[ "protected", "function", "addOrderBy", "(", "SelectStatement", "$", "selectStmt", ",", "$", "orderby", ",", "$", "orderType", ",", "$", "aliasName", ",", "$", "defaultOrder", ")", "{", "if", "(", "$", "orderby", "==", "null", ")", "{", "$", "orderby", "=...
Add the given order to the select statement @param $selectStmt The select statement (instance of SelectStatement) @param $orderby An array holding names of attributes to order by, maybe appended with 'ASC', 'DESC' (maybe null) @param $orderType The type that define the attributes in orderby (maybe null) @param $aliasName The table alias name to be used (maybe null) @param $defaultOrder The default order definition to use, if orderby is null (@see PersistenceMapper::getDefaultOrder())
[ "Add", "the", "given", "order", "to", "the", "select", "statement" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L648-L688
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.convertValuesForStorage
protected function convertValuesForStorage($values) { // filter values according to type foreach($values as $valueName => $value) { $type = $this->getAttribute($valueName)->getType(); // integer if (strpos(strtolower($type), 'int') === 0) { $value = (strlen($value) == 0) ? null : intval($value); $values[$valueName] = $value; } // null values if ($value === null) { $values[$valueName] = SQLConst::NULL(); } } return $values; }
php
protected function convertValuesForStorage($values) { // filter values according to type foreach($values as $valueName => $value) { $type = $this->getAttribute($valueName)->getType(); // integer if (strpos(strtolower($type), 'int') === 0) { $value = (strlen($value) == 0) ? null : intval($value); $values[$valueName] = $value; } // null values if ($value === null) { $values[$valueName] = SQLConst::NULL(); } } return $values; }
[ "protected", "function", "convertValuesForStorage", "(", "$", "values", ")", "{", "// filter values according to type", "foreach", "(", "$", "values", "as", "$", "valueName", "=>", "$", "value", ")", "{", "$", "type", "=", "$", "this", "->", "getAttribute", "(...
Convert values before putting into storage @param $values Associative Array @return Associative Array
[ "Convert", "values", "before", "putting", "into", "storage" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L749-L764
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.getSortableObject
protected function getSortableObject(PersistentObjectProxy $objectProxy, PersistentObjectProxy $relativeProxy, RelationDescription $relationDesc) { // in a many to many relation, we have to modify the order of the relation objects if ($relationDesc instanceof RDBManyToManyRelationDescription) { $nmObjects = $this->loadRelationObjects($objectProxy, $relativeProxy, $relationDesc); return $nmObjects[0]; } return $relativeProxy; }
php
protected function getSortableObject(PersistentObjectProxy $objectProxy, PersistentObjectProxy $relativeProxy, RelationDescription $relationDesc) { // in a many to many relation, we have to modify the order of the relation objects if ($relationDesc instanceof RDBManyToManyRelationDescription) { $nmObjects = $this->loadRelationObjects($objectProxy, $relativeProxy, $relationDesc); return $nmObjects[0]; } return $relativeProxy; }
[ "protected", "function", "getSortableObject", "(", "PersistentObjectProxy", "$", "objectProxy", ",", "PersistentObjectProxy", "$", "relativeProxy", ",", "RelationDescription", "$", "relationDesc", ")", "{", "// in a many to many relation, we have to modify the order of the relation...
Get the object which carries the sortkey in the relation of the given object and relative. @param PersistentObjectProxy $objectProxy @param PersistentObjectProxy $relativeProxy @param RelationDescription $relationDesc The relation description @return PersistentObjectProxy
[ "Get", "the", "object", "which", "carries", "the", "sortkey", "in", "the", "relation", "of", "the", "given", "object", "and", "relative", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L774-L782
train
iherwig/wcmf
src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php
NodeUnifiedRDBMapper.loadRelationObjects
protected function loadRelationObjects(PersistentObjectProxy $objectProxy, PersistentObjectProxy $relativeProxy, RDBManyToManyRelationDescription $relationDesc, $includeTransaction=false) { $nmMapper = self::getMapper($relationDesc->getThisEndRelation()->getOtherType()); $nmType = $nmMapper->getType(); $thisId = $objectProxy->getOID()->getFirstId(); $otherId = $relativeProxy->getOID()->getFirstId(); $thisEndRelation = $relationDesc->getThisEndRelation(); $otherEndRelation = $relationDesc->getOtherEndRelation(); $thisFkAttr = $nmMapper->getAttribute($thisEndRelation->getFkName()); $otherFkAttr = $nmMapper->getAttribute($otherEndRelation->getFkName()); $criteria1 = new Criteria($nmType, $thisFkAttr->getName(), "=", $thisId); $criteria2 = new Criteria($nmType, $otherFkAttr->getName(), "=", $otherId); $criteria = [$criteria1, $criteria2]; $nmObjects = $nmMapper->loadObjects($nmType, BuildDepth::SINGLE, $criteria); if ($includeTransaction) { $transaction = $this->persistenceFacade->getTransaction(); $objects = $transaction->getObjects(); foreach ($objects as $object) { if ($object->getType() == $nmType && $object instanceof Node) { // we expect single valued relation ends $thisEndObject = $object->getValue($thisEndRelation->getThisRole()); $otherEndObject = $object->getValue($otherEndRelation->getOtherRole()); if ($objectProxy->getOID() == $thisEndObject->getOID() && $relativeProxy->getOID() == $otherEndObject->getOID()) { $nmObjects[] = $object; } } } } return $nmObjects; }
php
protected function loadRelationObjects(PersistentObjectProxy $objectProxy, PersistentObjectProxy $relativeProxy, RDBManyToManyRelationDescription $relationDesc, $includeTransaction=false) { $nmMapper = self::getMapper($relationDesc->getThisEndRelation()->getOtherType()); $nmType = $nmMapper->getType(); $thisId = $objectProxy->getOID()->getFirstId(); $otherId = $relativeProxy->getOID()->getFirstId(); $thisEndRelation = $relationDesc->getThisEndRelation(); $otherEndRelation = $relationDesc->getOtherEndRelation(); $thisFkAttr = $nmMapper->getAttribute($thisEndRelation->getFkName()); $otherFkAttr = $nmMapper->getAttribute($otherEndRelation->getFkName()); $criteria1 = new Criteria($nmType, $thisFkAttr->getName(), "=", $thisId); $criteria2 = new Criteria($nmType, $otherFkAttr->getName(), "=", $otherId); $criteria = [$criteria1, $criteria2]; $nmObjects = $nmMapper->loadObjects($nmType, BuildDepth::SINGLE, $criteria); if ($includeTransaction) { $transaction = $this->persistenceFacade->getTransaction(); $objects = $transaction->getObjects(); foreach ($objects as $object) { if ($object->getType() == $nmType && $object instanceof Node) { // we expect single valued relation ends $thisEndObject = $object->getValue($thisEndRelation->getThisRole()); $otherEndObject = $object->getValue($otherEndRelation->getOtherRole()); if ($objectProxy->getOID() == $thisEndObject->getOID() && $relativeProxy->getOID() == $otherEndObject->getOID()) { $nmObjects[] = $object; } } } } return $nmObjects; }
[ "protected", "function", "loadRelationObjects", "(", "PersistentObjectProxy", "$", "objectProxy", ",", "PersistentObjectProxy", "$", "relativeProxy", ",", "RDBManyToManyRelationDescription", "$", "relationDesc", ",", "$", "includeTransaction", "=", "false", ")", "{", "$",...
Load the relation objects in a many to many relation from the database. @param $objectProxy The proxy at this end of the relation. @param $relativeProxy The proxy at the other end of the relation. @param $relationDesc The RDBManyToManyRelationDescription instance describing the relation. @param $includeTransaction Boolean whether to also search in the current transaction (default: false) @return Array of PersistentObject instances
[ "Load", "the", "relation", "objects", "in", "a", "many", "to", "many", "relation", "from", "the", "database", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/impl/NodeUnifiedRDBMapper.php#L792-L826
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistentObject.php
DefaultPersistentObject.initializeMapper
private function initializeMapper() { // set the mapper $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); if ($persistenceFacade->isKnownType($this->type)) { $this->mapper = $persistenceFacade->getMapper($this->type); } else { // initialize null mapper if not done already if (self::$nullMapper == null) { self::$nullMapper = new NullMapper(); } $this->mapper = self::$nullMapper; } }
php
private function initializeMapper() { // set the mapper $persistenceFacade = ObjectFactory::getInstance('persistenceFacade'); if ($persistenceFacade->isKnownType($this->type)) { $this->mapper = $persistenceFacade->getMapper($this->type); } else { // initialize null mapper if not done already if (self::$nullMapper == null) { self::$nullMapper = new NullMapper(); } $this->mapper = self::$nullMapper; } }
[ "private", "function", "initializeMapper", "(", ")", "{", "// set the mapper", "$", "persistenceFacade", "=", "ObjectFactory", "::", "getInstance", "(", "'persistenceFacade'", ")", ";", "if", "(", "$", "persistenceFacade", "->", "isKnownType", "(", "$", "this", "-...
Initialize the PersistenceMapper instance
[ "Initialize", "the", "PersistenceMapper", "instance" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistentObject.php#L98-L111
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistentObject.php
DefaultPersistentObject.setOIDInternal
protected function setOIDInternal(ObjectId $oid, $triggerListeners) { $this->type = $oid->getType(); $this->oid = $oid; // update the primary key attributes $ids = $oid->getId(); $pkNames = $this->getMapper()->getPkNames(); for ($i=0, $count=sizeof($pkNames); $i<$count; $i++) { if ($triggerListeners) { $this->setValue($pkNames[$i], $ids[$i], true); } else { $this->setValueInternal($pkNames[$i], $ids[$i]); } } }
php
protected function setOIDInternal(ObjectId $oid, $triggerListeners) { $this->type = $oid->getType(); $this->oid = $oid; // update the primary key attributes $ids = $oid->getId(); $pkNames = $this->getMapper()->getPkNames(); for ($i=0, $count=sizeof($pkNames); $i<$count; $i++) { if ($triggerListeners) { $this->setValue($pkNames[$i], $ids[$i], true); } else { $this->setValueInternal($pkNames[$i], $ids[$i]); } } }
[ "protected", "function", "setOIDInternal", "(", "ObjectId", "$", "oid", ",", "$", "triggerListeners", ")", "{", "$", "this", "->", "type", "=", "$", "oid", "->", "getType", "(", ")", ";", "$", "this", "->", "oid", "=", "$", "oid", ";", "// update the p...
Set the object id of the PersistentObject. @param $oid The PersistentObject's oid. @param $triggerListeners Boolean, whether value CahngeListeners should be notified or not
[ "Set", "the", "object", "id", "of", "the", "PersistentObject", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistentObject.php#L150-L164
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistentObject.php
DefaultPersistentObject.updateOID
private function updateOID() { $pkValues = []; // collect the values of the primary keys and compose the oid from them $pkNames = $this->getMapper()->getPkNames(); foreach ($pkNames as $pkName) { $pkValues[] = self::getValue($pkName); } $this->oid = new ObjectId($this->getType(), $pkValues); }
php
private function updateOID() { $pkValues = []; // collect the values of the primary keys and compose the oid from them $pkNames = $this->getMapper()->getPkNames(); foreach ($pkNames as $pkName) { $pkValues[] = self::getValue($pkName); } $this->oid = new ObjectId($this->getType(), $pkValues); }
[ "private", "function", "updateOID", "(", ")", "{", "$", "pkValues", "=", "[", "]", ";", "// collect the values of the primary keys and compose the oid from them", "$", "pkNames", "=", "$", "this", "->", "getMapper", "(", ")", "->", "getPkNames", "(", ")", ";", "...
Recalculate the object id
[ "Recalculate", "the", "object", "id" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistentObject.php#L272-L280
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistentObject.php
DefaultPersistentObject.validateValueAgainstValidateType
protected function validateValueAgainstValidateType($name, $value) { // don't validate referenced values $mapper = $this->getMapper(); if ($mapper->hasAttribute($name) && $mapper->getAttribute($name) instanceof ReferenceDescription) { return; } $validateType = $this->getValueProperty($name, 'validate_type'); if (($validateType == '' || Validator::validate($value, $validateType, ['entity' => $this, 'value' => $name]))) { return; } // construct the error message $messageInstance = ObjectFactory::getInstance('message'); $validateDescription = $this->getValueProperty($name, 'validate_description'); if (strlen($validateDescription) > 0) { // use configured message if existing $errorMessage = $messageInstance->getText($validateDescription); } else { // default text $errorMessage = $messageInstance->getText("The value of '%0%' (%1%) is invalid.", [$messageInstance->getText($name), $value]); } throw new ValidationException($name, $value, $errorMessage); }
php
protected function validateValueAgainstValidateType($name, $value) { // don't validate referenced values $mapper = $this->getMapper(); if ($mapper->hasAttribute($name) && $mapper->getAttribute($name) instanceof ReferenceDescription) { return; } $validateType = $this->getValueProperty($name, 'validate_type'); if (($validateType == '' || Validator::validate($value, $validateType, ['entity' => $this, 'value' => $name]))) { return; } // construct the error message $messageInstance = ObjectFactory::getInstance('message'); $validateDescription = $this->getValueProperty($name, 'validate_description'); if (strlen($validateDescription) > 0) { // use configured message if existing $errorMessage = $messageInstance->getText($validateDescription); } else { // default text $errorMessage = $messageInstance->getText("The value of '%0%' (%1%) is invalid.", [$messageInstance->getText($name), $value]); } throw new ValidationException($name, $value, $errorMessage); }
[ "protected", "function", "validateValueAgainstValidateType", "(", "$", "name", ",", "$", "value", ")", "{", "// don't validate referenced values", "$", "mapper", "=", "$", "this", "->", "getMapper", "(", ")", ";", "if", "(", "$", "mapper", "->", "hasAttribute", ...
Check a value's value against the validation type set on it. This method uses the validateType property of the attribute definition. Throws a ValidationException if the value is not valid. @param $name The name of the item to set. @param $value The value of the item.
[ "Check", "a", "value", "s", "value", "against", "the", "validation", "type", "set", "on", "it", ".", "This", "method", "uses", "the", "validateType", "property", "of", "the", "attribute", "definition", ".", "Throws", "a", "ValidationException", "if", "the", ...
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistentObject.php#L424-L447
train
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistentObject.php
DefaultPersistentObject.dumpArray
private static function dumpArray(array $array) { $str = "["; foreach ($array as $value) { if (is_object($value)) { $str .= $value->__toString().", "; } else { $str .= $value.", "; } } $str = preg_replace("/, $/", "", $str)."]"; return $str; }
php
private static function dumpArray(array $array) { $str = "["; foreach ($array as $value) { if (is_object($value)) { $str .= $value->__toString().", "; } else { $str .= $value.", "; } } $str = preg_replace("/, $/", "", $str)."]"; return $str; }
[ "private", "static", "function", "dumpArray", "(", "array", "$", "array", ")", "{", "$", "str", "=", "\"[\"", ";", "foreach", "(", "$", "array", "as", "$", "value", ")", "{", "if", "(", "is_object", "(", "$", "value", ")", ")", "{", "$", "str", "...
Get a string representation of an array of values. @param $array The array to dump @return String
[ "Get", "a", "string", "representation", "of", "an", "array", "of", "values", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistentObject.php#L610-L622
train
iherwig/wcmf
src/wcmf/lib/model/StringQuery.php
StringQuery.mapToDatabase
protected static function mapToDatabase($type, $valueName) { $mapper = self::getMapper($type); if ($mapper->hasAttribute($valueName)) { $attributeDescription = $mapper->getAttribute($valueName); } else { // if the attribute does not exist, it might be the column name already foreach ($mapper->getAttributes() as $curAttributeDesc) { if ($curAttributeDesc->getColumn() == $valueName) { $attributeDescription = $curAttributeDesc; break; } } } if (!$attributeDescription) { throw new PersistenceException("No attribute '".$valueName."' exists in '".$type."'"); } $table = $mapper->getRealTableName(); $column = $attributeDescription->getColumn(); return [$table, $column]; }
php
protected static function mapToDatabase($type, $valueName) { $mapper = self::getMapper($type); if ($mapper->hasAttribute($valueName)) { $attributeDescription = $mapper->getAttribute($valueName); } else { // if the attribute does not exist, it might be the column name already foreach ($mapper->getAttributes() as $curAttributeDesc) { if ($curAttributeDesc->getColumn() == $valueName) { $attributeDescription = $curAttributeDesc; break; } } } if (!$attributeDescription) { throw new PersistenceException("No attribute '".$valueName."' exists in '".$type."'"); } $table = $mapper->getRealTableName(); $column = $attributeDescription->getColumn(); return [$table, $column]; }
[ "protected", "static", "function", "mapToDatabase", "(", "$", "type", ",", "$", "valueName", ")", "{", "$", "mapper", "=", "self", "::", "getMapper", "(", "$", "type", ")", ";", "if", "(", "$", "mapper", "->", "hasAttribute", "(", "$", "valueName", ")"...
Map a application type and value name to the appropriate database names @param $type The type to map @param $valueName The name of the value to map @return An array with the table and column name or null if no mapper is found
[ "Map", "a", "application", "type", "and", "value", "name", "to", "the", "appropriate", "database", "names" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/StringQuery.php#L272-L293
train
GW2Treasures/gw2api
src/V2/ApiHandler.php
ApiHandler.getResponseAsJson
protected function getResponseAsJson( ResponseInterface $response ) { if( $response->hasHeader('Content-Type') ) { $typeHeader = $response->getHeader('Content-Type'); $contentType = array_shift($typeHeader); if( stripos( $contentType, 'application/json' ) === 0 ) { return json_decode($response->getBody(), false); } } return null; }
php
protected function getResponseAsJson( ResponseInterface $response ) { if( $response->hasHeader('Content-Type') ) { $typeHeader = $response->getHeader('Content-Type'); $contentType = array_shift($typeHeader); if( stripos( $contentType, 'application/json' ) === 0 ) { return json_decode($response->getBody(), false); } } return null; }
[ "protected", "function", "getResponseAsJson", "(", "ResponseInterface", "$", "response", ")", "{", "if", "(", "$", "response", "->", "hasHeader", "(", "'Content-Type'", ")", ")", "{", "$", "typeHeader", "=", "$", "response", "->", "getHeader", "(", "'Content-T...
Returns the json object if the response contains valid json, otherwise null. @param ResponseInterface $response @return mixed|null
[ "Returns", "the", "json", "object", "if", "the", "response", "contains", "valid", "json", "otherwise", "null", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/ApiHandler.php#L32-L43
train
iherwig/wcmf
src/wcmf/application/controller/XMLExportController.php
XMLExportController.exportNodes
protected function exportNodes($oids) { // Export starts from root oids and iterates over all children. // On every call we have to decide what to do: // - If there is an iterator stored in the session we are inside a tree and continue iterating (_NODES_PER_CALL nodes) // until the iterator finishes // - If the oids array holds one value!=null this is assumed to be an root oid and a new iterator is constructed // - If there is no iterator and no oid given, we return $session = $this->getSession(); $persistenceFacade = $this->getPersistenceFacade(); $message = $this->getMessage(); // get document definition $docFile = $this->getDownloadFile(); $nodesPerCall = $this->getRequestValue('nodesPerCall'); $cacheSection = $this->getRequestValue('cacheSection'); // check for iterator in session $iterator = PersistentIterator::load($this->ITERATOR_ID_VAR, $persistenceFacade, $session); // no iterator but oid given, start with new root oid if ($iterator == null && sizeof($oids) > 0 && $oids[0] != null) { $iterator = new PersistentIterator($this->ITERATOR_ID_VAR, $persistenceFacade, $session, $oids[0]); } // no iterator, no oid, finish if ($iterator == null) { $this->addWorkPackage($message->getText('Finish'), 1, [null], 'finishExport'); return; } // process nodes $fileHandle = fopen($docFile, "a"); $counter = 0; while ($iterator->valid() && $counter < $nodesPerCall) { // write node $this->writeNode($fileHandle, $iterator->current(), $iterator->key()+1); $iterator->next(); $counter++; } $this->endTags($fileHandle, 0); fclose($fileHandle); // decide what to do next $rootOIDs = $this->cache->get($cacheSection, self::CACHE_KEY_ROOT_OIDS); if (!$iterator->valid() && sizeof($rootOIDs) > 0) { // if the current iterator is finished, reset the iterator and proceed with the next root oid $nextOID = array_shift($rootOIDs); // store remaining root oids in the cache $this->cache->put($cacheSection, self::CACHE_KEY_ROOT_OIDS, $rootOIDs); // delete iterator to start with new root oid PersistentIterator::reset($this->ITERATOR_ID_VAR, $session); $name = $message->getText('Exporting tree: start with %0%', [$nextOID]); $this->addWorkPackage($name, 1, [$nextOID], 'exportNodes'); } elseif ($iterator->valid()) { // proceed with current iterator $iterator->save(); $name = $message->getText('Exporting tree: continue with %0%', [$iterator->current()]); $this->addWorkPackage($name, 1, [null], 'exportNodes'); } else { // finish $this->addWorkPackage($message->getText('Finish'), 1, [null], 'finishExport'); } }
php
protected function exportNodes($oids) { // Export starts from root oids and iterates over all children. // On every call we have to decide what to do: // - If there is an iterator stored in the session we are inside a tree and continue iterating (_NODES_PER_CALL nodes) // until the iterator finishes // - If the oids array holds one value!=null this is assumed to be an root oid and a new iterator is constructed // - If there is no iterator and no oid given, we return $session = $this->getSession(); $persistenceFacade = $this->getPersistenceFacade(); $message = $this->getMessage(); // get document definition $docFile = $this->getDownloadFile(); $nodesPerCall = $this->getRequestValue('nodesPerCall'); $cacheSection = $this->getRequestValue('cacheSection'); // check for iterator in session $iterator = PersistentIterator::load($this->ITERATOR_ID_VAR, $persistenceFacade, $session); // no iterator but oid given, start with new root oid if ($iterator == null && sizeof($oids) > 0 && $oids[0] != null) { $iterator = new PersistentIterator($this->ITERATOR_ID_VAR, $persistenceFacade, $session, $oids[0]); } // no iterator, no oid, finish if ($iterator == null) { $this->addWorkPackage($message->getText('Finish'), 1, [null], 'finishExport'); return; } // process nodes $fileHandle = fopen($docFile, "a"); $counter = 0; while ($iterator->valid() && $counter < $nodesPerCall) { // write node $this->writeNode($fileHandle, $iterator->current(), $iterator->key()+1); $iterator->next(); $counter++; } $this->endTags($fileHandle, 0); fclose($fileHandle); // decide what to do next $rootOIDs = $this->cache->get($cacheSection, self::CACHE_KEY_ROOT_OIDS); if (!$iterator->valid() && sizeof($rootOIDs) > 0) { // if the current iterator is finished, reset the iterator and proceed with the next root oid $nextOID = array_shift($rootOIDs); // store remaining root oids in the cache $this->cache->put($cacheSection, self::CACHE_KEY_ROOT_OIDS, $rootOIDs); // delete iterator to start with new root oid PersistentIterator::reset($this->ITERATOR_ID_VAR, $session); $name = $message->getText('Exporting tree: start with %0%', [$nextOID]); $this->addWorkPackage($name, 1, [$nextOID], 'exportNodes'); } elseif ($iterator->valid()) { // proceed with current iterator $iterator->save(); $name = $message->getText('Exporting tree: continue with %0%', [$iterator->current()]); $this->addWorkPackage($name, 1, [null], 'exportNodes'); } else { // finish $this->addWorkPackage($message->getText('Finish'), 1, [null], 'finishExport'); } }
[ "protected", "function", "exportNodes", "(", "$", "oids", ")", "{", "// Export starts from root oids and iterates over all children.", "// On every call we have to decide what to do:", "// - If there is an iterator stored in the session we are inside a tree and continue iterating (_NODES_PER_CAL...
Serialize all Nodes with given object ids to XML @param $oids The object ids to process @note This is a callback method called on a matching work package, see BatchController::addWorkPackage()
[ "Serialize", "all", "Nodes", "with", "given", "object", "ids", "to", "XML" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/XMLExportController.php#L230-L295
train
iherwig/wcmf
src/wcmf/application/controller/XMLExportController.php
XMLExportController.writeNode
protected function writeNode($fileHandle, ObjectId $oid, $depth) { $persistenceFacade = $this->getPersistenceFacade(); // get document definition $docIndent = $this->getRequestValue('docIndent'); $docLinebreak = $this->getRequestValue('docLinebreak'); $cacheSection = $this->getRequestValue('cacheSection'); // get document state from cache $lastIndent = $this->cache->get($cacheSection, self::CACHE_KEY_LAST_INDENT); $tagsToClose = $this->cache->get($cacheSection, self::CACHE_KEY_TAGS_TO_CLOSE); // load node and get element name $node = $persistenceFacade->load($oid); $elementName = $persistenceFacade->getSimpleType($node->getType()); // check if the node is written already $exportedOids = $this->cache->get($cacheSection, self::CACHE_KEY_EXPORTED_OIDS); if (!in_array($oid->__toString(), $exportedOids)) { // write node $mapper = $node->getMapper(); $hasUnvisitedChildren = $this->getNumUnvisitedChildren($node) > 0; $curIndent = $depth; $this->endTags($fileHandle, $curIndent); // write object's content // open start tag $this->fileUtil->fputsUnicode($fileHandle, str_repeat($docIndent, $curIndent).'<'.$elementName); // write object attributes $attributes = $mapper->getAttributes(); foreach ($attributes as $curAttribute) { $attributeName = $curAttribute->getName(); $value = $node->getValue($attributeName); $this->fileUtil->fputsUnicode($fileHandle, ' '.$attributeName.'="'.$this->formatValue($value).'"'); } // close start tag $this->fileUtil->fputsUnicode($fileHandle, '>'); if ($hasUnvisitedChildren) { $this->fileUtil->fputsUnicode($fileHandle, $docLinebreak); } // remember end tag if not closed if ($hasUnvisitedChildren) { $closeTag = ["name" => $elementName, "indent" => $curIndent]; array_unshift($tagsToClose, $closeTag); } else { $this->fileUtil->fputsUnicode($fileHandle, '</'.$elementName.'>'.$docLinebreak); } // remember current indent $lastIndent = $curIndent; // register exported node $exportedOids[] = $oid->__toString(); $this->cache->put($cacheSection, self::CACHE_KEY_EXPORTED_OIDS, $exportedOids); } // update document state in cache $this->cache->put($cacheSection, self::CACHE_KEY_LAST_INDENT, $lastIndent); $this->cache->put($cacheSection, self::CACHE_KEY_TAGS_TO_CLOSE, $tagsToClose); }
php
protected function writeNode($fileHandle, ObjectId $oid, $depth) { $persistenceFacade = $this->getPersistenceFacade(); // get document definition $docIndent = $this->getRequestValue('docIndent'); $docLinebreak = $this->getRequestValue('docLinebreak'); $cacheSection = $this->getRequestValue('cacheSection'); // get document state from cache $lastIndent = $this->cache->get($cacheSection, self::CACHE_KEY_LAST_INDENT); $tagsToClose = $this->cache->get($cacheSection, self::CACHE_KEY_TAGS_TO_CLOSE); // load node and get element name $node = $persistenceFacade->load($oid); $elementName = $persistenceFacade->getSimpleType($node->getType()); // check if the node is written already $exportedOids = $this->cache->get($cacheSection, self::CACHE_KEY_EXPORTED_OIDS); if (!in_array($oid->__toString(), $exportedOids)) { // write node $mapper = $node->getMapper(); $hasUnvisitedChildren = $this->getNumUnvisitedChildren($node) > 0; $curIndent = $depth; $this->endTags($fileHandle, $curIndent); // write object's content // open start tag $this->fileUtil->fputsUnicode($fileHandle, str_repeat($docIndent, $curIndent).'<'.$elementName); // write object attributes $attributes = $mapper->getAttributes(); foreach ($attributes as $curAttribute) { $attributeName = $curAttribute->getName(); $value = $node->getValue($attributeName); $this->fileUtil->fputsUnicode($fileHandle, ' '.$attributeName.'="'.$this->formatValue($value).'"'); } // close start tag $this->fileUtil->fputsUnicode($fileHandle, '>'); if ($hasUnvisitedChildren) { $this->fileUtil->fputsUnicode($fileHandle, $docLinebreak); } // remember end tag if not closed if ($hasUnvisitedChildren) { $closeTag = ["name" => $elementName, "indent" => $curIndent]; array_unshift($tagsToClose, $closeTag); } else { $this->fileUtil->fputsUnicode($fileHandle, '</'.$elementName.'>'.$docLinebreak); } // remember current indent $lastIndent = $curIndent; // register exported node $exportedOids[] = $oid->__toString(); $this->cache->put($cacheSection, self::CACHE_KEY_EXPORTED_OIDS, $exportedOids); } // update document state in cache $this->cache->put($cacheSection, self::CACHE_KEY_LAST_INDENT, $lastIndent); $this->cache->put($cacheSection, self::CACHE_KEY_TAGS_TO_CLOSE, $tagsToClose); }
[ "protected", "function", "writeNode", "(", "$", "fileHandle", ",", "ObjectId", "$", "oid", ",", "$", "depth", ")", "{", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "// get document definition", "$", "docIndent", "="...
Serialize a Node to XML @param $fileHandle The file handle to write to @param $oid The object id of the node @param $depth The depth of the node in the tree
[ "Serialize", "a", "Node", "to", "XML" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/XMLExportController.php#L356-L418
train
iherwig/wcmf
src/wcmf/application/controller/XMLExportController.php
XMLExportController.getNumUnvisitedChildren
protected function getNumUnvisitedChildren(Node $node) { $cacheSection = $this->getRequestValue('cacheSection'); $exportedOids = $this->cache->get($cacheSection, self::CACHE_KEY_EXPORTED_OIDS); $childOIDs = []; $mapper = $node->getMapper(); $relations = $mapper->getRelations('child'); foreach ($relations as $relation) { if ($relation->getOtherNavigability()) { $childValue = $node->getValue($relation->getOtherRole()); if ($childValue != null) { $children = $relation->isMultiValued() ? $childValue : [$childValue]; foreach ($children as $child) { $childOIDs[] = $child->getOID(); } } } } $numUnvisitedChildren = 0; foreach ($childOIDs as $childOid) { if (!in_array($childOid->__toString(), $exportedOids)) { $numUnvisitedChildren++; } } return $numUnvisitedChildren; }
php
protected function getNumUnvisitedChildren(Node $node) { $cacheSection = $this->getRequestValue('cacheSection'); $exportedOids = $this->cache->get($cacheSection, self::CACHE_KEY_EXPORTED_OIDS); $childOIDs = []; $mapper = $node->getMapper(); $relations = $mapper->getRelations('child'); foreach ($relations as $relation) { if ($relation->getOtherNavigability()) { $childValue = $node->getValue($relation->getOtherRole()); if ($childValue != null) { $children = $relation->isMultiValued() ? $childValue : [$childValue]; foreach ($children as $child) { $childOIDs[] = $child->getOID(); } } } } $numUnvisitedChildren = 0; foreach ($childOIDs as $childOid) { if (!in_array($childOid->__toString(), $exportedOids)) { $numUnvisitedChildren++; } } return $numUnvisitedChildren; }
[ "protected", "function", "getNumUnvisitedChildren", "(", "Node", "$", "node", ")", "{", "$", "cacheSection", "=", "$", "this", "->", "getRequestValue", "(", "'cacheSection'", ")", ";", "$", "exportedOids", "=", "$", "this", "->", "cache", "->", "get", "(", ...
Get number of children of the given node, that were not visited yet @param $node @return Integer
[ "Get", "number", "of", "children", "of", "the", "given", "node", "that", "were", "not", "visited", "yet" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/XMLExportController.php#L425-L450
train
iherwig/wcmf
src/wcmf/lib/presentation/format/impl/CacheTrait.php
CacheTrait.putInCache
protected function putInCache(Response $response, $payload) { $this->getCache()->put($this->getCacheSection($response), $response->getCacheId(), $payload, $response->getCacheLifetime()); }
php
protected function putInCache(Response $response, $payload) { $this->getCache()->put($this->getCacheSection($response), $response->getCacheId(), $payload, $response->getCacheLifetime()); }
[ "protected", "function", "putInCache", "(", "Response", "$", "response", ",", "$", "payload", ")", "{", "$", "this", "->", "getCache", "(", ")", "->", "put", "(", "$", "this", "->", "getCacheSection", "(", "$", "response", ")", ",", "$", "response", "-...
Store the payload of the response in the cache. @param $response @param $payload String
[ "Store", "the", "payload", "of", "the", "response", "in", "the", "cache", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/CacheTrait.php#L78-L80
train
iherwig/wcmf
src/wcmf/lib/presentation/format/impl/CacheTrait.php
CacheTrait.getFromCache
protected function getFromCache(Response $response) { return $this->getCache()->get($this->getCacheSection($response), $response->getCacheId()); }
php
protected function getFromCache(Response $response) { return $this->getCache()->get($this->getCacheSection($response), $response->getCacheId()); }
[ "protected", "function", "getFromCache", "(", "Response", "$", "response", ")", "{", "return", "$", "this", "->", "getCache", "(", ")", "->", "get", "(", "$", "this", "->", "getCacheSection", "(", "$", "response", ")", ",", "$", "response", "->", "getCac...
Load the payload of the response from the cache. @param $response @return String
[ "Load", "the", "payload", "of", "the", "response", "from", "the", "cache", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/format/impl/CacheTrait.php#L87-L89
train
iherwig/wcmf
src/wcmf/lib/service/impl/RPCClient.php
RPCClient.setSessionId
protected function setSessionId($sessionId) { $session = ObjectFactory::getInstance('session'); $sids = $session->get(self::SIDS_SESSION_VARNAME); $sids[$this->serverCli] = $sessionId; $session->set(self::SIDS_SESSION_VARNAME, $sids); }
php
protected function setSessionId($sessionId) { $session = ObjectFactory::getInstance('session'); $sids = $session->get(self::SIDS_SESSION_VARNAME); $sids[$this->serverCli] = $sessionId; $session->set(self::SIDS_SESSION_VARNAME, $sids); }
[ "protected", "function", "setSessionId", "(", "$", "sessionId", ")", "{", "$", "session", "=", "ObjectFactory", "::", "getInstance", "(", "'session'", ")", ";", "$", "sids", "=", "$", "session", "->", "get", "(", "self", "::", "SIDS_SESSION_VARNAME", ")", ...
Store the session id for our server in the local session @return The session id or null
[ "Store", "the", "session", "id", "for", "our", "server", "in", "the", "local", "session" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/impl/RPCClient.php#L164-L169
train
iherwig/wcmf
src/wcmf/lib/service/impl/RPCClient.php
RPCClient.getSessionId
protected function getSessionId() { // check if we already have a session with the server $session = ObjectFactory::getInstance('session'); $sids = $session->get(self::SIDS_SESSION_VARNAME); if (isset($sids[$this->serverCli])) { return $sids[$this->serverCli]; } return null; }
php
protected function getSessionId() { // check if we already have a session with the server $session = ObjectFactory::getInstance('session'); $sids = $session->get(self::SIDS_SESSION_VARNAME); if (isset($sids[$this->serverCli])) { return $sids[$this->serverCli]; } return null; }
[ "protected", "function", "getSessionId", "(", ")", "{", "// check if we already have a session with the server", "$", "session", "=", "ObjectFactory", "::", "getInstance", "(", "'session'", ")", ";", "$", "sids", "=", "$", "session", "->", "get", "(", "self", "::"...
Get the session id for our server from the local session @return The session id or null
[ "Get", "the", "session", "id", "for", "our", "server", "from", "the", "local", "session" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/service/impl/RPCClient.php#L175-L183
train
thelfensdrfer/yii2sshconsole
src/Controller.php
Controller.connect
public function connect($host, $auth, $port = 22, $timeout = 10) { $this->ssh = new SSH2($host, $port, $timeout); if (!isset($auth['key']) && isset($auth['username'])) { // Login via username/password $username = $auth['username']; $password = isset($auth['password']) ? $auth['password'] : ''; if (!$this->ssh->login($username, $password)) throw new LoginFailedException(Yii::t( 'Yii2SshConsole', 'Login failed for user {username} using password {answer}!', [ 'username' => $username, 'answer' => !empty($password) ? 1 : 0 ] )); else return true; } elseif (isset($auth['key']) and isset($auth['username'])) { // Login via private key $username = $auth['username']; $password = isset($auth['key_password']) ? $auth['key_password'] : ''; $key = new RSA; if (!empty($password)) { $key->setPassword($password); } $key->loadKey(file_get_contents($auth['key'])); if (!$this->ssh->login($username, $key)) throw new LoginFailedException(Yii::t( 'Yii2SshConsole', 'Login failed for user {username} using key with password {answer}!', [ 'username' => $username, 'answer' => !empty($password) ? 1 : 0 ] )); else return true; } else { // No username given throw new LoginUnknownException(Yii::t( 'Yii2SshConsole', 'No username given!' )); } return false; }
php
public function connect($host, $auth, $port = 22, $timeout = 10) { $this->ssh = new SSH2($host, $port, $timeout); if (!isset($auth['key']) && isset($auth['username'])) { // Login via username/password $username = $auth['username']; $password = isset($auth['password']) ? $auth['password'] : ''; if (!$this->ssh->login($username, $password)) throw new LoginFailedException(Yii::t( 'Yii2SshConsole', 'Login failed for user {username} using password {answer}!', [ 'username' => $username, 'answer' => !empty($password) ? 1 : 0 ] )); else return true; } elseif (isset($auth['key']) and isset($auth['username'])) { // Login via private key $username = $auth['username']; $password = isset($auth['key_password']) ? $auth['key_password'] : ''; $key = new RSA; if (!empty($password)) { $key->setPassword($password); } $key->loadKey(file_get_contents($auth['key'])); if (!$this->ssh->login($username, $key)) throw new LoginFailedException(Yii::t( 'Yii2SshConsole', 'Login failed for user {username} using key with password {answer}!', [ 'username' => $username, 'answer' => !empty($password) ? 1 : 0 ] )); else return true; } else { // No username given throw new LoginUnknownException(Yii::t( 'Yii2SshConsole', 'No username given!' )); } return false; }
[ "public", "function", "connect", "(", "$", "host", ",", "$", "auth", ",", "$", "port", "=", "22", ",", "$", "timeout", "=", "10", ")", "{", "$", "this", "->", "ssh", "=", "new", "SSH2", "(", "$", "host", ",", "$", "port", ",", "$", "timeout", ...
Connect to the ssh server. @param string $host @param array $auth Login via username/password [ 'username' => 'myname', 'password' => 'mypassword', // can be empty ] or via private key [ 'key' => '/path/to/private.key', 'password' => 'mykeypassword', // can be empty ] @param integer $port Default 22 @param integer $timeout Default 10 seconds @throws \yii2sshconsole\LoginFailedException If the login failes @throws \yii2sshconsole\LoginUnknownException If no username is set @return bool
[ "Connect", "to", "the", "ssh", "server", "." ]
7699c4cd0cddacd07a2236ca10f06ec384b2aa54
https://github.com/thelfensdrfer/yii2sshconsole/blob/7699c4cd0cddacd07a2236ca10f06ec384b2aa54/src/Controller.php#L43-L97
train
thelfensdrfer/yii2sshconsole
src/Controller.php
Controller.readLine
public function readLine() { $output = $this->ssh->_get_channel_packet(SSH2::CHANNEL_EXEC); return $output === true ? null : $output; }
php
public function readLine() { $output = $this->ssh->_get_channel_packet(SSH2::CHANNEL_EXEC); return $output === true ? null : $output; }
[ "public", "function", "readLine", "(", ")", "{", "$", "output", "=", "$", "this", "->", "ssh", "->", "_get_channel_packet", "(", "SSH2", "::", "CHANNEL_EXEC", ")", ";", "return", "$", "output", "===", "true", "?", "null", ":", "$", "output", ";", "}" ]
Read the next line from the SSH session. @return string|null
[ "Read", "the", "next", "line", "from", "the", "SSH", "session", "." ]
7699c4cd0cddacd07a2236ca10f06ec384b2aa54
https://github.com/thelfensdrfer/yii2sshconsole/blob/7699c4cd0cddacd07a2236ca10f06ec384b2aa54/src/Controller.php#L104-L109
train
thelfensdrfer/yii2sshconsole
src/Controller.php
Controller.run
public function run($commands, $callback = null) { if (!$this->ssh->isConnected()) throw new NotConnectedException(); if (is_array($commands)) $commands = implode(' && ', $commands); if ($callback === null) $output = ''; $this->ssh->exec($commands, false); while (true) { if (is_null($line = $this->readLine())) break; if ($callback === null) $output .= $line; else call_user_func($callback, $line, $this); } if ($callback === null) return $output; else return null; }
php
public function run($commands, $callback = null) { if (!$this->ssh->isConnected()) throw new NotConnectedException(); if (is_array($commands)) $commands = implode(' && ', $commands); if ($callback === null) $output = ''; $this->ssh->exec($commands, false); while (true) { if (is_null($line = $this->readLine())) break; if ($callback === null) $output .= $line; else call_user_func($callback, $line, $this); } if ($callback === null) return $output; else return null; }
[ "public", "function", "run", "(", "$", "commands", ",", "$", "callback", "=", "null", ")", "{", "if", "(", "!", "$", "this", "->", "ssh", "->", "isConnected", "(", ")", ")", "throw", "new", "NotConnectedException", "(", ")", ";", "if", "(", "is_array...
Run a ssh command for the current connection. @param string|array $commands @param callable $callback @throws NotConnectedException If the client is not connected to the server @return string|null
[ "Run", "a", "ssh", "command", "for", "the", "current", "connection", "." ]
7699c4cd0cddacd07a2236ca10f06ec384b2aa54
https://github.com/thelfensdrfer/yii2sshconsole/blob/7699c4cd0cddacd07a2236ca10f06ec384b2aa54/src/Controller.php#L121-L147
train
pr-of-it/t4
framework/Dbal/Query.php
Query.insert
public function insert($tables = null) { if (null !== $tables) { $this->tables($tables); } $this->action = 'insert'; return $this; }
php
public function insert($tables = null) { if (null !== $tables) { $this->tables($tables); } $this->action = 'insert'; return $this; }
[ "public", "function", "insert", "(", "$", "tables", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "tables", ")", "{", "$", "this", "->", "tables", "(", "$", "tables", ")", ";", "}", "$", "this", "->", "action", "=", "'insert'", ";", "retu...
Set all tables and set action to insert @param mixed $tables @return $this
[ "Set", "all", "tables", "and", "set", "action", "to", "insert" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L168-L175
train
pr-of-it/t4
framework/Dbal/Query.php
Query.update
public function update($tables = null) { if (null !== $tables) { $this->tables($tables); } $this->action = 'update'; return $this; }
php
public function update($tables = null) { if (null !== $tables) { $this->tables($tables); } $this->action = 'update'; return $this; }
[ "public", "function", "update", "(", "$", "tables", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "tables", ")", "{", "$", "this", "->", "tables", "(", "$", "tables", ")", ";", "}", "$", "this", "->", "action", "=", "'update'", ";", "retu...
Set all tables and set action to update @param mixed $tables @return $this
[ "Set", "all", "tables", "and", "set", "action", "to", "update" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L182-L189
train
pr-of-it/t4
framework/Dbal/Query.php
Query.delete
public function delete($tables = null) { if (null !== $tables) { $this->tables($tables); } $this->action = 'delete'; return $this; }
php
public function delete($tables = null) { if (null !== $tables) { $this->tables($tables); } $this->action = 'delete'; return $this; }
[ "public", "function", "delete", "(", "$", "tables", "=", "null", ")", "{", "if", "(", "null", "!==", "$", "tables", ")", "{", "$", "this", "->", "tables", "(", "$", "tables", ")", ";", "}", "$", "this", "->", "action", "=", "'delete'", ";", "retu...
Set all tables and set action to delete @param mixed $tables @return $this
[ "Set", "all", "tables", "and", "set", "action", "to", "delete" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L196-L203
train
pr-of-it/t4
framework/Dbal/Query.php
Query.table
public function table($table = []) { $tables = $this->prepareNames(func_get_args()); $this->tables = array_merge($this->tables ?: [], $tables); return $this; }
php
public function table($table = []) { $tables = $this->prepareNames(func_get_args()); $this->tables = array_merge($this->tables ?: [], $tables); return $this; }
[ "public", "function", "table", "(", "$", "table", "=", "[", "]", ")", "{", "$", "tables", "=", "$", "this", "->", "prepareNames", "(", "func_get_args", "(", ")", ")", ";", "$", "this", "->", "tables", "=", "array_merge", "(", "$", "this", "->", "ta...
Add one table to query @param mixed $table @return $this
[ "Add", "one", "table", "to", "query" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L210-L215
train
pr-of-it/t4
framework/Dbal/Query.php
Query.column
public function column($column = '*') { if ('*' == $column) { $this->columns = ['*']; } else { $columns = $this->prepareNames(func_get_args()); $this->columns = array_merge( empty($this->columns) || ['*'] == $this->columns ? [] : $this->columns, array_values(array_diff($columns, ['*'])) ); } return $this; }
php
public function column($column = '*') { if ('*' == $column) { $this->columns = ['*']; } else { $columns = $this->prepareNames(func_get_args()); $this->columns = array_merge( empty($this->columns) || ['*'] == $this->columns ? [] : $this->columns, array_values(array_diff($columns, ['*'])) ); } return $this; }
[ "public", "function", "column", "(", "$", "column", "=", "'*'", ")", "{", "if", "(", "'*'", "==", "$", "column", ")", "{", "$", "this", "->", "columns", "=", "[", "'*'", "]", ";", "}", "else", "{", "$", "columns", "=", "$", "this", "->", "prepa...
Add one column name to query @param mixed $column @return $this
[ "Add", "one", "column", "name", "to", "query" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L234-L246
train
pr-of-it/t4
framework/Dbal/Query.php
Query.columns
public function columns($columns = '*') { if ('*' == $columns) { $this->columns = ['*']; } else { $columns = $this->prepareNames(func_get_args()); $this->columns = array_values(array_diff($columns, ['*'])); } return $this; }
php
public function columns($columns = '*') { if ('*' == $columns) { $this->columns = ['*']; } else { $columns = $this->prepareNames(func_get_args()); $this->columns = array_values(array_diff($columns, ['*'])); } return $this; }
[ "public", "function", "columns", "(", "$", "columns", "=", "'*'", ")", "{", "if", "(", "'*'", "==", "$", "columns", ")", "{", "$", "this", "->", "columns", "=", "[", "'*'", "]", ";", "}", "else", "{", "$", "columns", "=", "$", "this", "->", "pr...
Set all query's columns @param mixed $columns @return $this
[ "Set", "all", "query", "s", "columns" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L253-L262
train
pr-of-it/t4
framework/Dbal/Query.php
Query.join
public function join($table, $on, $type = 'full', $alias = '') { if (!isset($this->joins)) { $this->joins = []; } $join = [ 'table' => $this->trimName($table), 'on' => $on, 'type' => $type, ]; if (!empty($alias)) { $join['alias'] = $this->trimName($alias); } $this->joins = array_merge($this->joins, [$join]); return $this; }
php
public function join($table, $on, $type = 'full', $alias = '') { if (!isset($this->joins)) { $this->joins = []; } $join = [ 'table' => $this->trimName($table), 'on' => $on, 'type' => $type, ]; if (!empty($alias)) { $join['alias'] = $this->trimName($alias); } $this->joins = array_merge($this->joins, [$join]); return $this; }
[ "public", "function", "join", "(", "$", "table", ",", "$", "on", ",", "$", "type", "=", "'full'", ",", "$", "alias", "=", "''", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "joins", ")", ")", "{", "$", "this", "->", "joins", "="...
Add one join statement to query @param string $table @param string $on @param string $type @param string $alias @return $this
[ "Add", "one", "join", "statement", "to", "query" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L272-L287
train
pr-of-it/t4
framework/Dbal/Query.php
Query.joins
public function joins($joins) { $this->joins = []; foreach ($joins as $join) { $j = [ 'table' => $this->trimName($join['table']), 'on' => $join['on'], 'type' => $join['type'], ]; if (!empty($alias)) { $j['alias'] = $this->trimName($join['alias']); } $this->joins = array_merge($this->joins, [$join]); } return $this; }
php
public function joins($joins) { $this->joins = []; foreach ($joins as $join) { $j = [ 'table' => $this->trimName($join['table']), 'on' => $join['on'], 'type' => $join['type'], ]; if (!empty($alias)) { $j['alias'] = $this->trimName($join['alias']); } $this->joins = array_merge($this->joins, [$join]); } return $this; }
[ "public", "function", "joins", "(", "$", "joins", ")", "{", "$", "this", "->", "joins", "=", "[", "]", ";", "foreach", "(", "$", "joins", "as", "$", "join", ")", "{", "$", "j", "=", "[", "'table'", "=>", "$", "this", "->", "trimName", "(", "$",...
Set all query's joins @param array $joins @return $this
[ "Set", "all", "query", "s", "joins" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L294-L309
train
pr-of-it/t4
framework/Dbal/Query.php
Query.group
public function group($group) { $group = $this->prepareNames(func_get_args(), false); $this->group = $group; return $this; }
php
public function group($group) { $group = $this->prepareNames(func_get_args(), false); $this->group = $group; return $this; }
[ "public", "function", "group", "(", "$", "group", ")", "{", "$", "group", "=", "$", "this", "->", "prepareNames", "(", "func_get_args", "(", ")", ",", "false", ")", ";", "$", "this", "->", "group", "=", "$", "group", ";", "return", "$", "this", ";"...
Sets group values @param string $group @return $this
[ "Sets", "group", "values" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L327-L332
train
pr-of-it/t4
framework/Dbal/Query.php
Query.order
public function order($order) { $order = $this->prepareNames(func_get_args(),false); $this->order = $order; return $this; }
php
public function order($order) { $order = $this->prepareNames(func_get_args(),false); $this->order = $order; return $this; }
[ "public", "function", "order", "(", "$", "order", ")", "{", "$", "order", "=", "$", "this", "->", "prepareNames", "(", "func_get_args", "(", ")", ",", "false", ")", ";", "$", "this", "->", "order", "=", "$", "order", ";", "return", "$", "this", ";"...
Sets order directions @param string $order @return $this
[ "Sets", "order", "directions" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L350-L355
train
pr-of-it/t4
framework/Dbal/Query.php
Query.value
public function value($key, $value) { $this->values = array_merge($this->values ?? [], [$this->trimName($key) => $value]); return $this; }
php
public function value($key, $value) { $this->values = array_merge($this->values ?? [], [$this->trimName($key) => $value]); return $this; }
[ "public", "function", "value", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "values", "=", "array_merge", "(", "$", "this", "->", "values", "??", "[", "]", ",", "[", "$", "this", "->", "trimName", "(", "$", "key", ")", "=>", ...
Add one query's value for insert @param string $key @param mixed $value @return $this
[ "Add", "one", "query", "s", "value", "for", "insert" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L385-L389
train
pr-of-it/t4
framework/Dbal/Query.php
Query.values
public function values(array $values = []) { $values = array_combine(array_map([$this, 'trimName'], array_keys($values)), array_values($values)); $this->values = $values; return $this; }
php
public function values(array $values = []) { $values = array_combine(array_map([$this, 'trimName'], array_keys($values)), array_values($values)); $this->values = $values; return $this; }
[ "public", "function", "values", "(", "array", "$", "values", "=", "[", "]", ")", "{", "$", "values", "=", "array_combine", "(", "array_map", "(", "[", "$", "this", ",", "'trimName'", "]", ",", "array_keys", "(", "$", "values", ")", ")", ",", "array_v...
Sets all query's values for insert @param array $values @return $this
[ "Sets", "all", "query", "s", "values", "for", "insert" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L396-L401
train
pr-of-it/t4
framework/Dbal/Query.php
Query.param
public function param($key, $value) { $this->params = array_merge($this->params ?? [], [$key => $value]); return $this; }
php
public function param($key, $value) { $this->params = array_merge($this->params ?? [], [$key => $value]); return $this; }
[ "public", "function", "param", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "params", "=", "array_merge", "(", "$", "this", "->", "params", "??", "[", "]", ",", "[", "$", "key", "=>", "$", "value", "]", ")", ";", "return", "...
Sets one bind parameter @param string $key @param mixed $value @return $this
[ "Sets", "one", "bind", "parameter" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Dbal/Query.php#L409-L413
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Core/AccessControlConfig.php
CKFinder_Connector_Core_AccessControlConfig.addACLEntry
private function addACLEntry($role, $resourceType, $folderPath, $allowRulesMask, $denyRulesMask) { if (!strlen($folderPath)) { $folderPath = '/'; } else { if (substr($folderPath,0,1) != '/') { $folderPath = '/' . $folderPath; } if (substr($folderPath,-1,1) != '/') { $folderPath .= '/'; } } $_entryKey = $role . "#@#" . $resourceType; if (array_key_exists($folderPath,$this->_aclEntries)) { if (array_key_exists($_entryKey, $this->_aclEntries[$folderPath])) { $_rulesMasks = $this->_aclEntries[$folderPath][$_entryKey]; foreach ($_rulesMasks[0] as $key => $value) { $allowRulesMask[$key] |= $value; } foreach ($_rulesMasks[1] as $key => $value) { $denyRulesMask[$key] |= $value; } } } else { $this->_aclEntries[$folderPath] = array(); } $this->_aclEntries[$folderPath][$_entryKey] = array($allowRulesMask, $denyRulesMask); }
php
private function addACLEntry($role, $resourceType, $folderPath, $allowRulesMask, $denyRulesMask) { if (!strlen($folderPath)) { $folderPath = '/'; } else { if (substr($folderPath,0,1) != '/') { $folderPath = '/' . $folderPath; } if (substr($folderPath,-1,1) != '/') { $folderPath .= '/'; } } $_entryKey = $role . "#@#" . $resourceType; if (array_key_exists($folderPath,$this->_aclEntries)) { if (array_key_exists($_entryKey, $this->_aclEntries[$folderPath])) { $_rulesMasks = $this->_aclEntries[$folderPath][$_entryKey]; foreach ($_rulesMasks[0] as $key => $value) { $allowRulesMask[$key] |= $value; } foreach ($_rulesMasks[1] as $key => $value) { $denyRulesMask[$key] |= $value; } } } else { $this->_aclEntries[$folderPath] = array(); } $this->_aclEntries[$folderPath][$_entryKey] = array($allowRulesMask, $denyRulesMask); }
[ "private", "function", "addACLEntry", "(", "$", "role", ",", "$", "resourceType", ",", "$", "folderPath", ",", "$", "allowRulesMask", ",", "$", "denyRulesMask", ")", "{", "if", "(", "!", "strlen", "(", "$", "folderPath", ")", ")", "{", "$", "folderPath",...
Add ACL entry @param string $role role @param string $resourceType resource type @param string $folderPath folder path @param int $allowRulesMask allow rules mask @param int $denyRulesMask deny rules mask @access private
[ "Add", "ACL", "entry" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Core/AccessControlConfig.php#L102-L136
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Core/AccessControlConfig.php
CKFinder_Connector_Core_AccessControlConfig.getComputedMask
public function getComputedMask($resourceType, $folderPath) { $_computedMask = 0; $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $_roleSessionVar = $_config->getRoleSessionVar(); $_userRole = null; if (strlen($_roleSessionVar) && isset($_SESSION[$_roleSessionVar])) { $_userRole = (string)$_SESSION[$_roleSessionVar]; } if (!is_null($_userRole) && !strlen($_userRole)) { $_userRole = null; } $folderPath = trim($folderPath, "/"); $_pathParts = explode("/", $folderPath); $_currentPath = "/"; for($i = -1; $i < sizeof($_pathParts); $i++) { if ($i >= 0) { if (!strlen($_pathParts[$i])) { continue; } if (array_key_exists($_currentPath . '*/', $this->_aclEntries)) $_computedMask = $this->mergePathComputedMask( $_computedMask, $resourceType, $_userRole, $_currentPath . '*/' ); $_currentPath .= $_pathParts[$i] . '/'; } if (array_key_exists($_currentPath, $this->_aclEntries)) { $_computedMask = $this->mergePathComputedMask( $_computedMask, $resourceType, $_userRole, $_currentPath ); } } return $_computedMask; }
php
public function getComputedMask($resourceType, $folderPath) { $_computedMask = 0; $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $_roleSessionVar = $_config->getRoleSessionVar(); $_userRole = null; if (strlen($_roleSessionVar) && isset($_SESSION[$_roleSessionVar])) { $_userRole = (string)$_SESSION[$_roleSessionVar]; } if (!is_null($_userRole) && !strlen($_userRole)) { $_userRole = null; } $folderPath = trim($folderPath, "/"); $_pathParts = explode("/", $folderPath); $_currentPath = "/"; for($i = -1; $i < sizeof($_pathParts); $i++) { if ($i >= 0) { if (!strlen($_pathParts[$i])) { continue; } if (array_key_exists($_currentPath . '*/', $this->_aclEntries)) $_computedMask = $this->mergePathComputedMask( $_computedMask, $resourceType, $_userRole, $_currentPath . '*/' ); $_currentPath .= $_pathParts[$i] . '/'; } if (array_key_exists($_currentPath, $this->_aclEntries)) { $_computedMask = $this->mergePathComputedMask( $_computedMask, $resourceType, $_userRole, $_currentPath ); } } return $_computedMask; }
[ "public", "function", "getComputedMask", "(", "$", "resourceType", ",", "$", "folderPath", ")", "{", "$", "_computedMask", "=", "0", ";", "$", "_config", "=", "&", "CKFinder_Connector_Core_Factory", "::", "getInstance", "(", "\"Core_Config\"", ")", ";", "$", "...
Get computed mask @param string $resourceType @param string $folderPath @return int
[ "Get", "computed", "mask" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Core/AccessControlConfig.php#L146-L184
train
pr-of-it/t4
framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Core/AccessControlConfig.php
CKFinder_Connector_Core_AccessControlConfig.mergePathComputedMask
private function mergePathComputedMask( $currentMask, $resourceType, $userRole, $path ) { $_folderEntries = $this->_aclEntries[$path]; $_possibleEntries = array(); $_possibleEntries[0] = "*#@#*"; $_possibleEntries[1] = "*#@#" . $resourceType; if (!is_null($userRole)) { $_possibleEntries[2] = $userRole . "#@#*"; $_possibleEntries[3] = $userRole . "#@#" . $resourceType; } for ($r = 0; $r < sizeof($_possibleEntries); $r++) { $_possibleKey = $_possibleEntries[$r]; if (array_key_exists($_possibleKey, $_folderEntries)) { $_rulesMasks = $_folderEntries[$_possibleKey]; $currentMask |= array_sum($_rulesMasks[0]); $currentMask ^= ($currentMask & array_sum($_rulesMasks[1])); } } return $currentMask; }
php
private function mergePathComputedMask( $currentMask, $resourceType, $userRole, $path ) { $_folderEntries = $this->_aclEntries[$path]; $_possibleEntries = array(); $_possibleEntries[0] = "*#@#*"; $_possibleEntries[1] = "*#@#" . $resourceType; if (!is_null($userRole)) { $_possibleEntries[2] = $userRole . "#@#*"; $_possibleEntries[3] = $userRole . "#@#" . $resourceType; } for ($r = 0; $r < sizeof($_possibleEntries); $r++) { $_possibleKey = $_possibleEntries[$r]; if (array_key_exists($_possibleKey, $_folderEntries)) { $_rulesMasks = $_folderEntries[$_possibleKey]; $currentMask |= array_sum($_rulesMasks[0]); $currentMask ^= ($currentMask & array_sum($_rulesMasks[1])); } } return $currentMask; }
[ "private", "function", "mergePathComputedMask", "(", "$", "currentMask", ",", "$", "resourceType", ",", "$", "userRole", ",", "$", "path", ")", "{", "$", "_folderEntries", "=", "$", "this", "->", "_aclEntries", "[", "$", "path", "]", ";", "$", "_possibleEn...
merge current mask with folder entries @access private @param int $currentMask @param string $resourceType @param string $userRole @param string $path @return int
[ "merge", "current", "mask", "with", "folder", "entries" ]
8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada
https://github.com/pr-of-it/t4/blob/8a8133e0b3abca9d7718fbdcf65b70c2d85b5ada/framework/Mvc/Extensions/Ckfinder/lib/core/connector/php/php5/Core/AccessControlConfig.php#L196-L224
train
aimeos/ai-controller-jobs
controller/common/src/Controller/Common/Product/Import/Xml/Processor/Catalog/Standard.php
Standard.getCatalogItems
protected function getCatalogItems( \DOMNode $node ) { foreach( $node->childNodes as $node ) { if( $node->nodeName === 'catalogitem' && ( $refAttr = $node->attributes->getNamedItem( 'ref' ) ) !== null ) { $codes[] = $refAttr->nodeValue; } } $items = []; if( !empty( $codes ) ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'catalog' ); $search = $manager->createSearch()->setSlice( 0, count( $codes ) ); $search->setConditions( $search->compare( '==', 'catalog.code', $codes ) ); foreach( $manager->searchItems( $search ) as $item ) { $items[$item->getCode()] = $item; } } return $items; }
php
protected function getCatalogItems( \DOMNode $node ) { foreach( $node->childNodes as $node ) { if( $node->nodeName === 'catalogitem' && ( $refAttr = $node->attributes->getNamedItem( 'ref' ) ) !== null ) { $codes[] = $refAttr->nodeValue; } } $items = []; if( !empty( $codes ) ) { $manager = \Aimeos\MShop::create( $this->getContext(), 'catalog' ); $search = $manager->createSearch()->setSlice( 0, count( $codes ) ); $search->setConditions( $search->compare( '==', 'catalog.code', $codes ) ); foreach( $manager->searchItems( $search ) as $item ) { $items[$item->getCode()] = $item; } } return $items; }
[ "protected", "function", "getCatalogItems", "(", "\\", "DOMNode", "$", "node", ")", "{", "foreach", "(", "$", "node", "->", "childNodes", "as", "$", "node", ")", "{", "if", "(", "$", "node", "->", "nodeName", "===", "'catalogitem'", "&&", "(", "$", "re...
Returns the catalog items referenced in the DOM node @param \DOMNode $node XML document node containing a list of nodes to process @return \Aimeos\MShop\Catalog\Item\Iface[] List of referenced catalog items
[ "Returns", "the", "catalog", "items", "referenced", "in", "the", "DOM", "node" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/common/src/Controller/Common/Product/Import/Xml/Processor/Catalog/Standard.php#L127-L153
train
aimeos/ai-controller-jobs
controller/common/src/Controller/Common/Product/Import/Csv/Processor/Catalog/Standard.php
Standard.addListItemDefaults
protected function addListItemDefaults( array $list, $pos ) { if( !isset( $list['catalog.lists.position'] ) ) { $list['catalog.lists.position'] = $pos; } if( !isset( $list['catalog.lists.status'] ) ) { $list['catalog.lists.status'] = 1; } return $list; }
php
protected function addListItemDefaults( array $list, $pos ) { if( !isset( $list['catalog.lists.position'] ) ) { $list['catalog.lists.position'] = $pos; } if( !isset( $list['catalog.lists.status'] ) ) { $list['catalog.lists.status'] = 1; } return $list; }
[ "protected", "function", "addListItemDefaults", "(", "array", "$", "list", ",", "$", "pos", ")", "{", "if", "(", "!", "isset", "(", "$", "list", "[", "'catalog.lists.position'", "]", ")", ")", "{", "$", "list", "[", "'catalog.lists.position'", "]", "=", ...
Adds the list item default values and returns the resulting array @param array $list Associative list of domain item keys and their values, e.g. "catalog.lists.status" => 1 @param integer $pos Computed position of the list item in the associated list of items @return array Given associative list enriched by default values if they were not already set
[ "Adds", "the", "list", "item", "default", "values", "and", "returns", "the", "resulting", "array" ]
e4a2fc47850f72907afff68858a2be5865fa4664
https://github.com/aimeos/ai-controller-jobs/blob/e4a2fc47850f72907afff68858a2be5865fa4664/controller/common/src/Controller/Common/Product/Import/Csv/Processor/Catalog/Standard.php#L200-L211
train