id
int32
0
241k
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
26,800
GW2Treasures/gw2api
src/V2/Pagination/PaginationHandler.php
PaginationHandler.onError
public function onError( ResponseInterface $response, RequestInterface $request ) { $json = $this->getResponseAsJson( $response ); if( !is_null( $json ) && isset( $json->text )) { if( strpos( $json->text, 'page out of range.' ) === 0 ) { throw new PageOutOfRangeException( $json->text, $response ); } } }
php
public function onError( ResponseInterface $response, RequestInterface $request ) { $json = $this->getResponseAsJson( $response ); if( !is_null( $json ) && isset( $json->text )) { if( strpos( $json->text, 'page out of range.' ) === 0 ) { throw new PageOutOfRangeException( $json->text, $response ); } } }
[ "public", "function", "onError", "(", "ResponseInterface", "$", "response", ",", "RequestInterface", "$", "request", ")", "{", "$", "json", "=", "$", "this", "->", "getResponseAsJson", "(", "$", "response", ")", ";", "if", "(", "!", "is_null", "(", "$", "json", ")", "&&", "isset", "(", "$", "json", "->", "text", ")", ")", "{", "if", "(", "strpos", "(", "$", "json", "->", "text", ",", "'page out of range.'", ")", "===", "0", ")", "{", "throw", "new", "PageOutOfRangeException", "(", "$", "json", "->", "text", ",", "$", "response", ")", ";", "}", "}", "}" ]
Handle PageOutOfRangeExceptions. @param ResponseInterface $response @param RequestInterface $request @throws PageOutOfRangeException
[ "Handle", "PageOutOfRangeExceptions", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Pagination/PaginationHandler.php#L26-L33
26,801
GW2Treasures/gw2api
src/GW2Api.php
GW2Api.extractCacertFile
protected function extractCacertFile() { if( $this->isIncludedAsPhar() ) { $cacertFilePath = $this->getCacertFilePath(); if( !file_exists( $cacertFilePath )) { copy( __DIR__ . '/cacert.pem', $cacertFilePath ); } } }
php
protected function extractCacertFile() { if( $this->isIncludedAsPhar() ) { $cacertFilePath = $this->getCacertFilePath(); if( !file_exists( $cacertFilePath )) { copy( __DIR__ . '/cacert.pem', $cacertFilePath ); } } }
[ "protected", "function", "extractCacertFile", "(", ")", "{", "if", "(", "$", "this", "->", "isIncludedAsPhar", "(", ")", ")", "{", "$", "cacertFilePath", "=", "$", "this", "->", "getCacertFilePath", "(", ")", ";", "if", "(", "!", "file_exists", "(", "$", "cacertFilePath", ")", ")", "{", "copy", "(", "__DIR__", ".", "'/cacert.pem'", ",", "$", "cacertFilePath", ")", ";", "}", "}", "}" ]
Copies the phar cacert from the phar into the temp directory.
[ "Copies", "the", "phar", "cacert", "from", "the", "phar", "into", "the", "temp", "directory", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/GW2Api.php#L114-L122
26,802
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.isCached
public function isCached() { $cache = ObjectFactory::getInstance('staticCache'); return $this->id == self::NO_CACHE ? false : $cache->exists(self::getCacheSection($this->type), self::getCacheId($this->id)); }
php
public function isCached() { $cache = ObjectFactory::getInstance('staticCache'); return $this->id == self::NO_CACHE ? false : $cache->exists(self::getCacheSection($this->type), self::getCacheId($this->id)); }
[ "public", "function", "isCached", "(", ")", "{", "$", "cache", "=", "ObjectFactory", "::", "getInstance", "(", "'staticCache'", ")", ";", "return", "$", "this", "->", "id", "==", "self", "::", "NO_CACHE", "?", "false", ":", "$", "cache", "->", "exists", "(", "self", "::", "getCacheSection", "(", "$", "this", "->", "type", ")", ",", "self", "::", "getCacheId", "(", "$", "this", "->", "id", ")", ")", ";", "}" ]
Check if the statement is cached already @return Boolean
[ "Check", "if", "the", "statement", "is", "cached", "already" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L106-L110
26,803
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.setParameters
public function setParameters($parameters) { $this->parameters = $parameters; // store version with colons stripped $this->parametersStripped = array_combine(array_map(function($name) { return preg_replace('/^:/', '', $name); }, array_keys($this->parameters)), $this->parameters); }
php
public function setParameters($parameters) { $this->parameters = $parameters; // store version with colons stripped $this->parametersStripped = array_combine(array_map(function($name) { return preg_replace('/^:/', '', $name); }, array_keys($this->parameters)), $this->parameters); }
[ "public", "function", "setParameters", "(", "$", "parameters", ")", "{", "$", "this", "->", "parameters", "=", "$", "parameters", ";", "// store version with colons stripped", "$", "this", "->", "parametersStripped", "=", "array_combine", "(", "array_map", "(", "function", "(", "$", "name", ")", "{", "return", "preg_replace", "(", "'/^:/'", ",", "''", ",", "$", "name", ")", ";", "}", ",", "array_keys", "(", "$", "this", "->", "parameters", ")", ")", ",", "$", "this", "->", "parameters", ")", ";", "}" ]
Set the parameter values to replace the placeholders with when doing the select @param $parameters Associative array with placeholders as keys
[ "Set", "the", "parameter", "values", "to", "replace", "the", "placeholders", "with", "when", "doing", "the", "select" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L137-L143
26,804
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.getRowCount
public function getRowCount() { $mapper = ObjectFactory::getInstance('persistenceFacade')->getMapper($this->type); if ($this->table) { $table = !is_array($this->table) ? $this-> table : key($this->table); // use pk columns for counting $countColumns = array_map(function($valueName) use ($mapper, $table) { return $mapper->quoteIdentifier($table).'.'.$mapper->quoteIdentifier($mapper->getAttribute($valueName)->getColumn()); }, $mapper->getPkNames()); } else { // fallback if table is not defined: take first column $adapter = $this->getAdapter(); $columns = $this->processSelect($adapter->getPlatform()); $countColumns = [$columns[$this->quantifier ? 1 : 0][0][0]]; } $countStatement = clone $this; $countStatement->reset(Select::COLUMNS); $countStatement->reset(Select::LIMIT); $countStatement->reset(Select::OFFSET); $countStatement->reset(Select::ORDER); $countStatement->reset(Select::GROUP); // remove all join columns to prevent errors because of missing group by for non aggregated columns (42000 - 1140) $joins = $countStatement->joins->getJoins(); $countStatement->reset(Select::JOINS); foreach ($joins as $key => $join) { // re add join without cols $countStatement->join($join["name"], $join["on"], [], $join["type"]); } // create aggregation column $countStatement->columns(['nRows' => new \Zend\Db\Sql\Expression('COUNT('.$this->quantifier.' '.join(', ', $countColumns).')')]); $countStatement->id = $this->id != self::NO_CACHE ? $this->id.'-count' : self::NO_CACHE; try { $result = $countStatement->query(); $row = $result->fetch(); return $row['nRows']; } catch (\Exception $ex) { self::$logger->error("The query: ".$countStatement->__toString()."\ncaused the following exception:\n".$ex->getMessage()); throw new PersistenceException("Error in persistent operation. See log file for details."); } }
php
public function getRowCount() { $mapper = ObjectFactory::getInstance('persistenceFacade')->getMapper($this->type); if ($this->table) { $table = !is_array($this->table) ? $this-> table : key($this->table); // use pk columns for counting $countColumns = array_map(function($valueName) use ($mapper, $table) { return $mapper->quoteIdentifier($table).'.'.$mapper->quoteIdentifier($mapper->getAttribute($valueName)->getColumn()); }, $mapper->getPkNames()); } else { // fallback if table is not defined: take first column $adapter = $this->getAdapter(); $columns = $this->processSelect($adapter->getPlatform()); $countColumns = [$columns[$this->quantifier ? 1 : 0][0][0]]; } $countStatement = clone $this; $countStatement->reset(Select::COLUMNS); $countStatement->reset(Select::LIMIT); $countStatement->reset(Select::OFFSET); $countStatement->reset(Select::ORDER); $countStatement->reset(Select::GROUP); // remove all join columns to prevent errors because of missing group by for non aggregated columns (42000 - 1140) $joins = $countStatement->joins->getJoins(); $countStatement->reset(Select::JOINS); foreach ($joins as $key => $join) { // re add join without cols $countStatement->join($join["name"], $join["on"], [], $join["type"]); } // create aggregation column $countStatement->columns(['nRows' => new \Zend\Db\Sql\Expression('COUNT('.$this->quantifier.' '.join(', ', $countColumns).')')]); $countStatement->id = $this->id != self::NO_CACHE ? $this->id.'-count' : self::NO_CACHE; try { $result = $countStatement->query(); $row = $result->fetch(); return $row['nRows']; } catch (\Exception $ex) { self::$logger->error("The query: ".$countStatement->__toString()."\ncaused the following exception:\n".$ex->getMessage()); throw new PersistenceException("Error in persistent operation. See log file for details."); } }
[ "public", "function", "getRowCount", "(", ")", "{", "$", "mapper", "=", "ObjectFactory", "::", "getInstance", "(", "'persistenceFacade'", ")", "->", "getMapper", "(", "$", "this", "->", "type", ")", ";", "if", "(", "$", "this", "->", "table", ")", "{", "$", "table", "=", "!", "is_array", "(", "$", "this", "->", "table", ")", "?", "$", "this", "->", "table", ":", "key", "(", "$", "this", "->", "table", ")", ";", "// use pk columns for counting", "$", "countColumns", "=", "array_map", "(", "function", "(", "$", "valueName", ")", "use", "(", "$", "mapper", ",", "$", "table", ")", "{", "return", "$", "mapper", "->", "quoteIdentifier", "(", "$", "table", ")", ".", "'.'", ".", "$", "mapper", "->", "quoteIdentifier", "(", "$", "mapper", "->", "getAttribute", "(", "$", "valueName", ")", "->", "getColumn", "(", ")", ")", ";", "}", ",", "$", "mapper", "->", "getPkNames", "(", ")", ")", ";", "}", "else", "{", "// fallback if table is not defined: take first column", "$", "adapter", "=", "$", "this", "->", "getAdapter", "(", ")", ";", "$", "columns", "=", "$", "this", "->", "processSelect", "(", "$", "adapter", "->", "getPlatform", "(", ")", ")", ";", "$", "countColumns", "=", "[", "$", "columns", "[", "$", "this", "->", "quantifier", "?", "1", ":", "0", "]", "[", "0", "]", "[", "0", "]", "]", ";", "}", "$", "countStatement", "=", "clone", "$", "this", ";", "$", "countStatement", "->", "reset", "(", "Select", "::", "COLUMNS", ")", ";", "$", "countStatement", "->", "reset", "(", "Select", "::", "LIMIT", ")", ";", "$", "countStatement", "->", "reset", "(", "Select", "::", "OFFSET", ")", ";", "$", "countStatement", "->", "reset", "(", "Select", "::", "ORDER", ")", ";", "$", "countStatement", "->", "reset", "(", "Select", "::", "GROUP", ")", ";", "// remove all join columns to prevent errors because of missing group by for non aggregated columns (42000 - 1140)", "$", "joins", "=", "$", "countStatement", "->", "joins", "->", "getJoins", "(", ")", ";", "$", "countStatement", "->", "reset", "(", "Select", "::", "JOINS", ")", ";", "foreach", "(", "$", "joins", "as", "$", "key", "=>", "$", "join", ")", "{", "// re add join without cols", "$", "countStatement", "->", "join", "(", "$", "join", "[", "\"name\"", "]", ",", "$", "join", "[", "\"on\"", "]", ",", "[", "]", ",", "$", "join", "[", "\"type\"", "]", ")", ";", "}", "// create aggregation column", "$", "countStatement", "->", "columns", "(", "[", "'nRows'", "=>", "new", "\\", "Zend", "\\", "Db", "\\", "Sql", "\\", "Expression", "(", "'COUNT('", ".", "$", "this", "->", "quantifier", ".", "' '", ".", "join", "(", "', '", ",", "$", "countColumns", ")", ".", "')'", ")", "]", ")", ";", "$", "countStatement", "->", "id", "=", "$", "this", "->", "id", "!=", "self", "::", "NO_CACHE", "?", "$", "this", "->", "id", ".", "'-count'", ":", "self", "::", "NO_CACHE", ";", "try", "{", "$", "result", "=", "$", "countStatement", "->", "query", "(", ")", ";", "$", "row", "=", "$", "result", "->", "fetch", "(", ")", ";", "return", "$", "row", "[", "'nRows'", "]", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "self", "::", "$", "logger", "->", "error", "(", "\"The query: \"", ".", "$", "countStatement", "->", "__toString", "(", ")", ".", "\"\\ncaused the following exception:\\n\"", ".", "$", "ex", "->", "getMessage", "(", ")", ")", ";", "throw", "new", "PersistenceException", "(", "\"Error in persistent operation. See log file for details.\"", ")", ";", "}", "}" ]
Execute a count query and return the row count @return Integer
[ "Execute", "a", "count", "query", "and", "return", "the", "row", "count" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L158-L201
26,805
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.save
public function save() { if ($this->id != self::NO_CACHE) { $cache = ObjectFactory::getInstance('staticCache'); $cache->put(self::getCacheSection($this->type), self::getCacheId($this->id), $this); } }
php
public function save() { if ($this->id != self::NO_CACHE) { $cache = ObjectFactory::getInstance('staticCache'); $cache->put(self::getCacheSection($this->type), self::getCacheId($this->id), $this); } }
[ "public", "function", "save", "(", ")", "{", "if", "(", "$", "this", "->", "id", "!=", "self", "::", "NO_CACHE", ")", "{", "$", "cache", "=", "ObjectFactory", "::", "getInstance", "(", "'staticCache'", ")", ";", "$", "cache", "->", "put", "(", "self", "::", "getCacheSection", "(", "$", "this", "->", "type", ")", ",", "self", "::", "getCacheId", "(", "$", "this", "->", "id", ")", ",", "$", "this", ")", ";", "}", "}" ]
Put the statement into the cache
[ "Put", "the", "statement", "into", "the", "cache" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L206-L211
26,806
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.addColumns
public function addColumns(array $columns, $joinName=null) { if ($joinName === null) { // add normal column $this->columns = $this->columns + $columns; } else { // add column to join $joins = []; foreach ($this->joins->getJoins() as $join) { if ($join['name'] == $joinName || in_array($joinName, array_keys($join['name']))) { $join['columns'] += $columns; } $joins[] = $join; } $this->joins->reset(); foreach ($joins as $join) { parent::join($join['name'], $join['on'], $join['columns'], $join['type']); } } }
php
public function addColumns(array $columns, $joinName=null) { if ($joinName === null) { // add normal column $this->columns = $this->columns + $columns; } else { // add column to join $joins = []; foreach ($this->joins->getJoins() as $join) { if ($join['name'] == $joinName || in_array($joinName, array_keys($join['name']))) { $join['columns'] += $columns; } $joins[] = $join; } $this->joins->reset(); foreach ($joins as $join) { parent::join($join['name'], $join['on'], $join['columns'], $join['type']); } } }
[ "public", "function", "addColumns", "(", "array", "$", "columns", ",", "$", "joinName", "=", "null", ")", "{", "if", "(", "$", "joinName", "===", "null", ")", "{", "// add normal column", "$", "this", "->", "columns", "=", "$", "this", "->", "columns", "+", "$", "columns", ";", "}", "else", "{", "// add column to join", "$", "joins", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "joins", "->", "getJoins", "(", ")", "as", "$", "join", ")", "{", "if", "(", "$", "join", "[", "'name'", "]", "==", "$", "joinName", "||", "in_array", "(", "$", "joinName", ",", "array_keys", "(", "$", "join", "[", "'name'", "]", ")", ")", ")", "{", "$", "join", "[", "'columns'", "]", "+=", "$", "columns", ";", "}", "$", "joins", "[", "]", "=", "$", "join", ";", "}", "$", "this", "->", "joins", "->", "reset", "(", ")", ";", "foreach", "(", "$", "joins", "as", "$", "join", ")", "{", "parent", "::", "join", "(", "$", "join", "[", "'name'", "]", ",", "$", "join", "[", "'on'", "]", ",", "$", "join", "[", "'columns'", "]", ",", "$", "join", "[", "'type'", "]", ")", ";", "}", "}", "}" ]
Add columns to the statement @param $columns Array of columns (@see Select::columns()) @param $joinName The name of the join to which the columns belong
[ "Add", "columns", "to", "the", "statement" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L231-L250
26,807
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.getAliasNames
public function getAliasNames($table) { $names = []; if (is_array($this->table) && current($this->table) == $table) { $names[] = key($this->table); } foreach ($this->joins->getJoins() as $join) { $joinName = $join['name']; if (is_array($joinName) && current($joinName) == $table) { $names[] = key($joinName); } } return $names; }
php
public function getAliasNames($table) { $names = []; if (is_array($this->table) && current($this->table) == $table) { $names[] = key($this->table); } foreach ($this->joins->getJoins() as $join) { $joinName = $join['name']; if (is_array($joinName) && current($joinName) == $table) { $names[] = key($joinName); } } return $names; }
[ "public", "function", "getAliasNames", "(", "$", "table", ")", "{", "$", "names", "=", "[", "]", ";", "if", "(", "is_array", "(", "$", "this", "->", "table", ")", "&&", "current", "(", "$", "this", "->", "table", ")", "==", "$", "table", ")", "{", "$", "names", "[", "]", "=", "key", "(", "$", "this", "->", "table", ")", ";", "}", "foreach", "(", "$", "this", "->", "joins", "->", "getJoins", "(", ")", "as", "$", "join", ")", "{", "$", "joinName", "=", "$", "join", "[", "'name'", "]", ";", "if", "(", "is_array", "(", "$", "joinName", ")", "&&", "current", "(", "$", "joinName", ")", "==", "$", "table", ")", "{", "$", "names", "[", "]", "=", "key", "(", "$", "joinName", ")", ";", "}", "}", "return", "$", "names", ";", "}" ]
Get the alias names for a table name @param $tables @return Array
[ "Get", "the", "alias", "names", "for", "a", "table", "name" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L257-L269
26,808
iherwig/wcmf
src/wcmf/lib/model/mapper/SelectStatement.php
SelectStatement.getSql
public function getSql() { $cacheKey = self::getCacheId($this->id); if (!isset($this->cachedSql[$cacheKey])) { $sql = trim((new Sql($this->getAdapter()))->buildSqlString($this)); $this->cachedSql[$cacheKey] = $sql; } return $this->cachedSql[$cacheKey]; }
php
public function getSql() { $cacheKey = self::getCacheId($this->id); if (!isset($this->cachedSql[$cacheKey])) { $sql = trim((new Sql($this->getAdapter()))->buildSqlString($this)); $this->cachedSql[$cacheKey] = $sql; } return $this->cachedSql[$cacheKey]; }
[ "public", "function", "getSql", "(", ")", "{", "$", "cacheKey", "=", "self", "::", "getCacheId", "(", "$", "this", "->", "id", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "cachedSql", "[", "$", "cacheKey", "]", ")", ")", "{", "$", "sql", "=", "trim", "(", "(", "new", "Sql", "(", "$", "this", "->", "getAdapter", "(", ")", ")", ")", "->", "buildSqlString", "(", "$", "this", ")", ")", ";", "$", "this", "->", "cachedSql", "[", "$", "cacheKey", "]", "=", "$", "sql", ";", "}", "return", "$", "this", "->", "cachedSql", "[", "$", "cacheKey", "]", ";", "}" ]
Get the sql string for this statement @return String
[ "Get", "the", "sql", "string", "for", "this", "statement" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/model/mapper/SelectStatement.php#L275-L282
26,809
iherwig/wcmf
src/wcmf/application/controller/BatchDisplayController.php
BatchDisplayController.loadNode
protected function loadNode(ObjectId $oid) { // check if we already loaded the node if ($this->isRegistered($oid)) { return; } $persistenceFacade = $this->getPersistenceFacade(); // restore the request values from session $language = $this->getRequestValue('language'); $translateValues = StringUtil::getBoolean($this->getRequestValue('translateValues')); // load the node $node = $persistenceFacade->load($oid); if ($node == null) { throw new PersistenceException("Can't load node '".$oid."'"); } // translate all nodes to the requested language if requested if ($this->isLocalizedRequest()) { $localization = $this->getLocalization(); $node = $localization->loadTranslation($node, $language, true, true); } // translate values if requested if ($translateValues) { $nodes = [$node]; if ($this->isLocalizedRequest()) { NodeUtil::translateValues($nodes, $language); } else { NodeUtil::translateValues($nodes); } } // assign it to the response $this->addNodeToResponse($node); $this->register($oid); $logger = $this->getLogger(); if ($logger->isInfoEnabled()) { $logger->info("Loaded: ".$node->getOID()); } if ($logger->isDebugEnabled()) { $logger->debug($node->toString()); } }
php
protected function loadNode(ObjectId $oid) { // check if we already loaded the node if ($this->isRegistered($oid)) { return; } $persistenceFacade = $this->getPersistenceFacade(); // restore the request values from session $language = $this->getRequestValue('language'); $translateValues = StringUtil::getBoolean($this->getRequestValue('translateValues')); // load the node $node = $persistenceFacade->load($oid); if ($node == null) { throw new PersistenceException("Can't load node '".$oid."'"); } // translate all nodes to the requested language if requested if ($this->isLocalizedRequest()) { $localization = $this->getLocalization(); $node = $localization->loadTranslation($node, $language, true, true); } // translate values if requested if ($translateValues) { $nodes = [$node]; if ($this->isLocalizedRequest()) { NodeUtil::translateValues($nodes, $language); } else { NodeUtil::translateValues($nodes); } } // assign it to the response $this->addNodeToResponse($node); $this->register($oid); $logger = $this->getLogger(); if ($logger->isInfoEnabled()) { $logger->info("Loaded: ".$node->getOID()); } if ($logger->isDebugEnabled()) { $logger->debug($node->toString()); } }
[ "protected", "function", "loadNode", "(", "ObjectId", "$", "oid", ")", "{", "// check if we already loaded the node", "if", "(", "$", "this", "->", "isRegistered", "(", "$", "oid", ")", ")", "{", "return", ";", "}", "$", "persistenceFacade", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", ";", "// restore the request values from session", "$", "language", "=", "$", "this", "->", "getRequestValue", "(", "'language'", ")", ";", "$", "translateValues", "=", "StringUtil", "::", "getBoolean", "(", "$", "this", "->", "getRequestValue", "(", "'translateValues'", ")", ")", ";", "// load the node", "$", "node", "=", "$", "persistenceFacade", "->", "load", "(", "$", "oid", ")", ";", "if", "(", "$", "node", "==", "null", ")", "{", "throw", "new", "PersistenceException", "(", "\"Can't load node '\"", ".", "$", "oid", ".", "\"'\"", ")", ";", "}", "// translate all nodes to the requested language if requested", "if", "(", "$", "this", "->", "isLocalizedRequest", "(", ")", ")", "{", "$", "localization", "=", "$", "this", "->", "getLocalization", "(", ")", ";", "$", "node", "=", "$", "localization", "->", "loadTranslation", "(", "$", "node", ",", "$", "language", ",", "true", ",", "true", ")", ";", "}", "// translate values if requested", "if", "(", "$", "translateValues", ")", "{", "$", "nodes", "=", "[", "$", "node", "]", ";", "if", "(", "$", "this", "->", "isLocalizedRequest", "(", ")", ")", "{", "NodeUtil", "::", "translateValues", "(", "$", "nodes", ",", "$", "language", ")", ";", "}", "else", "{", "NodeUtil", "::", "translateValues", "(", "$", "nodes", ")", ";", "}", "}", "// assign it to the response", "$", "this", "->", "addNodeToResponse", "(", "$", "node", ")", ";", "$", "this", "->", "register", "(", "$", "oid", ")", ";", "$", "logger", "=", "$", "this", "->", "getLogger", "(", ")", ";", "if", "(", "$", "logger", "->", "isInfoEnabled", "(", ")", ")", "{", "$", "logger", "->", "info", "(", "\"Loaded: \"", ".", "$", "node", "->", "getOID", "(", ")", ")", ";", "}", "if", "(", "$", "logger", "->", "isDebugEnabled", "(", ")", ")", "{", "$", "logger", "->", "debug", "(", "$", "node", "->", "toString", "(", ")", ")", ";", "}", "}" ]
Load the node with the given object id and assign it to the response. @param $oid The object id of the node to copy
[ "Load", "the", "node", "with", "the", "given", "object", "id", "and", "assign", "it", "to", "the", "response", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchDisplayController.php#L208-L254
26,810
iherwig/wcmf
src/wcmf/application/controller/BatchDisplayController.php
BatchDisplayController.register
protected function register(ObjectId $oid) { $registry = $this->getLocalSessionValue(self::REGISTRY_VAR); $registry[] = $oid->__toString(); $this->setLocalSessionValue(self::REGISTRY_VAR, $registry); }
php
protected function register(ObjectId $oid) { $registry = $this->getLocalSessionValue(self::REGISTRY_VAR); $registry[] = $oid->__toString(); $this->setLocalSessionValue(self::REGISTRY_VAR, $registry); }
[ "protected", "function", "register", "(", "ObjectId", "$", "oid", ")", "{", "$", "registry", "=", "$", "this", "->", "getLocalSessionValue", "(", "self", "::", "REGISTRY_VAR", ")", ";", "$", "registry", "[", "]", "=", "$", "oid", "->", "__toString", "(", ")", ";", "$", "this", "->", "setLocalSessionValue", "(", "self", "::", "REGISTRY_VAR", ",", "$", "registry", ")", ";", "}" ]
Register an object id in the registry @param $oid The object id to register
[ "Register", "an", "object", "id", "in", "the", "registry" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchDisplayController.php#L260-L264
26,811
iherwig/wcmf
src/wcmf/application/controller/BatchDisplayController.php
BatchDisplayController.isRegistered
protected function isRegistered(ObjectId $oid) { $registry = $this->getLocalSessionValue(self::REGISTRY_VAR); return in_array($oid->__toString(), $registry); }
php
protected function isRegistered(ObjectId $oid) { $registry = $this->getLocalSessionValue(self::REGISTRY_VAR); return in_array($oid->__toString(), $registry); }
[ "protected", "function", "isRegistered", "(", "ObjectId", "$", "oid", ")", "{", "$", "registry", "=", "$", "this", "->", "getLocalSessionValue", "(", "self", "::", "REGISTRY_VAR", ")", ";", "return", "in_array", "(", "$", "oid", "->", "__toString", "(", ")", ",", "$", "registry", ")", ";", "}" ]
Check if an object id is registered in the registry @param $oid The object id to check @return Boolean whether the object id is registered or not
[ "Check", "if", "an", "object", "id", "is", "registered", "in", "the", "registry" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchDisplayController.php#L271-L274
26,812
iherwig/wcmf
src/wcmf/application/controller/BatchDisplayController.php
BatchDisplayController.addNodeToResponse
protected function addNodeToResponse(Node $node) { $response = $this->getResponse(); if (!$response->hasValue('list')) { $objects = []; $response->setValue('list', $objects); } $objects = $response->getValue('list'); $objects[] = $node; $response->setValue('list', $objects); }
php
protected function addNodeToResponse(Node $node) { $response = $this->getResponse(); if (!$response->hasValue('list')) { $objects = []; $response->setValue('list', $objects); } $objects = $response->getValue('list'); $objects[] = $node; $response->setValue('list', $objects); }
[ "protected", "function", "addNodeToResponse", "(", "Node", "$", "node", ")", "{", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "if", "(", "!", "$", "response", "->", "hasValue", "(", "'list'", ")", ")", "{", "$", "objects", "=", "[", "]", ";", "$", "response", "->", "setValue", "(", "'list'", ",", "$", "objects", ")", ";", "}", "$", "objects", "=", "$", "response", "->", "getValue", "(", "'list'", ")", ";", "$", "objects", "[", "]", "=", "$", "node", ";", "$", "response", "->", "setValue", "(", "'list'", ",", "$", "objects", ")", ";", "}" ]
Add a given node to the list variable of the response @param $node The Node instance to add
[ "Add", "a", "given", "node", "to", "the", "list", "variable", "of", "the", "response" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchDisplayController.php#L280-L290
26,813
GW2Treasures/gw2api
src/V2/Schema/SchemaHandler.php
SchemaHandler.onRequest
public function onRequest( RequestInterface $request ) { $schema = $this->getEndpoint()->getSchema(); return $request->withHeader( 'X-Schema-Version', $schema ); }
php
public function onRequest( RequestInterface $request ) { $schema = $this->getEndpoint()->getSchema(); return $request->withHeader( 'X-Schema-Version', $schema ); }
[ "public", "function", "onRequest", "(", "RequestInterface", "$", "request", ")", "{", "$", "schema", "=", "$", "this", "->", "getEndpoint", "(", ")", "->", "getSchema", "(", ")", ";", "return", "$", "request", "->", "withHeader", "(", "'X-Schema-Version'", ",", "$", "schema", ")", ";", "}" ]
Add the schema version header. @param RequestInterface $request @return MessageInterface|RequestInterface
[ "Add", "the", "schema", "version", "header", "." ]
c8795af0c1d0a434b9e530f779d5a95786db2176
https://github.com/GW2Treasures/gw2api/blob/c8795af0c1d0a434b9e530f779d5a95786db2176/src/V2/Schema/SchemaHandler.php#L22-L26
26,814
iherwig/wcmf
src/wcmf/application/controller/MediaController.php
MediaController.onFileMoved
protected function onFileMoved($cmd, $result, $args, $elfinder) { $addedFiles = $result['added']; $removedFiles = $result['removed']; for ($i=0, $count=sizeof($removedFiles); $i<$count; $i++) { $source = $removedFiles[$i]['realpath']; $target = $elfinder->realpath($addedFiles[$i]['hash']); } $logger = $this->getLogger(); $logger->debug($cmd." file: ".$source." -> ".$target); }
php
protected function onFileMoved($cmd, $result, $args, $elfinder) { $addedFiles = $result['added']; $removedFiles = $result['removed']; for ($i=0, $count=sizeof($removedFiles); $i<$count; $i++) { $source = $removedFiles[$i]['realpath']; $target = $elfinder->realpath($addedFiles[$i]['hash']); } $logger = $this->getLogger(); $logger->debug($cmd." file: ".$source." -> ".$target); }
[ "protected", "function", "onFileMoved", "(", "$", "cmd", ",", "$", "result", ",", "$", "args", ",", "$", "elfinder", ")", "{", "$", "addedFiles", "=", "$", "result", "[", "'added'", "]", ";", "$", "removedFiles", "=", "$", "result", "[", "'removed'", "]", ";", "for", "(", "$", "i", "=", "0", ",", "$", "count", "=", "sizeof", "(", "$", "removedFiles", ")", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "$", "source", "=", "$", "removedFiles", "[", "$", "i", "]", "[", "'realpath'", "]", ";", "$", "target", "=", "$", "elfinder", "->", "realpath", "(", "$", "addedFiles", "[", "$", "i", "]", "[", "'hash'", "]", ")", ";", "}", "$", "logger", "=", "$", "this", "->", "getLogger", "(", ")", ";", "$", "logger", "->", "debug", "(", "$", "cmd", ".", "\" file: \"", ".", "$", "source", ".", "\" -> \"", ".", "$", "target", ")", ";", "}" ]
Called when file is moved @param $cmd elFinder command name @param $result Command result as array @param $args Command arguments from client @param $elfinder elFinder instance
[ "Called", "when", "file", "is", "moved" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/MediaController.php#L156-L165
26,815
iherwig/wcmf
src/wcmf/lib/i18n/impl/FileMessage.php
FileMessage.getTranslations
private function getTranslations($lang) { if (!isset($this->translations[$lang])) { $messageFile = $this->localeDir."/messages_".$lang.".php"; if (file_exists($messageFile)) { require_once($messageFile); // store for later reference $this->translations[$lang] = ${"messages_$lang"}; } else { $this->translations[$lang] = []; } } return $this->translations[$lang]; }
php
private function getTranslations($lang) { if (!isset($this->translations[$lang])) { $messageFile = $this->localeDir."/messages_".$lang.".php"; if (file_exists($messageFile)) { require_once($messageFile); // store for later reference $this->translations[$lang] = ${"messages_$lang"}; } else { $this->translations[$lang] = []; } } return $this->translations[$lang]; }
[ "private", "function", "getTranslations", "(", "$", "lang", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "translations", "[", "$", "lang", "]", ")", ")", "{", "$", "messageFile", "=", "$", "this", "->", "localeDir", ".", "\"/messages_\"", ".", "$", "lang", ".", "\".php\"", ";", "if", "(", "file_exists", "(", "$", "messageFile", ")", ")", "{", "require_once", "(", "$", "messageFile", ")", ";", "// store for later reference", "$", "this", "->", "translations", "[", "$", "lang", "]", "=", "$", "{", "\"messages_$lang\"", "}", ";", "}", "else", "{", "$", "this", "->", "translations", "[", "$", "lang", "]", "=", "[", "]", ";", "}", "}", "return", "$", "this", "->", "translations", "[", "$", "lang", "]", ";", "}" ]
Get all translations for a language. @param $lang The language (optional, default: '') @return The translations as associative array
[ "Get", "all", "translations", "for", "a", "language", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/i18n/impl/FileMessage.php#L97-L110
26,816
vufind-org/vufindharvest
src/OaiPmh/HarvesterFactory.php
HarvesterFactory.configureClient
protected function configureClient(Client $client, array $settings) { $configuredClient = $client ?: new Client(); // Set authentication, if necessary: if (!empty($settings['httpUser']) && !empty($settings['httpPass'])) { $configuredClient->setAuth($settings['httpUser'], $settings['httpPass']); } // Set up assorted client options from $settings array: $configuredClient->setOptions($this->getClientOptions($settings)); return $configuredClient; }
php
protected function configureClient(Client $client, array $settings) { $configuredClient = $client ?: new Client(); // Set authentication, if necessary: if (!empty($settings['httpUser']) && !empty($settings['httpPass'])) { $configuredClient->setAuth($settings['httpUser'], $settings['httpPass']); } // Set up assorted client options from $settings array: $configuredClient->setOptions($this->getClientOptions($settings)); return $configuredClient; }
[ "protected", "function", "configureClient", "(", "Client", "$", "client", ",", "array", "$", "settings", ")", "{", "$", "configuredClient", "=", "$", "client", "?", ":", "new", "Client", "(", ")", ";", "// Set authentication, if necessary:", "if", "(", "!", "empty", "(", "$", "settings", "[", "'httpUser'", "]", ")", "&&", "!", "empty", "(", "$", "settings", "[", "'httpPass'", "]", ")", ")", "{", "$", "configuredClient", "->", "setAuth", "(", "$", "settings", "[", "'httpUser'", "]", ",", "$", "settings", "[", "'httpPass'", "]", ")", ";", "}", "// Set up assorted client options from $settings array:", "$", "configuredClient", "->", "setOptions", "(", "$", "this", "->", "getClientOptions", "(", "$", "settings", ")", ")", ";", "return", "$", "configuredClient", ";", "}" ]
Configure the HTTP client @param Client $client HTTP client @param array $settings Settings @return Client @throws Exception
[ "Configure", "the", "HTTP", "client" ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterFactory.php#L103-L116
26,817
vufind-org/vufindharvest
src/OaiPmh/HarvesterFactory.php
HarvesterFactory.getBasePath
protected function getBasePath($harvestRoot, $target) { // Build the full harvest path: $basePath = rtrim($harvestRoot, '/') . '/' . rtrim($target, '/') . '/'; // Create the directory if it does not already exist: if (!is_dir($basePath)) { if (!mkdir($basePath)) { throw new \Exception("Problem creating directory {$basePath}."); } } return $basePath; }
php
protected function getBasePath($harvestRoot, $target) { // Build the full harvest path: $basePath = rtrim($harvestRoot, '/') . '/' . rtrim($target, '/') . '/'; // Create the directory if it does not already exist: if (!is_dir($basePath)) { if (!mkdir($basePath)) { throw new \Exception("Problem creating directory {$basePath}."); } } return $basePath; }
[ "protected", "function", "getBasePath", "(", "$", "harvestRoot", ",", "$", "target", ")", "{", "// Build the full harvest path:", "$", "basePath", "=", "rtrim", "(", "$", "harvestRoot", ",", "'/'", ")", ".", "'/'", ".", "rtrim", "(", "$", "target", ",", "'/'", ")", ".", "'/'", ";", "// Create the directory if it does not already exist:", "if", "(", "!", "is_dir", "(", "$", "basePath", ")", ")", "{", "if", "(", "!", "mkdir", "(", "$", "basePath", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Problem creating directory {$basePath}.\"", ")", ";", "}", "}", "return", "$", "basePath", ";", "}" ]
Set up directory structure for harvesting. @param string $harvestRoot Root directory containing harvested data. @param string $target The OAI-PMH target directory to create inside $harvestRoot. @return string
[ "Set", "up", "directory", "structure", "for", "harvesting", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterFactory.php#L127-L140
26,818
vufind-org/vufindharvest
src/OaiPmh/HarvesterFactory.php
HarvesterFactory.getCommunicator
protected function getCommunicator(Client $client, array $settings, ResponseProcessorInterface $processor, $target ) { if (empty($settings['url'])) { throw new \Exception("Missing base URL for {$target}."); } $comm = new Communicator($settings['url'], $client, $processor); // We only want the communicator to output messages if we are in verbose // mode; communicator messages are considered verbose output. if (isset($settings['verbose']) && $settings['verbose'] && $writer = $this->getConsoleWriter($settings) ) { $comm->setOutputWriter($writer); } return $comm; }
php
protected function getCommunicator(Client $client, array $settings, ResponseProcessorInterface $processor, $target ) { if (empty($settings['url'])) { throw new \Exception("Missing base URL for {$target}."); } $comm = new Communicator($settings['url'], $client, $processor); // We only want the communicator to output messages if we are in verbose // mode; communicator messages are considered verbose output. if (isset($settings['verbose']) && $settings['verbose'] && $writer = $this->getConsoleWriter($settings) ) { $comm->setOutputWriter($writer); } return $comm; }
[ "protected", "function", "getCommunicator", "(", "Client", "$", "client", ",", "array", "$", "settings", ",", "ResponseProcessorInterface", "$", "processor", ",", "$", "target", ")", "{", "if", "(", "empty", "(", "$", "settings", "[", "'url'", "]", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "\"Missing base URL for {$target}.\"", ")", ";", "}", "$", "comm", "=", "new", "Communicator", "(", "$", "settings", "[", "'url'", "]", ",", "$", "client", ",", "$", "processor", ")", ";", "// We only want the communicator to output messages if we are in verbose", "// mode; communicator messages are considered verbose output.", "if", "(", "isset", "(", "$", "settings", "[", "'verbose'", "]", ")", "&&", "$", "settings", "[", "'verbose'", "]", "&&", "$", "writer", "=", "$", "this", "->", "getConsoleWriter", "(", "$", "settings", ")", ")", "{", "$", "comm", "->", "setOutputWriter", "(", "$", "writer", ")", ";", "}", "return", "$", "comm", ";", "}" ]
Get the communicator. @param Client $client HTTP client @param array $settings Additional settings @param ResponseProcessorInterface $processor Response processor @param string $target Target being configured (used for error messages) @return Communicator
[ "Get", "the", "communicator", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterFactory.php#L153-L168
26,819
vufind-org/vufindharvest
src/OaiPmh/HarvesterFactory.php
HarvesterFactory.getFormatter
protected function getFormatter(Communicator $communicator, array $settings) { // Build the formatter: $formatter = new RecordXmlFormatter($settings); // Load set names if we're going to need them: if ($formatter->needsSetNames()) { $loader = $this->getSetLoader($communicator, $settings); if ($writer = $this->getConsoleWriter($settings)) { $loader->setOutputWriter($writer); } $formatter->setSetNames($loader->getNames()); } return $formatter; }
php
protected function getFormatter(Communicator $communicator, array $settings) { // Build the formatter: $formatter = new RecordXmlFormatter($settings); // Load set names if we're going to need them: if ($formatter->needsSetNames()) { $loader = $this->getSetLoader($communicator, $settings); if ($writer = $this->getConsoleWriter($settings)) { $loader->setOutputWriter($writer); } $formatter->setSetNames($loader->getNames()); } return $formatter; }
[ "protected", "function", "getFormatter", "(", "Communicator", "$", "communicator", ",", "array", "$", "settings", ")", "{", "// Build the formatter:", "$", "formatter", "=", "new", "RecordXmlFormatter", "(", "$", "settings", ")", ";", "// Load set names if we're going to need them:", "if", "(", "$", "formatter", "->", "needsSetNames", "(", ")", ")", "{", "$", "loader", "=", "$", "this", "->", "getSetLoader", "(", "$", "communicator", ",", "$", "settings", ")", ";", "if", "(", "$", "writer", "=", "$", "this", "->", "getConsoleWriter", "(", "$", "settings", ")", ")", "{", "$", "loader", "->", "setOutputWriter", "(", "$", "writer", ")", ";", "}", "$", "formatter", "->", "setSetNames", "(", "$", "loader", "->", "getNames", "(", ")", ")", ";", "}", "return", "$", "formatter", ";", "}" ]
Get the record XML formatter. @param Communicator $communicator Communicator @param array $settings Additional settings @return RecordXmlFormatter
[ "Get", "the", "record", "XML", "formatter", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterFactory.php#L178-L193
26,820
vufind-org/vufindharvest
src/OaiPmh/HarvesterFactory.php
HarvesterFactory.getWriter
protected function getWriter(RecordWriterStrategyInterface $strategy, RecordXmlFormatter $formatter, array $settings ) { return new RecordWriter($strategy, $formatter, $settings); }
php
protected function getWriter(RecordWriterStrategyInterface $strategy, RecordXmlFormatter $formatter, array $settings ) { return new RecordWriter($strategy, $formatter, $settings); }
[ "protected", "function", "getWriter", "(", "RecordWriterStrategyInterface", "$", "strategy", ",", "RecordXmlFormatter", "$", "formatter", ",", "array", "$", "settings", ")", "{", "return", "new", "RecordWriter", "(", "$", "strategy", ",", "$", "formatter", ",", "$", "settings", ")", ";", "}" ]
Build the writer support object. @param RecordWriterStrategyInterface $strategy Writing strategy @param RecordXmlFormatter $formatter XML record formatter @param array $settings Configuration settings @return RecordWriter
[ "Build", "the", "writer", "support", "object", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterFactory.php#L256-L260
26,821
vufind-org/vufindharvest
src/OaiPmh/HarvesterFactory.php
HarvesterFactory.getHarvester
public function getHarvester($target, $harvestRoot, Client $client = null, array $settings = [] ) { $basePath = $this->getBasePath($harvestRoot, $target); $responseProcessor = $this->getResponseProcessor($basePath, $settings); $communicator = $this->getCommunicator( $this->configureClient($client, $settings), $settings, $responseProcessor, $target ); $formatter = $this->getFormatter($communicator, $settings); $strategy = $this->getWriterStrategyFactory() ->getStrategy($basePath, $settings); $writer = $this->getWriter($strategy, $formatter, $settings); $stateManager = $this->getStateManager($basePath); $harvester = new Harvester($communicator, $writer, $stateManager, $settings); if ($writer = $this->getConsoleWriter($settings)) { $harvester->setOutputWriter($writer); } return $harvester; }
php
public function getHarvester($target, $harvestRoot, Client $client = null, array $settings = [] ) { $basePath = $this->getBasePath($harvestRoot, $target); $responseProcessor = $this->getResponseProcessor($basePath, $settings); $communicator = $this->getCommunicator( $this->configureClient($client, $settings), $settings, $responseProcessor, $target ); $formatter = $this->getFormatter($communicator, $settings); $strategy = $this->getWriterStrategyFactory() ->getStrategy($basePath, $settings); $writer = $this->getWriter($strategy, $formatter, $settings); $stateManager = $this->getStateManager($basePath); $harvester = new Harvester($communicator, $writer, $stateManager, $settings); if ($writer = $this->getConsoleWriter($settings)) { $harvester->setOutputWriter($writer); } return $harvester; }
[ "public", "function", "getHarvester", "(", "$", "target", ",", "$", "harvestRoot", ",", "Client", "$", "client", "=", "null", ",", "array", "$", "settings", "=", "[", "]", ")", "{", "$", "basePath", "=", "$", "this", "->", "getBasePath", "(", "$", "harvestRoot", ",", "$", "target", ")", ";", "$", "responseProcessor", "=", "$", "this", "->", "getResponseProcessor", "(", "$", "basePath", ",", "$", "settings", ")", ";", "$", "communicator", "=", "$", "this", "->", "getCommunicator", "(", "$", "this", "->", "configureClient", "(", "$", "client", ",", "$", "settings", ")", ",", "$", "settings", ",", "$", "responseProcessor", ",", "$", "target", ")", ";", "$", "formatter", "=", "$", "this", "->", "getFormatter", "(", "$", "communicator", ",", "$", "settings", ")", ";", "$", "strategy", "=", "$", "this", "->", "getWriterStrategyFactory", "(", ")", "->", "getStrategy", "(", "$", "basePath", ",", "$", "settings", ")", ";", "$", "writer", "=", "$", "this", "->", "getWriter", "(", "$", "strategy", ",", "$", "formatter", ",", "$", "settings", ")", ";", "$", "stateManager", "=", "$", "this", "->", "getStateManager", "(", "$", "basePath", ")", ";", "$", "harvester", "=", "new", "Harvester", "(", "$", "communicator", ",", "$", "writer", ",", "$", "stateManager", ",", "$", "settings", ")", ";", "if", "(", "$", "writer", "=", "$", "this", "->", "getConsoleWriter", "(", "$", "settings", ")", ")", "{", "$", "harvester", "->", "setOutputWriter", "(", "$", "writer", ")", ";", "}", "return", "$", "harvester", ";", "}" ]
Get the harvester @param string $target Name of source being harvested (used as directory name for storing harvested data inside $harvestRoot) @param string $harvestRoot Root directory containing harvested data. @param Client $client HTTP client @param array $settings Additional settings @return Harvester @throws \Exception
[ "Get", "the", "harvester" ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/HarvesterFactory.php#L285-L304
26,822
iherwig/wcmf
src/wcmf/application/controller/BatchController.php
BatchController.addWorkPackage
protected function addWorkPackage($name, $size, array $oids, $callback, $args=null) { $request = $this->getRequest(); $response = $this->getResponse(); if (strlen($callback) == 0) { throw new ApplicationException($request, $response, ApplicationError::getGeneral("Wrong work package description '".$name."': No callback given.")); } $workPackages = $this->getLocalSessionValue(self::PACKAGES_VAR); $counter = 1; $total = sizeof($oids); while(sizeof($oids) > 0) { $items = []; for($i=0; $i<$size && sizeof($oids)>0; $i++) { $nextItem = array_shift($oids); $items[] = sprintf('%s', $nextItem); } // define status text $start = $counter; $end = ($counter+sizeof($items)-1); $stepsText = $counter; if ($start != $end) { $stepsText .= '-'.($counter+sizeof($items)-1); } $statusText = ""; if ($total > 1) { $statusText = $stepsText.'/'.$total; } $curWorkPackage = [ 'name' => $name.' '.$statusText, 'oids' => $items, 'callback' => $callback, 'args' => $args ]; $workPackages[] = $curWorkPackage; $counter += $size; } $this->workPackages = $workPackages; // update session $this->setLocalSessionValue(self::PACKAGES_VAR, $workPackages); $this->setLocalSessionValue(self::NUM_STEPS_VAR, sizeof($workPackages)); }
php
protected function addWorkPackage($name, $size, array $oids, $callback, $args=null) { $request = $this->getRequest(); $response = $this->getResponse(); if (strlen($callback) == 0) { throw new ApplicationException($request, $response, ApplicationError::getGeneral("Wrong work package description '".$name."': No callback given.")); } $workPackages = $this->getLocalSessionValue(self::PACKAGES_VAR); $counter = 1; $total = sizeof($oids); while(sizeof($oids) > 0) { $items = []; for($i=0; $i<$size && sizeof($oids)>0; $i++) { $nextItem = array_shift($oids); $items[] = sprintf('%s', $nextItem); } // define status text $start = $counter; $end = ($counter+sizeof($items)-1); $stepsText = $counter; if ($start != $end) { $stepsText .= '-'.($counter+sizeof($items)-1); } $statusText = ""; if ($total > 1) { $statusText = $stepsText.'/'.$total; } $curWorkPackage = [ 'name' => $name.' '.$statusText, 'oids' => $items, 'callback' => $callback, 'args' => $args ]; $workPackages[] = $curWorkPackage; $counter += $size; } $this->workPackages = $workPackages; // update session $this->setLocalSessionValue(self::PACKAGES_VAR, $workPackages); $this->setLocalSessionValue(self::NUM_STEPS_VAR, sizeof($workPackages)); }
[ "protected", "function", "addWorkPackage", "(", "$", "name", ",", "$", "size", ",", "array", "$", "oids", ",", "$", "callback", ",", "$", "args", "=", "null", ")", "{", "$", "request", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "response", "=", "$", "this", "->", "getResponse", "(", ")", ";", "if", "(", "strlen", "(", "$", "callback", ")", "==", "0", ")", "{", "throw", "new", "ApplicationException", "(", "$", "request", ",", "$", "response", ",", "ApplicationError", "::", "getGeneral", "(", "\"Wrong work package description '\"", ".", "$", "name", ".", "\"': No callback given.\"", ")", ")", ";", "}", "$", "workPackages", "=", "$", "this", "->", "getLocalSessionValue", "(", "self", "::", "PACKAGES_VAR", ")", ";", "$", "counter", "=", "1", ";", "$", "total", "=", "sizeof", "(", "$", "oids", ")", ";", "while", "(", "sizeof", "(", "$", "oids", ")", ">", "0", ")", "{", "$", "items", "=", "[", "]", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "size", "&&", "sizeof", "(", "$", "oids", ")", ">", "0", ";", "$", "i", "++", ")", "{", "$", "nextItem", "=", "array_shift", "(", "$", "oids", ")", ";", "$", "items", "[", "]", "=", "sprintf", "(", "'%s'", ",", "$", "nextItem", ")", ";", "}", "// define status text", "$", "start", "=", "$", "counter", ";", "$", "end", "=", "(", "$", "counter", "+", "sizeof", "(", "$", "items", ")", "-", "1", ")", ";", "$", "stepsText", "=", "$", "counter", ";", "if", "(", "$", "start", "!=", "$", "end", ")", "{", "$", "stepsText", ".=", "'-'", ".", "(", "$", "counter", "+", "sizeof", "(", "$", "items", ")", "-", "1", ")", ";", "}", "$", "statusText", "=", "\"\"", ";", "if", "(", "$", "total", ">", "1", ")", "{", "$", "statusText", "=", "$", "stepsText", ".", "'/'", ".", "$", "total", ";", "}", "$", "curWorkPackage", "=", "[", "'name'", "=>", "$", "name", ".", "' '", ".", "$", "statusText", ",", "'oids'", "=>", "$", "items", ",", "'callback'", "=>", "$", "callback", ",", "'args'", "=>", "$", "args", "]", ";", "$", "workPackages", "[", "]", "=", "$", "curWorkPackage", ";", "$", "counter", "+=", "$", "size", ";", "}", "$", "this", "->", "workPackages", "=", "$", "workPackages", ";", "// update session", "$", "this", "->", "setLocalSessionValue", "(", "self", "::", "PACKAGES_VAR", ",", "$", "workPackages", ")", ";", "$", "this", "->", "setLocalSessionValue", "(", "self", "::", "NUM_STEPS_VAR", ",", "sizeof", "(", "$", "workPackages", ")", ")", ";", "}" ]
Add a work package to session. This package will be divided into sub packages of given size. @param $name Display name of the package (will be supplemented by startNumber-endNumber, e.g. '1-7', '8-14', ...) @param $size Size of one sub package. This defines how many of the oids will be passed to the callback in one call (e.g. '7' means pass 7 oids per call) @param $oids An array of object ids (or other application specific package identifiers) that will be distributed into sub packages of given size @param $callback The name of method to call for this package type. The callback method must accept the following parameters: 1. array parameter (the object ids to process in the current call) 2. optionally array parameter (the additional arguments) @param $args Associative array of additional callback arguments (application specific) (default: _null_)
[ "Add", "a", "work", "package", "to", "session", ".", "This", "package", "will", "be", "divided", "into", "sub", "packages", "of", "given", "size", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchController.php#L209-L253
26,823
iherwig/wcmf
src/wcmf/application/controller/BatchController.php
BatchController.getRequestValue
protected function getRequestValue($name) { $requestValues = $this->getLocalSessionValue(self::REQUEST_VAR); return isset($requestValues[$name]) ? $requestValues[$name] : null; }
php
protected function getRequestValue($name) { $requestValues = $this->getLocalSessionValue(self::REQUEST_VAR); return isset($requestValues[$name]) ? $requestValues[$name] : null; }
[ "protected", "function", "getRequestValue", "(", "$", "name", ")", "{", "$", "requestValues", "=", "$", "this", "->", "getLocalSessionValue", "(", "self", "::", "REQUEST_VAR", ")", ";", "return", "isset", "(", "$", "requestValues", "[", "$", "name", "]", ")", "?", "$", "requestValues", "[", "$", "name", "]", ":", "null", ";", "}" ]
Get a value from the initial request. @param $name The name of the value @return Mixed
[ "Get", "a", "value", "from", "the", "initial", "request", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchController.php#L284-L287
26,824
iherwig/wcmf
src/wcmf/application/controller/BatchController.php
BatchController.getDisplayText
protected function getDisplayText($step) { $numPackages = sizeof($this->workPackages); return ($step>=0 && $step<$numPackages) ? $this->workPackages[$step]['name']." ..." : ($step>=$numPackages ? "Done" : ""); }
php
protected function getDisplayText($step) { $numPackages = sizeof($this->workPackages); return ($step>=0 && $step<$numPackages) ? $this->workPackages[$step]['name']." ..." : ($step>=$numPackages ? "Done" : ""); }
[ "protected", "function", "getDisplayText", "(", "$", "step", ")", "{", "$", "numPackages", "=", "sizeof", "(", "$", "this", "->", "workPackages", ")", ";", "return", "(", "$", "step", ">=", "0", "&&", "$", "step", "<", "$", "numPackages", ")", "?", "$", "this", "->", "workPackages", "[", "$", "step", "]", "[", "'name'", "]", ".", "\" ...\"", ":", "(", "$", "step", ">=", "$", "numPackages", "?", "\"Done\"", ":", "\"\"", ")", ";", "}" ]
Get the text to display for the current step. @param $step The step number
[ "Get", "the", "text", "to", "display", "for", "the", "current", "step", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/BatchController.php#L301-L305
26,825
iherwig/wcmf
src/wcmf/lib/presentation/Controller.php
Controller.executeSubAction
protected function executeSubAction($action) { $curRequest = $this->getRequest(); $subRequest = ObjectFactory::getNewInstance('request'); $subRequest->setSender(get_class($this)); $subRequest->setContext($curRequest->getContext()); $subRequest->setAction($action); $subRequest->setHeaders($curRequest->getHeaders()); $subRequest->setValues($curRequest->getValues()); $subRequest->setFormat('null'); $subRequest->setResponseFormat('null'); $subResponse = ObjectFactory::getNewInstance('response'); $this->actionMapper->processAction($subRequest, $subResponse); return $subResponse; }
php
protected function executeSubAction($action) { $curRequest = $this->getRequest(); $subRequest = ObjectFactory::getNewInstance('request'); $subRequest->setSender(get_class($this)); $subRequest->setContext($curRequest->getContext()); $subRequest->setAction($action); $subRequest->setHeaders($curRequest->getHeaders()); $subRequest->setValues($curRequest->getValues()); $subRequest->setFormat('null'); $subRequest->setResponseFormat('null'); $subResponse = ObjectFactory::getNewInstance('response'); $this->actionMapper->processAction($subRequest, $subResponse); return $subResponse; }
[ "protected", "function", "executeSubAction", "(", "$", "action", ")", "{", "$", "curRequest", "=", "$", "this", "->", "getRequest", "(", ")", ";", "$", "subRequest", "=", "ObjectFactory", "::", "getNewInstance", "(", "'request'", ")", ";", "$", "subRequest", "->", "setSender", "(", "get_class", "(", "$", "this", ")", ")", ";", "$", "subRequest", "->", "setContext", "(", "$", "curRequest", "->", "getContext", "(", ")", ")", ";", "$", "subRequest", "->", "setAction", "(", "$", "action", ")", ";", "$", "subRequest", "->", "setHeaders", "(", "$", "curRequest", "->", "getHeaders", "(", ")", ")", ";", "$", "subRequest", "->", "setValues", "(", "$", "curRequest", "->", "getValues", "(", ")", ")", ";", "$", "subRequest", "->", "setFormat", "(", "'null'", ")", ";", "$", "subRequest", "->", "setResponseFormat", "(", "'null'", ")", ";", "$", "subResponse", "=", "ObjectFactory", "::", "getNewInstance", "(", "'response'", ")", ";", "$", "this", "->", "actionMapper", "->", "processAction", "(", "$", "subRequest", ",", "$", "subResponse", ")", ";", "return", "$", "subResponse", ";", "}" ]
Delegate the current request to another action. The context is the same as the current context and the source controller will be set to this. The request and response format will be NullFormat which means that all request values should be passed in the application internal format and all response values will have that format. Execution will return to the calling controller instance afterwards. @param $action The name of the action to execute @return Response instance
[ "Delegate", "the", "current", "request", "to", "another", "action", ".", "The", "context", "is", "the", "same", "as", "the", "current", "context", "and", "the", "source", "controller", "will", "be", "set", "to", "this", ".", "The", "request", "and", "response", "format", "will", "be", "NullFormat", "which", "means", "that", "all", "request", "values", "should", "be", "passed", "in", "the", "application", "internal", "format", "and", "all", "response", "values", "will", "have", "that", "format", ".", "Execution", "will", "return", "to", "the", "calling", "controller", "instance", "afterwards", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/Controller.php#L211-L224
26,826
iherwig/wcmf
src/wcmf/lib/presentation/Controller.php
Controller.endTransaction
protected function endTransaction($commit) { $tx = $this->getPersistenceFacade()->getTransaction(); if ($this->startedTransaction && $tx->isActive()) { if ($commit) { $tx->commit(); } else { $tx->rollback(); } } $this->startedTransaction = false; }
php
protected function endTransaction($commit) { $tx = $this->getPersistenceFacade()->getTransaction(); if ($this->startedTransaction && $tx->isActive()) { if ($commit) { $tx->commit(); } else { $tx->rollback(); } } $this->startedTransaction = false; }
[ "protected", "function", "endTransaction", "(", "$", "commit", ")", "{", "$", "tx", "=", "$", "this", "->", "getPersistenceFacade", "(", ")", "->", "getTransaction", "(", ")", ";", "if", "(", "$", "this", "->", "startedTransaction", "&&", "$", "tx", "->", "isActive", "(", ")", ")", "{", "if", "(", "$", "commit", ")", "{", "$", "tx", "->", "commit", "(", ")", ";", "}", "else", "{", "$", "tx", "->", "rollback", "(", ")", ";", "}", "}", "$", "this", "->", "startedTransaction", "=", "false", ";", "}" ]
End the transaction. Only if this controller instance started the transaction, it will be committed or rolled back. Otherwise the call will be ignored. @param $commit Boolean whether the transaction should be committed
[ "End", "the", "transaction", ".", "Only", "if", "this", "controller", "instance", "started", "the", "transaction", "it", "will", "be", "committed", "or", "rolled", "back", ".", "Otherwise", "the", "call", "will", "be", "ignored", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/Controller.php#L347-L358
26,827
iherwig/wcmf
src/wcmf/lib/presentation/Controller.php
Controller.getLocalSessionValue
protected function getLocalSessionValue($key, $default=null) { $sessionVarname = get_class($this); $localValues = $this->session->get($sessionVarname, null); return array_key_exists($key, $localValues) ? $localValues[$key] : $default; }
php
protected function getLocalSessionValue($key, $default=null) { $sessionVarname = get_class($this); $localValues = $this->session->get($sessionVarname, null); return array_key_exists($key, $localValues) ? $localValues[$key] : $default; }
[ "protected", "function", "getLocalSessionValue", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "sessionVarname", "=", "get_class", "(", "$", "this", ")", ";", "$", "localValues", "=", "$", "this", "->", "session", "->", "get", "(", "$", "sessionVarname", ",", "null", ")", ";", "return", "array_key_exists", "(", "$", "key", ",", "$", "localValues", ")", "?", "$", "localValues", "[", "$", "key", "]", ":", "$", "default", ";", "}" ]
Set the value of a local session variable. @param $key The key (name) of the session vaiable. @param $default The default value if the key is not defined (optional, default: _null_) @return The session var or null if it doesn't exist.
[ "Set", "the", "value", "of", "a", "local", "session", "variable", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/Controller.php#L435-L439
26,828
iherwig/wcmf
src/wcmf/lib/presentation/Controller.php
Controller.setLocalSessionValue
protected function setLocalSessionValue($key, $value) { $sessionVarname = get_class($this); $localValues = $this->session->get($sessionVarname, null); if ($localValues == null) { $localValues = []; } $localValues[$key] = $value; $this->session->set($sessionVarname, $localValues); }
php
protected function setLocalSessionValue($key, $value) { $sessionVarname = get_class($this); $localValues = $this->session->get($sessionVarname, null); if ($localValues == null) { $localValues = []; } $localValues[$key] = $value; $this->session->set($sessionVarname, $localValues); }
[ "protected", "function", "setLocalSessionValue", "(", "$", "key", ",", "$", "value", ")", "{", "$", "sessionVarname", "=", "get_class", "(", "$", "this", ")", ";", "$", "localValues", "=", "$", "this", "->", "session", "->", "get", "(", "$", "sessionVarname", ",", "null", ")", ";", "if", "(", "$", "localValues", "==", "null", ")", "{", "$", "localValues", "=", "[", "]", ";", "}", "$", "localValues", "[", "$", "key", "]", "=", "$", "value", ";", "$", "this", "->", "session", "->", "set", "(", "$", "sessionVarname", ",", "$", "localValues", ")", ";", "}" ]
Get the value of a local session variable. @param $key The key (name) of the session vaiable. @param $value The value of the session variable.
[ "Get", "the", "value", "of", "a", "local", "session", "variable", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/presentation/Controller.php#L446-L454
26,829
iherwig/wcmf
src/wcmf/lib/config/ActionKey.php
ActionKey.createKey
public static function createKey($resource, $context, $action) { return $resource.self::$actionDelimiter.$context.self::$actionDelimiter.$action; }
php
public static function createKey($resource, $context, $action) { return $resource.self::$actionDelimiter.$context.self::$actionDelimiter.$action; }
[ "public", "static", "function", "createKey", "(", "$", "resource", ",", "$", "context", ",", "$", "action", ")", "{", "return", "$", "resource", ".", "self", "::", "$", "actionDelimiter", ".", "$", "context", ".", "self", "::", "$", "actionDelimiter", ".", "$", "action", ";", "}" ]
Create an action key from the given values @param $resource The resource @param $context The context @param $action The action @return String
[ "Create", "an", "action", "key", "from", "the", "given", "values" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/ActionKey.php#L33-L35
26,830
iherwig/wcmf
src/wcmf/lib/config/ActionKey.php
ActionKey.parseKey
public static function parseKey($actionKey) { list($resource, $context, $action) = explode(self::$actionDelimiter, $actionKey); return ['resource' => $resource, 'context' => $context, 'action' => $action]; }
php
public static function parseKey($actionKey) { list($resource, $context, $action) = explode(self::$actionDelimiter, $actionKey); return ['resource' => $resource, 'context' => $context, 'action' => $action]; }
[ "public", "static", "function", "parseKey", "(", "$", "actionKey", ")", "{", "list", "(", "$", "resource", ",", "$", "context", ",", "$", "action", ")", "=", "explode", "(", "self", "::", "$", "actionDelimiter", ",", "$", "actionKey", ")", ";", "return", "[", "'resource'", "=>", "$", "resource", ",", "'context'", "=>", "$", "context", ",", "'action'", "=>", "$", "action", "]", ";", "}" ]
Parse an action @param $actionKey The action key @return Associative array with keys 'resouce', 'context', 'action'
[ "Parse", "an", "action" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/ActionKey.php#L42-L45
26,831
iherwig/wcmf
src/wcmf/lib/config/ActionKey.php
ActionKey.getBestMatch
public static function getBestMatch(ActionKeyProvider $actionKeyProvider, $resource, $context, $action) { $hasResource = strlen($resource) > 0; $hasContext = strlen($context) > 0; $hasAction = strlen($action) > 0; // check resource?context?action if ($hasResource && $hasContext && $hasAction) { $key = self::createKey($resource, $context, $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check resource??action if ($hasResource && $hasAction) { $key = self::createKey($resource, '', $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check resource?context? if ($hasResource && $hasContext) { $key = self::createKey($resource, $context, ''); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ?context?action if ($hasContext && $hasAction) { $key = self::createKey('', $context, $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ??action if ($hasAction) { $key = self::createKey('', '', $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check resource?? if ($hasResource) { $key = self::createKey($resource, '', ''); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ?context? if ($hasContext) { $key = self::createKey('', $context, ''); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ?? $key = self::createKey('', '', ''); if ($actionKeyProvider->containsKey($key)) { return $key; } // no key found for requested key return ''; }
php
public static function getBestMatch(ActionKeyProvider $actionKeyProvider, $resource, $context, $action) { $hasResource = strlen($resource) > 0; $hasContext = strlen($context) > 0; $hasAction = strlen($action) > 0; // check resource?context?action if ($hasResource && $hasContext && $hasAction) { $key = self::createKey($resource, $context, $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check resource??action if ($hasResource && $hasAction) { $key = self::createKey($resource, '', $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check resource?context? if ($hasResource && $hasContext) { $key = self::createKey($resource, $context, ''); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ?context?action if ($hasContext && $hasAction) { $key = self::createKey('', $context, $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ??action if ($hasAction) { $key = self::createKey('', '', $action); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check resource?? if ($hasResource) { $key = self::createKey($resource, '', ''); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ?context? if ($hasContext) { $key = self::createKey('', $context, ''); if ($actionKeyProvider->containsKey($key)) { return $key; } } // check ?? $key = self::createKey('', '', ''); if ($actionKeyProvider->containsKey($key)) { return $key; } // no key found for requested key return ''; }
[ "public", "static", "function", "getBestMatch", "(", "ActionKeyProvider", "$", "actionKeyProvider", ",", "$", "resource", ",", "$", "context", ",", "$", "action", ")", "{", "$", "hasResource", "=", "strlen", "(", "$", "resource", ")", ">", "0", ";", "$", "hasContext", "=", "strlen", "(", "$", "context", ")", ">", "0", ";", "$", "hasAction", "=", "strlen", "(", "$", "action", ")", ">", "0", ";", "// check resource?context?action", "if", "(", "$", "hasResource", "&&", "$", "hasContext", "&&", "$", "hasAction", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "$", "resource", ",", "$", "context", ",", "$", "action", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check resource??action", "if", "(", "$", "hasResource", "&&", "$", "hasAction", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "$", "resource", ",", "''", ",", "$", "action", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check resource?context?", "if", "(", "$", "hasResource", "&&", "$", "hasContext", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "$", "resource", ",", "$", "context", ",", "''", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check ?context?action", "if", "(", "$", "hasContext", "&&", "$", "hasAction", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "''", ",", "$", "context", ",", "$", "action", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check ??action", "if", "(", "$", "hasAction", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "''", ",", "''", ",", "$", "action", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check resource??", "if", "(", "$", "hasResource", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "$", "resource", ",", "''", ",", "''", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check ?context?", "if", "(", "$", "hasContext", ")", "{", "$", "key", "=", "self", "::", "createKey", "(", "''", ",", "$", "context", ",", "''", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "}", "// check ??", "$", "key", "=", "self", "::", "createKey", "(", "''", ",", "''", ",", "''", ")", ";", "if", "(", "$", "actionKeyProvider", "->", "containsKey", "(", "$", "key", ")", ")", "{", "return", "$", "key", ";", "}", "// no key found for requested key", "return", "''", ";", "}" ]
Get an action key that matches a given combination of resource, context, action best. @param $actionKeyProvider ActionKeyProvider instance used to search action keys @param $resource The given resource @param $context The given context @param $action The given action @return The best matching key or an empty string if nothing matches.
[ "Get", "an", "action", "key", "that", "matches", "a", "given", "combination", "of", "resource", "context", "action", "best", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/config/ActionKey.php#L55-L124
26,832
vufind-org/vufindharvest
src/OaiPmh/RecordWriter.php
RecordWriter.write
public function write($records) { // Array for tracking successfully harvested IDs: $harvestedIds = []; // Date of most recent record encountered: $endDate = 0; $this->strategy->beginWrite(); // Loop through the records: foreach ($records as $record) { // Die if the record is missing its header: if (empty($record->header)) { throw new \Exception('Unexpected missing record header.'); } // Get the ID of the current record: $id = $this->extractID($record); // Save the current record, either as a deleted or as a regular file: $attribs = $record->header->attributes(); if (strtolower($attribs['status']) == 'deleted') { $this->strategy->addDeletedRecord($id); } else { $recordXML = $this->recordFormatter->format($id, $record); $this->strategy->addRecord($id, $recordXML); $harvestedIds[] = $id; } // If the current record's date is newer than the previous end date, // remember it for future reference: $date = $this->normalizeDate($record->header->datestamp); if ($date && $date > $endDate) { $endDate = $date; } } $this->strategy->endWrite(); $this->writeHarvestedIdsLog($harvestedIds); return $endDate; }
php
public function write($records) { // Array for tracking successfully harvested IDs: $harvestedIds = []; // Date of most recent record encountered: $endDate = 0; $this->strategy->beginWrite(); // Loop through the records: foreach ($records as $record) { // Die if the record is missing its header: if (empty($record->header)) { throw new \Exception('Unexpected missing record header.'); } // Get the ID of the current record: $id = $this->extractID($record); // Save the current record, either as a deleted or as a regular file: $attribs = $record->header->attributes(); if (strtolower($attribs['status']) == 'deleted') { $this->strategy->addDeletedRecord($id); } else { $recordXML = $this->recordFormatter->format($id, $record); $this->strategy->addRecord($id, $recordXML); $harvestedIds[] = $id; } // If the current record's date is newer than the previous end date, // remember it for future reference: $date = $this->normalizeDate($record->header->datestamp); if ($date && $date > $endDate) { $endDate = $date; } } $this->strategy->endWrite(); $this->writeHarvestedIdsLog($harvestedIds); return $endDate; }
[ "public", "function", "write", "(", "$", "records", ")", "{", "// Array for tracking successfully harvested IDs:", "$", "harvestedIds", "=", "[", "]", ";", "// Date of most recent record encountered:", "$", "endDate", "=", "0", ";", "$", "this", "->", "strategy", "->", "beginWrite", "(", ")", ";", "// Loop through the records:", "foreach", "(", "$", "records", "as", "$", "record", ")", "{", "// Die if the record is missing its header:", "if", "(", "empty", "(", "$", "record", "->", "header", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'Unexpected missing record header.'", ")", ";", "}", "// Get the ID of the current record:", "$", "id", "=", "$", "this", "->", "extractID", "(", "$", "record", ")", ";", "// Save the current record, either as a deleted or as a regular file:", "$", "attribs", "=", "$", "record", "->", "header", "->", "attributes", "(", ")", ";", "if", "(", "strtolower", "(", "$", "attribs", "[", "'status'", "]", ")", "==", "'deleted'", ")", "{", "$", "this", "->", "strategy", "->", "addDeletedRecord", "(", "$", "id", ")", ";", "}", "else", "{", "$", "recordXML", "=", "$", "this", "->", "recordFormatter", "->", "format", "(", "$", "id", ",", "$", "record", ")", ";", "$", "this", "->", "strategy", "->", "addRecord", "(", "$", "id", ",", "$", "recordXML", ")", ";", "$", "harvestedIds", "[", "]", "=", "$", "id", ";", "}", "// If the current record's date is newer than the previous end date,", "// remember it for future reference:", "$", "date", "=", "$", "this", "->", "normalizeDate", "(", "$", "record", "->", "header", "->", "datestamp", ")", ";", "if", "(", "$", "date", "&&", "$", "date", ">", "$", "endDate", ")", "{", "$", "endDate", "=", "$", "date", ";", "}", "}", "$", "this", "->", "strategy", "->", "endWrite", "(", ")", ";", "$", "this", "->", "writeHarvestedIdsLog", "(", "$", "harvestedIds", ")", ";", "return", "$", "endDate", ";", "}" ]
Save harvested records to disk and return the end date. @param object $records SimpleXML records. @return int
[ "Save", "harvested", "records", "to", "disk", "and", "return", "the", "end", "date", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/RecordWriter.php#L189-L232
26,833
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistenceFacade.php
DefaultPersistenceFacade.setMappers
public function setMappers($mappers) { $this->mappers = $mappers; foreach ($mappers as $fqName => $mapper) { // register simple type names $name = $this->calculateSimpleType($fqName); if (!isset($this->mappers[$name])) { $this->mappers[$name] = $mapper; if (!isset($this->simpleToFqNames[$name])) { $this->simpleToFqNames[$name] = $fqName; } else { // if the simple type name already exists, we remove // it in order to prevent collisions with the new type unset($this->simpleToFqNames[$name]); } } // set logging strategy $mapper->setLogStrategy($this->logStrategy); } }
php
public function setMappers($mappers) { $this->mappers = $mappers; foreach ($mappers as $fqName => $mapper) { // register simple type names $name = $this->calculateSimpleType($fqName); if (!isset($this->mappers[$name])) { $this->mappers[$name] = $mapper; if (!isset($this->simpleToFqNames[$name])) { $this->simpleToFqNames[$name] = $fqName; } else { // if the simple type name already exists, we remove // it in order to prevent collisions with the new type unset($this->simpleToFqNames[$name]); } } // set logging strategy $mapper->setLogStrategy($this->logStrategy); } }
[ "public", "function", "setMappers", "(", "$", "mappers", ")", "{", "$", "this", "->", "mappers", "=", "$", "mappers", ";", "foreach", "(", "$", "mappers", "as", "$", "fqName", "=>", "$", "mapper", ")", "{", "// register simple type names", "$", "name", "=", "$", "this", "->", "calculateSimpleType", "(", "$", "fqName", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "mappers", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "mappers", "[", "$", "name", "]", "=", "$", "mapper", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "simpleToFqNames", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "simpleToFqNames", "[", "$", "name", "]", "=", "$", "fqName", ";", "}", "else", "{", "// if the simple type name already exists, we remove", "// it in order to prevent collisions with the new type", "unset", "(", "$", "this", "->", "simpleToFqNames", "[", "$", "name", "]", ")", ";", "}", "}", "// set logging strategy", "$", "mapper", "->", "setLogStrategy", "(", "$", "this", "->", "logStrategy", ")", ";", "}", "}" ]
Set the PersistentMapper instances. @param $mappers Associative array with the fully qualified mapped class names as keys and the mapper instances as values
[ "Set", "the", "PersistentMapper", "instances", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistenceFacade.php#L71-L90
26,834
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistenceFacade.php
DefaultPersistenceFacade.checkArrayParameter
private function checkArrayParameter($param, $paramName, $className=null) { if ($param == null) { return; } if (!is_array($param)) { throw new IllegalArgumentException("The parameter '".$paramName. "' is expected to be null or an array"); } if ($className != null) { foreach ($param as $instance) { if (!($instance instanceof $className)) { throw new IllegalArgumentException("The parameter '".$paramName. "' is expected to contain only instances of '".$className."'"); } } } }
php
private function checkArrayParameter($param, $paramName, $className=null) { if ($param == null) { return; } if (!is_array($param)) { throw new IllegalArgumentException("The parameter '".$paramName. "' is expected to be null or an array"); } if ($className != null) { foreach ($param as $instance) { if (!($instance instanceof $className)) { throw new IllegalArgumentException("The parameter '".$paramName. "' is expected to contain only instances of '".$className."'"); } } } }
[ "private", "function", "checkArrayParameter", "(", "$", "param", ",", "$", "paramName", ",", "$", "className", "=", "null", ")", "{", "if", "(", "$", "param", "==", "null", ")", "{", "return", ";", "}", "if", "(", "!", "is_array", "(", "$", "param", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The parameter '\"", ".", "$", "paramName", ".", "\"' is expected to be null or an array\"", ")", ";", "}", "if", "(", "$", "className", "!=", "null", ")", "{", "foreach", "(", "$", "param", "as", "$", "instance", ")", "{", "if", "(", "!", "(", "$", "instance", "instanceof", "$", "className", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The parameter '\"", ".", "$", "paramName", ".", "\"' is expected to contain only instances of '\"", ".", "$", "className", ".", "\"'\"", ")", ";", "}", "}", "}", "}" ]
Check if the given value is either null or an array and throw an exception if not @param $param The parameter @param $paramName The name of the parameter (used in the exception text) @param $className Class name to match if, instances of a specific type are expected (optional)
[ "Check", "if", "the", "given", "value", "is", "either", "null", "or", "an", "array", "and", "throw", "an", "exception", "if", "not" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistenceFacade.php#L277-L293
26,835
iherwig/wcmf
src/wcmf/lib/persistence/impl/DefaultPersistenceFacade.php
DefaultPersistenceFacade.calculateSimpleType
protected function calculateSimpleType($type) { $pos = strrpos($type, '.'); if ($pos !== false) { return substr($type, $pos+1); } return $type; }
php
protected function calculateSimpleType($type) { $pos = strrpos($type, '.'); if ($pos !== false) { return substr($type, $pos+1); } return $type; }
[ "protected", "function", "calculateSimpleType", "(", "$", "type", ")", "{", "$", "pos", "=", "strrpos", "(", "$", "type", ",", "'.'", ")", ";", "if", "(", "$", "pos", "!==", "false", ")", "{", "return", "substr", "(", "$", "type", ",", "$", "pos", "+", "1", ")", ";", "}", "return", "$", "type", ";", "}" ]
Calculate the simple type name for a given fully qualified type name. @param $type Type name with namespace @return Simple type name (without namespace)
[ "Calculate", "the", "simple", "type", "name", "for", "a", "given", "fully", "qualified", "type", "name", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultPersistenceFacade.php#L318-L324
26,836
skie/plum_search
src/FormParameter/AutocompleteParameter.php
AutocompleteParameter.initializeInnerParameters
public function initializeInnerParameters() { $paramName = $this->config('name'); $this->_dependentParameters[$paramName] = new HiddenParameter($this->_registry, [ 'name' => $paramName ]); }
php
public function initializeInnerParameters() { $paramName = $this->config('name'); $this->_dependentParameters[$paramName] = new HiddenParameter($this->_registry, [ 'name' => $paramName ]); }
[ "public", "function", "initializeInnerParameters", "(", ")", "{", "$", "paramName", "=", "$", "this", "->", "config", "(", "'name'", ")", ";", "$", "this", "->", "_dependentParameters", "[", "$", "paramName", "]", "=", "new", "HiddenParameter", "(", "$", "this", "->", "_registry", ",", "[", "'name'", "=>", "$", "paramName", "]", ")", ";", "}" ]
initialize inner parameters @return void
[ "initialize", "inner", "parameters" ]
24d981e240bff7c15731981d6f9b3056abdaf80e
https://github.com/skie/plum_search/blob/24d981e240bff7c15731981d6f9b3056abdaf80e/src/FormParameter/AutocompleteParameter.php#L74-L80
26,837
vufind-org/vufindharvest
src/OaiPmh/SetLoader.php
SetLoader.getNames
public function getNames() { $this->write("Loading set list... "); // On the first pass through the following loop, we want to get the // first page of sets without using a resumption token: $params = []; $setNames = []; // Grab set information until we have it all (at which point we will // break out of this otherwise-infinite loop): do { // Process current page of results: $response = $this->sendRequest('ListSets', $params); if (isset($response->ListSets->set)) { foreach ($response->ListSets->set as $current) { $spec = (string)$current->setSpec; $name = (string)$current->setName; if (!empty($spec)) { $setNames[$spec] = $name; } } } // Is there a resumption token? If so, continue looping; if not, // we're done! $params['resumptionToken'] = !empty($response->ListSets->resumptionToken) ? (string)$response->ListSets->resumptionToken : ''; } while (!empty($params['resumptionToken'])); $this->writeLine("found " . count($setNames)); return $setNames; }
php
public function getNames() { $this->write("Loading set list... "); // On the first pass through the following loop, we want to get the // first page of sets without using a resumption token: $params = []; $setNames = []; // Grab set information until we have it all (at which point we will // break out of this otherwise-infinite loop): do { // Process current page of results: $response = $this->sendRequest('ListSets', $params); if (isset($response->ListSets->set)) { foreach ($response->ListSets->set as $current) { $spec = (string)$current->setSpec; $name = (string)$current->setName; if (!empty($spec)) { $setNames[$spec] = $name; } } } // Is there a resumption token? If so, continue looping; if not, // we're done! $params['resumptionToken'] = !empty($response->ListSets->resumptionToken) ? (string)$response->ListSets->resumptionToken : ''; } while (!empty($params['resumptionToken'])); $this->writeLine("found " . count($setNames)); return $setNames; }
[ "public", "function", "getNames", "(", ")", "{", "$", "this", "->", "write", "(", "\"Loading set list... \"", ")", ";", "// On the first pass through the following loop, we want to get the", "// first page of sets without using a resumption token:", "$", "params", "=", "[", "]", ";", "$", "setNames", "=", "[", "]", ";", "// Grab set information until we have it all (at which point we will", "// break out of this otherwise-infinite loop):", "do", "{", "// Process current page of results:", "$", "response", "=", "$", "this", "->", "sendRequest", "(", "'ListSets'", ",", "$", "params", ")", ";", "if", "(", "isset", "(", "$", "response", "->", "ListSets", "->", "set", ")", ")", "{", "foreach", "(", "$", "response", "->", "ListSets", "->", "set", "as", "$", "current", ")", "{", "$", "spec", "=", "(", "string", ")", "$", "current", "->", "setSpec", ";", "$", "name", "=", "(", "string", ")", "$", "current", "->", "setName", ";", "if", "(", "!", "empty", "(", "$", "spec", ")", ")", "{", "$", "setNames", "[", "$", "spec", "]", "=", "$", "name", ";", "}", "}", "}", "// Is there a resumption token? If so, continue looping; if not,", "// we're done!", "$", "params", "[", "'resumptionToken'", "]", "=", "!", "empty", "(", "$", "response", "->", "ListSets", "->", "resumptionToken", ")", "?", "(", "string", ")", "$", "response", "->", "ListSets", "->", "resumptionToken", ":", "''", ";", "}", "while", "(", "!", "empty", "(", "$", "params", "[", "'resumptionToken'", "]", ")", ")", ";", "$", "this", "->", "writeLine", "(", "\"found \"", ".", "count", "(", "$", "setNames", ")", ")", ";", "return", "$", "setNames", ";", "}" ]
Load set list from the server. @return array
[ "Load", "set", "list", "from", "the", "server", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/SetLoader.php#L90-L123
26,838
vufind-org/vufindharvest
src/OaiPmh/RecordXmlFormatter.php
RecordXmlFormatter.fixNamespaces
protected function fixNamespaces($xml, $ns, $attr = '') { foreach ($ns as $key => $val) { if (!empty($key) && strstr($xml, $key . ':') && !strstr($xml, 'xmlns:' . $key) && !strstr($attr, 'xmlns:' . $key) ) { $attr .= ' xmlns:' . $key . '="' . $val . '"'; } } if (!empty($attr)) { $xml = preg_replace('/>/', ' ' . $attr . '>', $xml, 1); } return $xml; }
php
protected function fixNamespaces($xml, $ns, $attr = '') { foreach ($ns as $key => $val) { if (!empty($key) && strstr($xml, $key . ':') && !strstr($xml, 'xmlns:' . $key) && !strstr($attr, 'xmlns:' . $key) ) { $attr .= ' xmlns:' . $key . '="' . $val . '"'; } } if (!empty($attr)) { $xml = preg_replace('/>/', ' ' . $attr . '>', $xml, 1); } return $xml; }
[ "protected", "function", "fixNamespaces", "(", "$", "xml", ",", "$", "ns", ",", "$", "attr", "=", "''", ")", "{", "foreach", "(", "$", "ns", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "!", "empty", "(", "$", "key", ")", "&&", "strstr", "(", "$", "xml", ",", "$", "key", ".", "':'", ")", "&&", "!", "strstr", "(", "$", "xml", ",", "'xmlns:'", ".", "$", "key", ")", "&&", "!", "strstr", "(", "$", "attr", ",", "'xmlns:'", ".", "$", "key", ")", ")", "{", "$", "attr", ".=", "' xmlns:'", ".", "$", "key", ".", "'=\"'", ".", "$", "val", ".", "'\"'", ";", "}", "}", "if", "(", "!", "empty", "(", "$", "attr", ")", ")", "{", "$", "xml", "=", "preg_replace", "(", "'/>/'", ",", "' '", ".", "$", "attr", ".", "'>'", ",", "$", "xml", ",", "1", ")", ";", "}", "return", "$", "xml", ";", "}" ]
Fix namespaces in the top tag of the XML document to compensate for bugs in the SimpleXML library. @param string $xml XML document to clean up @param array $ns Namespaces to check @param string $attr Attributes extracted from the <metadata> tag @return string
[ "Fix", "namespaces", "in", "the", "top", "tag", "of", "the", "XML", "document", "to", "compensate", "for", "bugs", "in", "the", "SimpleXML", "library", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/RecordXmlFormatter.php#L132-L146
26,839
vufind-org/vufindharvest
src/OaiPmh/RecordXmlFormatter.php
RecordXmlFormatter.getHeaderSetAdditions
protected function getHeaderSetAdditions($setSpec) { $insert = ''; foreach ($setSpec as $current) { $set = (string)$current; if ($this->injectSetSpec) { $insert .= $this->createTag($this->injectSetSpec, $set); } if ($this->injectSetName) { $name = $this->setNames[$set] ?? $set; $insert .= $this->createTag($this->injectSetName, $name); } } return $insert; }
php
protected function getHeaderSetAdditions($setSpec) { $insert = ''; foreach ($setSpec as $current) { $set = (string)$current; if ($this->injectSetSpec) { $insert .= $this->createTag($this->injectSetSpec, $set); } if ($this->injectSetName) { $name = $this->setNames[$set] ?? $set; $insert .= $this->createTag($this->injectSetName, $name); } } return $insert; }
[ "protected", "function", "getHeaderSetAdditions", "(", "$", "setSpec", ")", "{", "$", "insert", "=", "''", ";", "foreach", "(", "$", "setSpec", "as", "$", "current", ")", "{", "$", "set", "=", "(", "string", ")", "$", "current", ";", "if", "(", "$", "this", "->", "injectSetSpec", ")", "{", "$", "insert", ".=", "$", "this", "->", "createTag", "(", "$", "this", "->", "injectSetSpec", ",", "$", "set", ")", ";", "}", "if", "(", "$", "this", "->", "injectSetName", ")", "{", "$", "name", "=", "$", "this", "->", "setNames", "[", "$", "set", "]", "??", "$", "set", ";", "$", "insert", ".=", "$", "this", "->", "createTag", "(", "$", "this", "->", "injectSetName", ",", "$", "name", ")", ";", "}", "}", "return", "$", "insert", ";", "}" ]
Format setSpec header element as XML tags for inclusion in final record. @param object $setSpec Header setSpec element (in SimpleXML format). @return string
[ "Format", "setSpec", "header", "element", "as", "XML", "tags", "for", "inclusion", "in", "final", "record", "." ]
43a42d1e2292fbba8974a26ace3d522551a1a88f
https://github.com/vufind-org/vufindharvest/blob/43a42d1e2292fbba8974a26ace3d522551a1a88f/src/OaiPmh/RecordXmlFormatter.php#L180-L194
26,840
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", ",", "(", "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", ";", "}" ]
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
26,841
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", ",", "$", "xml", ")", ";", "}" ]
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
26,842
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.\"", ")", ";", "}", "$", "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", ")", ")", ";", "}" ]
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
26,843
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", "(", "'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", ";", "}" ]
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
26,844
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", "[", "'key'", "]", "===", "$", "key", ")", "||", "(", "$", "key", "!==", "null", "&&", "strval", "(", "$", "item", "[", "'key'", "]", ")", "===", "strval", "(", "$", "key", ")", ")", ")", "{", "return", "$", "item", "[", "'value'", "]", ";", "}", "}", "return", "$", "key", ";", "}" ]
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
26,845
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", "->", "getAttribute", "(", "$", "this", "->", "otherName", ")", ";", "}" ]
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
26,846
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", ")", "{", "$", "proxy", "=", "new", "PersistentObjectProxy", "(", "$", "object", "->", "getOID", "(", ")", ")", ";", "$", "proxy", "->", "realSubject", "=", "$", "object", ";", "return", "$", "proxy", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot create proxy from unknown object\"", ")", ";", "}", "}" ]
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", "argument", "if", "already", "an", "PersistentObjectProxy", "instance", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/PersistentObjectProxy.php#L44-L56
26,847
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", "(", ")", ")", ";", "$", "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", "]", ")", ";", "}" ]
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
26,848
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'", ")", ")", "{", "$", "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", "(", ")", ";", "}" ]
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
26,849
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
26,850
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", ".", "$", "cacheDir", ".", "'cache/'", ")", ";", "$", "fileUtil", "=", "new", "FileUtil", "(", ")", ";", "$", "fileUtil", "->", "mkdirRec", "(", "$", "this", "->", "view", "->", "getCompileDir", "(", ")", ")", ";", "$", "fileUtil", "->", "mkdirRec", "(", "$", "this", "->", "view", "->", "getCacheDir", "(", ")", ")", ";", "}" ]
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
26,851
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", "(", ")", ";", "$", "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'", ")", ";", "}" ]
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
26,852
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", "(", ")", ";", "$", "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'", ")", ";", "}" ]
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
26,853
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", "(", ")", ";", "// 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'", ")", ";", "}" ]
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
26,854
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", "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", ")", ";", "}" ]
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
26,855
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", "=", "$", "this", "->", "getPermissionManager", "(", ")", ";", "foreach", "(", "$", "this", "->", "tempPermissions", "as", "$", "permission", ")", "{", "$", "permissionManager", "->", "removeTempPermission", "(", "$", "permission", ")", ";", "}", "}", "}" ]
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
26,856
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", "->", "call", "(", "$", "request", ")", ";", "return", "$", "response", ";", "}", "return", "ObjectFactory", "::", "getNewInstance", "(", "'response'", ")", ";", "}" ]
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
26,857
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'", ")", ";", "$", "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", "]", ";", "}" ]
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
26,858
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'", ")", ";", "$", "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", "]", ";", "}" ]
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
26,859
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", ")", ";", "$", "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", ";", "}" ]
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
26,860
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", "=", "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", ";", "}" ]
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
26,861
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
26,862
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", "->", "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", ";", "}" ]
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
26,863
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", ")", ".", "\"/\"", ".", "$", "anchorOID", "->", "__toString", "(", ")", ";", "if", "(", "$", "anchorName", "!=", "null", ")", "{", "$", "str", ".=", "\"#\"", ".", "$", "anchorName", ";", "}", "return", "$", "str", ";", "}" ]
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
26,864
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", "(", "$", "matches", "[", "1", "]", ")", ">", "0", ")", "{", "$", "oid", "=", "$", "matches", "[", "1", "]", "[", "0", "]", ";", "return", "ObjectId", "::", "parse", "(", "$", "oid", ")", ";", "}", "return", "null", ";", "}" ]
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
26,865
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", "(", "$", "matches", "[", "1", "]", ")", ">", "0", ")", "{", "$", "name", "=", "$", "matches", "[", "1", "]", "[", "0", "]", ";", "return", "$", "name", ";", "}", "return", "null", ";", "}" ]
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
26,866
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'", ")", ";", "$", "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", ";", "}" ]
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
26,867
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 a string. \"%s\" passed.'", ",", "gettype", "(", "$", "vatNumber", ")", ")", ")", ";", "}", "$", "this", "->", "vatNumber", "=", "$", "vatNumber", ";", "}" ]
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
26,868
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", "(", "$", "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\"", ")", ";", "}", "}" ]
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
26,869
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", ",", "$", "statusCode", ",", "$", "message", ")", ";", "return", "$", "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
26,870
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", "instanceof", "AuthorizationException", ")", "{", "return", "self", "::", "get", "(", "PERMISSION_DENIED", ")", ";", "}", "return", "self", "::", "getGeneral", "(", "$", "ex", "->", "getMessage", "(", ")", ")", ";", "}" ]
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
26,871
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", "(", "!", "$", "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", ";", "}" ]
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", "all", "nodes", "of", "the", "given", "type", "will", "be", "selected", "." ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/application/controller/ListController.php#L160-L182
26,872
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", "(", "$", "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", ")", ";", "}", "}" ]
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
26,873
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", "=", "$", "request", "->", "withHeader", "(", "'Authorization'", ",", "'Bearer '", ".", "$", "apiKey", ")", ";", "}", "return", "$", "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
26,874
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", ")", ";", "$", "end", "=", "'</'", ".", "str_replace", "(", "[", "'<'", ",", "'>'", "]", ",", "''", ",", "$", "tmp", "[", "0", "]", ")", ".", "'>'", ";", "// Assemble the document:", "return", "$", "start", ".", "$", "innerXML", ".", "$", "end", ";", "}" ]
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
26,875
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", "=", "$", "id", ";", "}", "}" ]
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
26,876
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", "(", "$", "this", "->", "innerXML", ")", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "deletedIds", ")", ")", "{", "$", "this", "->", "saveDeletedRecords", "(", "$", "this", "->", "deletedIds", ")", ";", "}", "}" ]
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
26,877
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 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", ";", "}" ]
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
26,878
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", "::", "getCacheDir", "(", "$", "imageFile", ")", ";", "return", "self", "::", "makeRelative", "(", "$", "directory", ".", "(", "strlen", "(", "$", "width", ")", ">", "0", "?", "$", "width", ".", "'-'", ":", "''", ")", ".", "$", "baseName", ")", ";", "}" ]
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
26,879
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", "::", "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", ")", ";", "}", "}", "}", "}", "}" ]
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
26,880
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", "(", "$", "imageFile", ",", "strlen", "(", "$", "mediaRoot", ")", ")", ")", ".", "'/'", ";", "}" ]
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
26,881
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'", ",", "'Media'", ")", ";", "return", "self", "::", "makeRelative", "(", "$", "mediaRootAbs", ")", ";", "}" ]
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
26,882
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", "(", "$", "_SERVER", "[", "'SCRIPT_FILENAME'", "]", ")", ")", ".", "'/'", ";", "}", "return", "URIUtil", "::", "makeRelative", "(", "$", "location", ",", "self", "::", "$", "scriptDirAbs", ")", ";", "}" ]
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
26,883
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", "(", "$", "width", ")", ";", "$", "image", "->", "save", "(", "$", "destFile", ")", ";", "}" ]
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
26,884
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", "=", "(", "$", "maxMultiplicity", ">", "1", "||", "$", "maxMultiplicity", "==", "'unbounded'", ")", ";", "}", "return", "$", "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
26,885
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", "]", ",", "'delete'", ")", ";", "file_put_contents", "(", "$", "filename", ",", "implode", "(", "\"\\n\"", ",", "$", "ids", ")", ")", ";", "}" ]
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
26,886
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 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", ";", "}" ]
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
26,887
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", "[", "$", "validateTypeName", "]", ")", ")", "{", "throw", "new", "ConfigurationException", "(", "\"Configuration section 'Validators' does not contain a validator named: \"", ".", "$", "validateTypeName", ")", ";", "}", "return", "$", "validatorTypes", "[", "$", "validateTypeName", "]", ";", "}" ]
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
26,888
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", "::", "$", "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", ";", "}" ]
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
26,889
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", "::", "$", "logger", "->", "debug", "(", "\"Register new object: \"", ".", "$", "key", ")", ";", "}", "$", "this", "->", "newObjects", "[", "$", "key", "]", "=", "$", "object", ";", "$", "this", "->", "observedObjects", "[", "$", "key", "]", "=", "$", "object", ";", "return", "$", "object", ";", "}" ]
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
26,890
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", "(", "$", "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", ";", "}" ]
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
26,891
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", "(", ")", "]", ")", ";", "}", "$", "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", "=", "[", "]", ";", "}" ]
Clear all internal
[ "Clear", "all", "internal" ]
2542b8d4139464d39a9a8ce8a954dfecf700c41b
https://github.com/iherwig/wcmf/blob/2542b8d4139464d39a9a8ce8a954dfecf700c41b/src/wcmf/lib/persistence/impl/DefaultTransaction.php#L385-L407
26,892
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", "(", "$", "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", ";", "}" ]
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
26,893
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", ")", "{", "$", "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", ";", "}" ]
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
26,894
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", ")", "{", "$", "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", ";", "}" ]
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
26,895
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", "(", ")", ";", "}", "return", "$", "str", ";", "}" ]
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
26,896
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", "=", "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", ",", "]", ";", "}" ]
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
26,897
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", "$", "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", "(", ")", "]", ";", "}" ]
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
26,898
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", "$", "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", ";", "}" ]
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
26,899
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", "=", "[", "]", ";", "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", ";", "}" ]
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