repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
smasty/Neevo
src/Neevo/Manager.php
Manager.loadFile
public function loadFile($filename){ $this->connection->connect(); $abort = ignore_user_abort(); @set_time_limit(0); ignore_user_abort(true); $handle = @fopen($filename, 'r'); if($handle === false){ ignore_user_abort($abort); throw new NeevoException("Cannot open file '$filename' for SQL import."); } $sql = ''; $count = 0; while(!feof($handle)){ $content = fgets($handle); $sql .= $content; if(substr(rtrim($content), -1) === ';'){ // Passed directly to driver without logging. $this->connection->getDriver()->runQuery($sql); $sql = ''; $count++; } } if(trim($sql)){ $this->connection->getDriver()->runQuery($sql); $count++; } fclose($handle); ignore_user_abort($abort); return $count; }
php
public function loadFile($filename){ $this->connection->connect(); $abort = ignore_user_abort(); @set_time_limit(0); ignore_user_abort(true); $handle = @fopen($filename, 'r'); if($handle === false){ ignore_user_abort($abort); throw new NeevoException("Cannot open file '$filename' for SQL import."); } $sql = ''; $count = 0; while(!feof($handle)){ $content = fgets($handle); $sql .= $content; if(substr(rtrim($content), -1) === ';'){ // Passed directly to driver without logging. $this->connection->getDriver()->runQuery($sql); $sql = ''; $count++; } } if(trim($sql)){ $this->connection->getDriver()->runQuery($sql); $count++; } fclose($handle); ignore_user_abort($abort); return $count; }
[ "public", "function", "loadFile", "(", "$", "filename", ")", "{", "$", "this", "->", "connection", "->", "connect", "(", ")", ";", "$", "abort", "=", "ignore_user_abort", "(", ")", ";", "@", "set_time_limit", "(", "0", ")", ";", "ignore_user_abort", "(",...
Imports a SQL dump from given file. Based on implementation in Nette\Database. @copyright 2004 David Grudl, http://davidgrudl.com @license New BSD license @param string $filename @return int Number of executed commands
[ "Imports", "a", "SQL", "dump", "from", "given", "file", ".", "Based", "on", "implementation", "in", "Nette", "\\", "Database", "." ]
3a1bf7e8ce24d453bb27dca3a9aca86852789f11
https://github.com/smasty/Neevo/blob/3a1bf7e8ce24d453bb27dca3a9aca86852789f11/src/Neevo/Manager.php#L152-L183
train
smasty/Neevo
src/Neevo/Manager.php
Manager.attachObserver
public function attachObserver(ObserverInterface $observer, $event){ $this->observers->attach($observer, $event); $this->connection->attachObserver($observer, $event); $e = new NeevoException; $e->attachObserver($observer, $event); }
php
public function attachObserver(ObserverInterface $observer, $event){ $this->observers->attach($observer, $event); $this->connection->attachObserver($observer, $event); $e = new NeevoException; $e->attachObserver($observer, $event); }
[ "public", "function", "attachObserver", "(", "ObserverInterface", "$", "observer", ",", "$", "event", ")", "{", "$", "this", "->", "observers", "->", "attach", "(", "$", "observer", ",", "$", "event", ")", ";", "$", "this", "->", "connection", "->", "att...
Attaches an observer for debugging. @param ObserverInterface $observer @param int $event Event to attach the observer to.
[ "Attaches", "an", "observer", "for", "debugging", "." ]
3a1bf7e8ce24d453bb27dca3a9aca86852789f11
https://github.com/smasty/Neevo/blob/3a1bf7e8ce24d453bb27dca3a9aca86852789f11/src/Neevo/Manager.php#L227-L232
train
smasty/Neevo
src/Neevo/Manager.php
Manager.detachObserver
public function detachObserver(ObserverInterface $observer){ $this->connection->detachObserver($observer); $this->observers->detach($observer); $e = new NeevoException; $e->detachObserver($observer); }
php
public function detachObserver(ObserverInterface $observer){ $this->connection->detachObserver($observer); $this->observers->detach($observer); $e = new NeevoException; $e->detachObserver($observer); }
[ "public", "function", "detachObserver", "(", "ObserverInterface", "$", "observer", ")", "{", "$", "this", "->", "connection", "->", "detachObserver", "(", "$", "observer", ")", ";", "$", "this", "->", "observers", "->", "detach", "(", "$", "observer", ")", ...
Detaches given observer. @param ObserverInterface $observer
[ "Detaches", "given", "observer", "." ]
3a1bf7e8ce24d453bb27dca3a9aca86852789f11
https://github.com/smasty/Neevo/blob/3a1bf7e8ce24d453bb27dca3a9aca86852789f11/src/Neevo/Manager.php#L239-L244
train
smasty/Neevo
src/Neevo/Manager.php
Manager.updateStatus
public function updateStatus(ObservableInterface $subject, $event){ $this->last = (string) $subject; $this->queries++; }
php
public function updateStatus(ObservableInterface $subject, $event){ $this->last = (string) $subject; $this->queries++; }
[ "public", "function", "updateStatus", "(", "ObservableInterface", "$", "subject", ",", "$", "event", ")", "{", "$", "this", "->", "last", "=", "(", "string", ")", "$", "subject", ";", "$", "this", "->", "queries", "++", ";", "}" ]
Receives update from observable subject. @param ObservableInterface $subject @param int $event Event type
[ "Receives", "update", "from", "observable", "subject", "." ]
3a1bf7e8ce24d453bb27dca3a9aca86852789f11
https://github.com/smasty/Neevo/blob/3a1bf7e8ce24d453bb27dca3a9aca86852789f11/src/Neevo/Manager.php#L264-L267
train
smasty/Neevo
src/Neevo/Manager.php
Manager.highlightSql
public static function highlightSql($sql){ $keywords1 = 'SELECT|UPDATE|INSERT\s+INTO|DELETE|FROM|VALUES|SET|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|(?:LEFT\s+|RIGHT\s+|INNER\s+)?JOIN'; $keywords2 = 'RANDOM|RAND|ASC|DESC|USING|AND|OR|ON|IN|IS|NOT|NULL|LIKE|TRUE|FALSE|AS'; $sql = str_replace("\\'", '\\&#39;', $sql); $sql = preg_replace_callback("~(/\\*.*\\*/)|($keywords1)|($keywords2)|('[^']+'|[0-9]+)~", 'self::_highlightCallback', $sql); $sql = str_replace('\\&#39;', "\\'", $sql); return '<pre style="color:#555" class="sql-dump">' . trim($sql) . "</pre>\n"; }
php
public static function highlightSql($sql){ $keywords1 = 'SELECT|UPDATE|INSERT\s+INTO|DELETE|FROM|VALUES|SET|WHERE|HAVING|GROUP\s+BY|ORDER\s+BY|LIMIT|OFFSET|(?:LEFT\s+|RIGHT\s+|INNER\s+)?JOIN'; $keywords2 = 'RANDOM|RAND|ASC|DESC|USING|AND|OR|ON|IN|IS|NOT|NULL|LIKE|TRUE|FALSE|AS'; $sql = str_replace("\\'", '\\&#39;', $sql); $sql = preg_replace_callback("~(/\\*.*\\*/)|($keywords1)|($keywords2)|('[^']+'|[0-9]+)~", 'self::_highlightCallback', $sql); $sql = str_replace('\\&#39;', "\\'", $sql); return '<pre style="color:#555" class="sql-dump">' . trim($sql) . "</pre>\n"; }
[ "public", "static", "function", "highlightSql", "(", "$", "sql", ")", "{", "$", "keywords1", "=", "'SELECT|UPDATE|INSERT\\s+INTO|DELETE|FROM|VALUES|SET|WHERE|HAVING|GROUP\\s+BY|ORDER\\s+BY|LIMIT|OFFSET|(?:LEFT\\s+|RIGHT\\s+|INNER\\s+)?JOIN'", ";", "$", "keywords2", "=", "'RANDOM|RA...
Highlights given SQL code. @param string $sql @return string
[ "Highlights", "given", "SQL", "code", "." ]
3a1bf7e8ce24d453bb27dca3a9aca86852789f11
https://github.com/smasty/Neevo/blob/3a1bf7e8ce24d453bb27dca3a9aca86852789f11/src/Neevo/Manager.php#L302-L310
train
CeusMedia/Common
src/Alg/Time/Clock.php
Alg_Time_Clock.getTime
public function getTime( $base = 3, $round = 3 ) { $time = $this->microtimeStop - $this->microtimeStart; $time = $time * pow( 10, $base ); $time = round( $time, $round ); return $time; }
php
public function getTime( $base = 3, $round = 3 ) { $time = $this->microtimeStop - $this->microtimeStart; $time = $time * pow( 10, $base ); $time = round( $time, $round ); return $time; }
[ "public", "function", "getTime", "(", "$", "base", "=", "3", ",", "$", "round", "=", "3", ")", "{", "$", "time", "=", "$", "this", "->", "microtimeStop", "-", "$", "this", "->", "microtimeStart", ";", "$", "time", "=", "$", "time", "*", "pow", "(...
Calculates the time difference between start and stop in microseconds. @access public @param int $base Time Base ( 0 - sec | 3 - msec | 6 - µsec) @param int $round Numbers after dot @return string
[ "Calculates", "the", "time", "difference", "between", "start", "and", "stop", "in", "microseconds", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/Alg/Time/Clock.php#L77-L83
train
CeusMedia/Common
src/Alg/Time/Clock.php
Alg_Time_Clock.stop
public function stop( $base = 3, $round = 3 ) { $this->microtimeStop = microtime( TRUE ); return $this->getTime( $base, $round ); }
php
public function stop( $base = 3, $round = 3 ) { $this->microtimeStop = microtime( TRUE ); return $this->getTime( $base, $round ); }
[ "public", "function", "stop", "(", "$", "base", "=", "3", ",", "$", "round", "=", "3", ")", "{", "$", "this", "->", "microtimeStop", "=", "microtime", "(", "TRUE", ")", ";", "return", "$", "this", "->", "getTime", "(", "$", "base", ",", "$", "rou...
Stops the watch and return the time difference between start and stop. @access public @param int $base Time Base ( 0 - sec | 3 - msec | 6 - µsec) @param int $round Numbers after dot @return string
[ "Stops", "the", "watch", "and", "return", "the", "time", "difference", "between", "start", "and", "stop", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/Alg/Time/Clock.php#L112-L116
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.exec
public function exec( $statement ){ $this->logStatement( $statement ); try{ $this->numberExecutes++; $this->numberStatements++; return parent::exec( $statement ); } catch( \PDOException $e ){ $this->logError( $e, $statement ); // logs Error and throws SQL Exception } }
php
public function exec( $statement ){ $this->logStatement( $statement ); try{ $this->numberExecutes++; $this->numberStatements++; return parent::exec( $statement ); } catch( \PDOException $e ){ $this->logError( $e, $statement ); // logs Error and throws SQL Exception } }
[ "public", "function", "exec", "(", "$", "statement", ")", "{", "$", "this", "->", "logStatement", "(", "$", "statement", ")", ";", "try", "{", "$", "this", "->", "numberExecutes", "++", ";", "$", "this", "->", "numberStatements", "++", ";", "return", "...
Executes a Statement and returns Number of affected Rows. @access public @param string $statement SQL Statement to execute @return int
[ "Executes", "a", "Statement", "and", "returns", "Number", "of", "affected", "Rows", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L122-L132
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.getTables
public function getTables( $prefix = NULL ){ $query = "SHOW TABLES" . ( $prefix ? " LIKE '".$prefix."%'" : "" ); return parent::query( $query )->fetchAll( PDO::FETCH_COLUMN ); }
php
public function getTables( $prefix = NULL ){ $query = "SHOW TABLES" . ( $prefix ? " LIKE '".$prefix."%'" : "" ); return parent::query( $query )->fetchAll( PDO::FETCH_COLUMN ); }
[ "public", "function", "getTables", "(", "$", "prefix", "=", "NULL", ")", "{", "$", "query", "=", "\"SHOW TABLES\"", ".", "(", "$", "prefix", "?", "\" LIKE '\"", ".", "$", "prefix", ".", "\"%'\"", ":", "\"\"", ")", ";", "return", "parent", "::", "query"...
Returns list of tables in database. With given prefix the returned list will be filtered. @access public @param string $prefix Table prefix to filter by (optional). @return array
[ "Returns", "list", "of", "tables", "in", "database", ".", "With", "given", "prefix", "the", "returned", "list", "will", "be", "filtered", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L154-L157
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.logError
protected function logError( PDOException $exception, $statement ){ if( !$this->logFileErrors ) return; // throw $exception; $info = $exception->errorInfo; $sqlError = isset( $info[2] ) ? $info[2] : NULL; $sqlCode = $info[1]; $pdoCode = $info[0]; $message = $exception->getMessage(); $statement = preg_replace( "@\r?\n@", " ", $statement ); $statement = preg_replace( "@ +@", " ", $statement ); $note = self::$errorTemplate; $note = str_replace( "{time}", time(), $note ); $note = str_replace( "{sqlError}", $sqlError, $note ); $note = str_replace( "{sqlCode}", $sqlCode, $note ); $note = str_replace( "{pdoCode}", $pdoCode, $note ); $note = str_replace( "{message}", $message, $note ); $note = str_replace( "{statement}", $statement, $note ); error_log( $note, 3, $this->logFileErrors ); throw new \Exception_SQL( $sqlError, $sqlCode, $pdoCode ); }
php
protected function logError( PDOException $exception, $statement ){ if( !$this->logFileErrors ) return; // throw $exception; $info = $exception->errorInfo; $sqlError = isset( $info[2] ) ? $info[2] : NULL; $sqlCode = $info[1]; $pdoCode = $info[0]; $message = $exception->getMessage(); $statement = preg_replace( "@\r?\n@", " ", $statement ); $statement = preg_replace( "@ +@", " ", $statement ); $note = self::$errorTemplate; $note = str_replace( "{time}", time(), $note ); $note = str_replace( "{sqlError}", $sqlError, $note ); $note = str_replace( "{sqlCode}", $sqlCode, $note ); $note = str_replace( "{pdoCode}", $pdoCode, $note ); $note = str_replace( "{message}", $message, $note ); $note = str_replace( "{statement}", $statement, $note ); error_log( $note, 3, $this->logFileErrors ); throw new \Exception_SQL( $sqlError, $sqlCode, $pdoCode ); }
[ "protected", "function", "logError", "(", "PDOException", "$", "exception", ",", "$", "statement", ")", "{", "if", "(", "!", "$", "this", "->", "logFileErrors", ")", "return", ";", "//\t\t\tthrow $exception;", "$", "info", "=", "$", "exception", "->", "error...
Notes Information from PDO Exception in Error Log File and throw SQL Exception. @access protected @param PDOException $e PDO Exception thrown by invalid SQL Statement @param string $statement SQL Statement which originated PDO Exception @return void
[ "Notes", "Information", "from", "PDO", "Exception", "in", "Error", "Log", "File", "and", "throw", "SQL", "Exception", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L166-L188
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.logStatement
protected function logStatement( $statement ){ if( !$this->logFileStatements ) return; $statement = preg_replace( "@(\r)?\n@", " ", $statement ); $message = time()." ".getEnv( 'REMOTE_ADDR' )." ".$statement."\n"; error_log( $message, 3, $this->logFileStatements); }
php
protected function logStatement( $statement ){ if( !$this->logFileStatements ) return; $statement = preg_replace( "@(\r)?\n@", " ", $statement ); $message = time()." ".getEnv( 'REMOTE_ADDR' )." ".$statement."\n"; error_log( $message, 3, $this->logFileStatements); }
[ "protected", "function", "logStatement", "(", "$", "statement", ")", "{", "if", "(", "!", "$", "this", "->", "logFileStatements", ")", "return", ";", "$", "statement", "=", "preg_replace", "(", "\"@(\\r)?\\n@\"", ",", "\" \"", ",", "$", "statement", ")", "...
Notes a SQL Statement in Statement Log File. @access protected @param string $statement SQL Statement @return void
[ "Notes", "a", "SQL", "Statement", "in", "Statement", "Log", "File", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L196-L202
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.rollBack
public function rollBack(){ if( !$this->openTransactions ) // there has been an inner RollBack or no Transaction was opened return FALSE; // ignore Commit if( $this->openTransactions == 1 ){ // only 1 Transaction open parent::rollBack(); // roll back Transaction $this->innerTransactionFail = FALSE; // forget about failed inner Transactions } else $this->innerTransactionFail = TRUE; // note about failed inner Transactions $this->openTransactions--; // decrease Transaction Counter return TRUE; }
php
public function rollBack(){ if( !$this->openTransactions ) // there has been an inner RollBack or no Transaction was opened return FALSE; // ignore Commit if( $this->openTransactions == 1 ){ // only 1 Transaction open parent::rollBack(); // roll back Transaction $this->innerTransactionFail = FALSE; // forget about failed inner Transactions } else $this->innerTransactionFail = TRUE; // note about failed inner Transactions $this->openTransactions--; // decrease Transaction Counter return TRUE; }
[ "public", "function", "rollBack", "(", ")", "{", "if", "(", "!", "$", "this", "->", "openTransactions", ")", "// there has been an inner RollBack or no Transaction was opened", "return", "FALSE", ";", "// ignore Commit", "if", "(", "$", "this", "->", "openTransactio...
Rolls back a Transaction. @access public @return bool
[ "Rolls", "back", "a", "Transaction", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L227-L238
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.setErrorLogFile
public function setErrorLogFile( $fileName ){ $this->logFileErrors = $fileName; if( $fileName && !file_exists( dirname( $fileName ) ) ) mkDir( dirname( $fileName ), 0700, TRUE ); }
php
public function setErrorLogFile( $fileName ){ $this->logFileErrors = $fileName; if( $fileName && !file_exists( dirname( $fileName ) ) ) mkDir( dirname( $fileName ), 0700, TRUE ); }
[ "public", "function", "setErrorLogFile", "(", "$", "fileName", ")", "{", "$", "this", "->", "logFileErrors", "=", "$", "fileName", ";", "if", "(", "$", "fileName", "&&", "!", "file_exists", "(", "dirname", "(", "$", "fileName", ")", ")", ")", "mkDir", ...
Sets File Name of Error Log. @access public @param string $fileName File Name of Statement Error File @return void
[ "Sets", "File", "Name", "of", "Error", "Log", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L246-L250
train
CeusMedia/Common
src/DB/PDO/Connection.php
DB_PDO_Connection.setStatementLogFile
public function setStatementLogFile( $fileName ){ $this->logFileStatements = $fileName; if( $fileName && !file_exists( dirname( $fileName ) ) ) mkDir( dirname( $fileName ), 0700, TRUE ); }
php
public function setStatementLogFile( $fileName ){ $this->logFileStatements = $fileName; if( $fileName && !file_exists( dirname( $fileName ) ) ) mkDir( dirname( $fileName ), 0700, TRUE ); }
[ "public", "function", "setStatementLogFile", "(", "$", "fileName", ")", "{", "$", "this", "->", "logFileStatements", "=", "$", "fileName", ";", "if", "(", "$", "fileName", "&&", "!", "file_exists", "(", "dirname", "(", "$", "fileName", ")", ")", ")", "mk...
Sets File Name of Statement Log. @access public @param string $fileName File Name of Statement Log File @return void
[ "Sets", "File", "Name", "of", "Statement", "Log", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/DB/PDO/Connection.php#L258-L262
train
CeusMedia/Common
src/Net/Memory/Cache.php
Net_Memory_Cache.has
public function has( $key ) { $value = $this->store->get( $key ); if( $value === FALSE ) return $this->store->replace( $key, FALSE ) ? TRUE : FALSE; return TRUE; }
php
public function has( $key ) { $value = $this->store->get( $key ); if( $value === FALSE ) return $this->store->replace( $key, FALSE ) ? TRUE : FALSE; return TRUE; }
[ "public", "function", "has", "(", "$", "key", ")", "{", "$", "value", "=", "$", "this", "->", "store", "->", "get", "(", "$", "key", ")", ";", "if", "(", "$", "value", "===", "FALSE", ")", "return", "$", "this", "->", "store", "->", "replace", ...
Indicates whether a Pair is stored by its Key. @access public @param string $key Key of Cache Pair @return bool
[ "Indicates", "whether", "a", "Pair", "is", "stored", "by", "its", "Key", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/Net/Memory/Cache.php#L122-L128
train
CeusMedia/Common
src/Net/Memory/Cache.php
Net_Memory_Cache.set
public function set( $key, $value ) { return $this->store->set( $key, $value, 0, $this->expires ); }
php
public function set( $key, $value ) { return $this->store->set( $key, $value, 0, $this->expires ); }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "return", "$", "this", "->", "store", "->", "set", "(", "$", "key", ",", "$", "value", ",", "0", ",", "$", "this", "->", "expires", ")", ";", "}" ]
Stores or replaces a Pair. @access public @param string $key Key of Cache Pair @param int $value Value to store @return bool
[ "Stores", "or", "replaces", "a", "Pair", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/Net/Memory/Cache.php#L160-L163
train
meritoo/common-library
src/Utilities/MimeTypes.php
MimeTypes.getExtensions
public static function getExtensions(array $mimesTypes, $asUpperCase = false) { if (empty($mimesTypes)) { return []; } $extensions = []; foreach ($mimesTypes as $mimeType) { $extension = self::getExtension($mimeType); /* * No extension for given mime type? * Nothing to do */ if (empty($extension)) { continue; } if ($asUpperCase) { if (is_array($extension)) { array_walk($extension, function (&$value) { $value = strtoupper($value); }); } else { $extension = strtoupper($extension); } } $extensions[$mimeType] = $extension; } return $extensions; }
php
public static function getExtensions(array $mimesTypes, $asUpperCase = false) { if (empty($mimesTypes)) { return []; } $extensions = []; foreach ($mimesTypes as $mimeType) { $extension = self::getExtension($mimeType); /* * No extension for given mime type? * Nothing to do */ if (empty($extension)) { continue; } if ($asUpperCase) { if (is_array($extension)) { array_walk($extension, function (&$value) { $value = strtoupper($value); }); } else { $extension = strtoupper($extension); } } $extensions[$mimeType] = $extension; } return $extensions; }
[ "public", "static", "function", "getExtensions", "(", "array", "$", "mimesTypes", ",", "$", "asUpperCase", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "mimesTypes", ")", ")", "{", "return", "[", "]", ";", "}", "$", "extensions", "=", "[", "...
Returns extensions for given mimes types @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg'] @param bool $asUpperCase (optional) If is set to true, extensions are returned as upper case. Otherwise - lower case. @return array
[ "Returns", "extensions", "for", "given", "mimes", "types" ]
b166b8b805ae97c15688d27323cae8976bd0f6dc
https://github.com/meritoo/common-library/blob/b166b8b805ae97c15688d27323cae8976bd0f6dc/src/Utilities/MimeTypes.php#L690-L723
train
meritoo/common-library
src/Utilities/MimeTypes.php
MimeTypes.getExtension
public static function getExtension($mimeType) { if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes, true)) { $data = Arrays::setKeysAsValues(self::$mimeTypes, false); return $data[$mimeType]; } return ''; }
php
public static function getExtension($mimeType) { if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes, true)) { $data = Arrays::setKeysAsValues(self::$mimeTypes, false); return $data[$mimeType]; } return ''; }
[ "public", "static", "function", "getExtension", "(", "$", "mimeType", ")", "{", "if", "(", "is_string", "(", "$", "mimeType", ")", "&&", "in_array", "(", "$", "mimeType", ",", "self", "::", "$", "mimeTypes", ",", "true", ")", ")", "{", "$", "data", "...
Returns extension for given mime type @param string $mimeType The mime type, e.g. "video/mpeg" @return array|string
[ "Returns", "extension", "for", "given", "mime", "type" ]
b166b8b805ae97c15688d27323cae8976bd0f6dc
https://github.com/meritoo/common-library/blob/b166b8b805ae97c15688d27323cae8976bd0f6dc/src/Utilities/MimeTypes.php#L731-L740
train
meritoo/common-library
src/Utilities/MimeTypes.php
MimeTypes.getMimeType
public static function getMimeType($filePath) { /* * The file does not exist? * Nothing to do */ if (!is_string($filePath) || !is_readable($filePath)) { return ''; } // 1st possibility: the finfo class if (class_exists('finfo')) { $finfo = new \finfo(); return $finfo->file($filePath, FILEINFO_MIME_TYPE); } // 2nd possibility: the mime_content_type function if (function_exists('mime_content_type')) { return mime_content_type($filePath); } // Oops, there is no possibility to read the mime type $template = 'Neither \'finfo\' class nor \'mime_content_type\' function exists. There is no way to read the' . ' mime type of file \'%s\'.'; $message = sprintf($template, $filePath); throw new \RuntimeException($message); }
php
public static function getMimeType($filePath) { /* * The file does not exist? * Nothing to do */ if (!is_string($filePath) || !is_readable($filePath)) { return ''; } // 1st possibility: the finfo class if (class_exists('finfo')) { $finfo = new \finfo(); return $finfo->file($filePath, FILEINFO_MIME_TYPE); } // 2nd possibility: the mime_content_type function if (function_exists('mime_content_type')) { return mime_content_type($filePath); } // Oops, there is no possibility to read the mime type $template = 'Neither \'finfo\' class nor \'mime_content_type\' function exists. There is no way to read the' . ' mime type of file \'%s\'.'; $message = sprintf($template, $filePath); throw new \RuntimeException($message); }
[ "public", "static", "function", "getMimeType", "(", "$", "filePath", ")", "{", "/*\n * The file does not exist?\n * Nothing to do\n */", "if", "(", "!", "is_string", "(", "$", "filePath", ")", "||", "!", "is_readable", "(", "$", "filePath", ")"...
Returns mime type of given file @param string $filePath Path of the file to check @throws \RuntimeException @return string
[ "Returns", "mime", "type", "of", "given", "file" ]
b166b8b805ae97c15688d27323cae8976bd0f6dc
https://github.com/meritoo/common-library/blob/b166b8b805ae97c15688d27323cae8976bd0f6dc/src/Utilities/MimeTypes.php#L762-L791
train
meritoo/common-library
src/Utilities/MimeTypes.php
MimeTypes.isImage
public static function isImage($mimeType) { if (in_array($mimeType, self::$mimeTypes, true)) { return (bool)preg_match('|^image/.+$|', $mimeType); } return false; }
php
public static function isImage($mimeType) { if (in_array($mimeType, self::$mimeTypes, true)) { return (bool)preg_match('|^image/.+$|', $mimeType); } return false; }
[ "public", "static", "function", "isImage", "(", "$", "mimeType", ")", "{", "if", "(", "in_array", "(", "$", "mimeType", ",", "self", "::", "$", "mimeTypes", ",", "true", ")", ")", "{", "return", "(", "bool", ")", "preg_match", "(", "'|^image/.+$|'", ",...
Returns information whether the given file type is an image @param string $mimeType The mime type of file @return bool
[ "Returns", "information", "whether", "the", "given", "file", "type", "is", "an", "image" ]
b166b8b805ae97c15688d27323cae8976bd0f6dc
https://github.com/meritoo/common-library/blob/b166b8b805ae97c15688d27323cae8976bd0f6dc/src/Utilities/MimeTypes.php#L799-L806
train
CeusMedia/Common
src/XML/DOM/XPathQuery.php
XML_DOM_XPathQuery.loadFile
public function loadFile( $fileName ) { if( !file_exists( $fileName ) ) throw new Exception( 'XML File "'.$fileName.'" is not existing.' ); $this->document = new DOMDocument(); $this->document->load( $fileName ); $this->xPath = new DOMXpath( $this->document ); return true; }
php
public function loadFile( $fileName ) { if( !file_exists( $fileName ) ) throw new Exception( 'XML File "'.$fileName.'" is not existing.' ); $this->document = new DOMDocument(); $this->document->load( $fileName ); $this->xPath = new DOMXpath( $this->document ); return true; }
[ "public", "function", "loadFile", "(", "$", "fileName", ")", "{", "if", "(", "!", "file_exists", "(", "$", "fileName", ")", ")", "throw", "new", "Exception", "(", "'XML File \"'", ".", "$", "fileName", ".", "'\" is not existing.'", ")", ";", "$", "this", ...
Loads XML from File. @access public @param string $fileName File Name to load XML from @return bool
[ "Loads", "XML", "from", "File", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/XML/DOM/XPathQuery.php#L95-L103
train
CeusMedia/Common
src/XML/DOM/XPathQuery.php
XML_DOM_XPathQuery.loadUrl
public function loadUrl( $url ) { $options = array(); foreach( $this->getOptions() as $key => $value ) $options["CURLOPT_".strtoupper( $key )] = $value; $xml = Net_Reader::readUrl( $url, $options ); if( !$xml ) throw new Exception( 'No XML found for URL "'.$url.'".' ); $this->loadXml( $xml ); return true; }
php
public function loadUrl( $url ) { $options = array(); foreach( $this->getOptions() as $key => $value ) $options["CURLOPT_".strtoupper( $key )] = $value; $xml = Net_Reader::readUrl( $url, $options ); if( !$xml ) throw new Exception( 'No XML found for URL "'.$url.'".' ); $this->loadXml( $xml ); return true; }
[ "public", "function", "loadUrl", "(", "$", "url", ")", "{", "$", "options", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "getOptions", "(", ")", "as", "$", "key", "=>", "$", "value", ")", "$", "options", "[", "\"CURLOPT_\"", ".",...
Loads XML from URL. @access public @param string $url URL to load XML from @return bool @todo Error Handling
[ "Loads", "XML", "from", "URL", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/XML/DOM/XPathQuery.php#L112-L122
train
CeusMedia/Common
src/XML/DOM/XPathQuery.php
XML_DOM_XPathQuery.loadXml
public function loadXml( $xml ) { $this->document = new DOMDocument(); $validator = new XML_Validator(); if( !$validator->validate( $xml ) ){ $message = $validator->getErrorMessage(); throw new InvalidArgumentException( 'XML is invalid ('.$message.')' ); } $this->document->loadXml( $xml ); $this->xPath = new DOMXPath( $this->document ); }
php
public function loadXml( $xml ) { $this->document = new DOMDocument(); $validator = new XML_Validator(); if( !$validator->validate( $xml ) ){ $message = $validator->getErrorMessage(); throw new InvalidArgumentException( 'XML is invalid ('.$message.')' ); } $this->document->loadXml( $xml ); $this->xPath = new DOMXPath( $this->document ); }
[ "public", "function", "loadXml", "(", "$", "xml", ")", "{", "$", "this", "->", "document", "=", "new", "DOMDocument", "(", ")", ";", "$", "validator", "=", "new", "XML_Validator", "(", ")", ";", "if", "(", "!", "$", "validator", "->", "validate", "("...
Loads XML into XPath Parser. @access public @return void
[ "Loads", "XML", "into", "XPath", "Parser", "." ]
1138adf9341782a6284c05884989f7497532bcf4
https://github.com/CeusMedia/Common/blob/1138adf9341782a6284c05884989f7497532bcf4/src/XML/DOM/XPathQuery.php#L129-L139
train
sseffa/laravel-video-api
src/Sseffa/VideoApi/Services/Youtube.php
Youtube.getVideoList
public function getVideoList($id) { $this->setId($id); $list = array(); $data = $this->getData(str_replace('{key}', $this->key, $this->baseChannelUrl)); if(!isset($data->items)) { throw new \Exception("Video channel not found"); } foreach($data->items as $value) { $list[] = $this->getVideoDetail($value->contentDetails->videoId); } return $list; }
php
public function getVideoList($id) { $this->setId($id); $list = array(); $data = $this->getData(str_replace('{key}', $this->key, $this->baseChannelUrl)); if(!isset($data->items)) { throw new \Exception("Video channel not found"); } foreach($data->items as $value) { $list[] = $this->getVideoDetail($value->contentDetails->videoId); } return $list; }
[ "public", "function", "getVideoList", "(", "$", "id", ")", "{", "$", "this", "->", "setId", "(", "$", "id", ")", ";", "$", "list", "=", "array", "(", ")", ";", "$", "data", "=", "$", "this", "->", "getData", "(", "str_replace", "(", "'{key}'", ",...
Get Video List @param string $id @return array @throws \Exception
[ "Get", "Video", "List" ]
c8d653aad95cd85624aedce8b38e13e388fb283d
https://github.com/sseffa/laravel-video-api/blob/c8d653aad95cd85624aedce8b38e13e388fb283d/src/Sseffa/VideoApi/Services/Youtube.php#L100-L118
train
sseffa/laravel-video-api
src/Sseffa/VideoApi/Services/Youtube.php
Youtube._convert_time
public static function _convert_time($time) { $reference = new DateTimeImmutable; $endTime = $reference->add(new DateInterval($time)); return $endTime->getTimestamp() - $reference->getTimestamp(); }
php
public static function _convert_time($time) { $reference = new DateTimeImmutable; $endTime = $reference->add(new DateInterval($time)); return $endTime->getTimestamp() - $reference->getTimestamp(); }
[ "public", "static", "function", "_convert_time", "(", "$", "time", ")", "{", "$", "reference", "=", "new", "DateTimeImmutable", ";", "$", "endTime", "=", "$", "reference", "->", "add", "(", "new", "DateInterval", "(", "$", "time", ")", ")", ";", "return"...
Parse the YouTube timestamp to seconds @param string $time YouTube format timestamp @return integer Seconds
[ "Parse", "the", "YouTube", "timestamp", "to", "seconds" ]
c8d653aad95cd85624aedce8b38e13e388fb283d
https://github.com/sseffa/laravel-video-api/blob/c8d653aad95cd85624aedce8b38e13e388fb283d/src/Sseffa/VideoApi/Services/Youtube.php#L191-L197
train
josegonzalez/php-queuesadilla
src/josegonzalez/Queuesadilla/Worker/SequentialWorker.php
SequentialWorker.jobException
public function jobException(Event $event) { $data = $event->data(); $this->logger()->alert(sprintf('Exception: "%s"', $data['exception']->getMessage())); }
php
public function jobException(Event $event) { $data = $event->data(); $this->logger()->alert(sprintf('Exception: "%s"', $data['exception']->getMessage())); }
[ "public", "function", "jobException", "(", "Event", "$", "event", ")", "{", "$", "data", "=", "$", "event", "->", "data", "(", ")", ";", "$", "this", "->", "logger", "(", ")", "->", "alert", "(", "sprintf", "(", "'Exception: \"%s\"'", ",", "$", "data...
Event triggered on Worker.job.exception @param Event $event @return void
[ "Event", "triggered", "on", "Worker", ".", "job", ".", "exception" ]
437ddfde53931cc98155ee45c83449851bcd481b
https://github.com/josegonzalez/php-queuesadilla/blob/437ddfde53931cc98155ee45c83449851bcd481b/src/josegonzalez/Queuesadilla/Worker/SequentialWorker.php#L218-L222
train
josegonzalez/php-queuesadilla
src/josegonzalez/Queuesadilla/Event/EventManagerTrait.php
EventManagerTrait.eventManager
public function eventManager(EmitterInterface $eventManager = null) { if ($eventManager !== null) { $this->eventManager = $eventManager; } elseif (empty($this->eventManager)) { $this->eventManager = new EventManager(); } return $this->eventManager; }
php
public function eventManager(EmitterInterface $eventManager = null) { if ($eventManager !== null) { $this->eventManager = $eventManager; } elseif (empty($this->eventManager)) { $this->eventManager = new EventManager(); } return $this->eventManager; }
[ "public", "function", "eventManager", "(", "EmitterInterface", "$", "eventManager", "=", "null", ")", "{", "if", "(", "$", "eventManager", "!==", "null", ")", "{", "$", "this", "->", "eventManager", "=", "$", "eventManager", ";", "}", "elseif", "(", "empty...
Returns the League\Event\EmitterInterface manager instance for this object. You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will. @param \League\Event\EmitterInterface $eventManager the eventManager to set @return \League\Event\EmitterInterface
[ "Returns", "the", "League", "\\", "Event", "\\", "EmitterInterface", "manager", "instance", "for", "this", "object", "." ]
437ddfde53931cc98155ee45c83449851bcd481b
https://github.com/josegonzalez/php-queuesadilla/blob/437ddfde53931cc98155ee45c83449851bcd481b/src/josegonzalez/Queuesadilla/Event/EventManagerTrait.php#L37-L46
train
josegonzalez/php-queuesadilla
src/josegonzalez/Queuesadilla/Engine/PdoEngine.php
PdoEngine.cleanup
protected function cleanup($queue) { $sql = implode(" ", [ sprintf( 'SELECT id FROM %s', $this->quoteIdentifier($this->config('table')) ), sprintf('WHERE %s = ?', $this->quoteIdentifier('queue')), 'AND expires_at < ?' ]); $datetime = new DateTime; $dtFormatted = $datetime->format('Y-m-d H:i:s'); try { $sth = $this->connection()->prepare($sql); $sth->bindParam(1, $queue, PDO::PARAM_STR); $sth->bindParam(2, $dtFormatted, PDO::PARAM_STR); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); if (!empty($result)) { $this->reject([ 'id' => $result['id'], 'queue' => $queue ]); } } catch (PDOException $e) { $this->logger()->error($e->getMessage()); } }
php
protected function cleanup($queue) { $sql = implode(" ", [ sprintf( 'SELECT id FROM %s', $this->quoteIdentifier($this->config('table')) ), sprintf('WHERE %s = ?', $this->quoteIdentifier('queue')), 'AND expires_at < ?' ]); $datetime = new DateTime; $dtFormatted = $datetime->format('Y-m-d H:i:s'); try { $sth = $this->connection()->prepare($sql); $sth->bindParam(1, $queue, PDO::PARAM_STR); $sth->bindParam(2, $dtFormatted, PDO::PARAM_STR); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); if (!empty($result)) { $this->reject([ 'id' => $result['id'], 'queue' => $queue ]); } } catch (PDOException $e) { $this->logger()->error($e->getMessage()); } }
[ "protected", "function", "cleanup", "(", "$", "queue", ")", "{", "$", "sql", "=", "implode", "(", "\" \"", ",", "[", "sprintf", "(", "'SELECT id FROM %s'", ",", "$", "this", "->", "quoteIdentifier", "(", "$", "this", "->", "config", "(", "'table'", ")", ...
Check if expired jobs are present in the database and reject them @param string $queue name of the queue @return void
[ "Check", "if", "expired", "jobs", "are", "present", "in", "the", "database", "and", "reject", "them" ]
437ddfde53931cc98155ee45c83449851bcd481b
https://github.com/josegonzalez/php-queuesadilla/blob/437ddfde53931cc98155ee45c83449851bcd481b/src/josegonzalez/Queuesadilla/Engine/PdoEngine.php#L311-L342
train
josegonzalez/php-queuesadilla
src/josegonzalez/Queuesadilla/Engine/PdoEngine.php
PdoEngine.generatePopOrderSql
protected function generatePopOrderSql($options = []) { $orderPart = 'ORDER BY priority ASC'; if (isset($options['pop_order']) && $options['pop_order'] === self::POP_ORDER_FIFO) { $orderPart = 'ORDER BY created_at ASC'; } return $orderPart; }
php
protected function generatePopOrderSql($options = []) { $orderPart = 'ORDER BY priority ASC'; if (isset($options['pop_order']) && $options['pop_order'] === self::POP_ORDER_FIFO) { $orderPart = 'ORDER BY created_at ASC'; } return $orderPart; }
[ "protected", "function", "generatePopOrderSql", "(", "$", "options", "=", "[", "]", ")", "{", "$", "orderPart", "=", "'ORDER BY priority ASC'", ";", "if", "(", "isset", "(", "$", "options", "[", "'pop_order'", "]", ")", "&&", "$", "options", "[", "'pop_ord...
Generate ORDER sql @param array $options @return string @throws \InvalidArgumentException if the "pop_order" option is not valid or null
[ "Generate", "ORDER", "sql" ]
437ddfde53931cc98155ee45c83449851bcd481b
https://github.com/josegonzalez/php-queuesadilla/blob/437ddfde53931cc98155ee45c83449851bcd481b/src/josegonzalez/Queuesadilla/Engine/PdoEngine.php#L378-L386
train
bittools/skyhub-php
src/Api.php
Api.setAuthentication
public function setAuthentication($email, $apiKey) { $headers = [ self::HEADER_USER_EMAIL => $email, self::HEADER_API_KEY => $apiKey, ]; $this->service->setHeaders($headers, true, true); return $this; }
php
public function setAuthentication($email, $apiKey) { $headers = [ self::HEADER_USER_EMAIL => $email, self::HEADER_API_KEY => $apiKey, ]; $this->service->setHeaders($headers, true, true); return $this; }
[ "public", "function", "setAuthentication", "(", "$", "email", ",", "$", "apiKey", ")", "{", "$", "headers", "=", "[", "self", "::", "HEADER_USER_EMAIL", "=>", "$", "email", ",", "self", "::", "HEADER_API_KEY", "=>", "$", "apiKey", ",", "]", ";", "$", "...
Reset the authorization information and use the same instance of the API object to use different accounts. @param string $email @param string $apiKey @return $this
[ "Reset", "the", "authorization", "information", "and", "use", "the", "same", "instance", "of", "the", "API", "object", "to", "use", "different", "accounts", "." ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api.php#L84-L94
train
bittools/skyhub-php
src/Api/Handler/Request/Sales/OrderHandler.php
OrderHandler.orders
public function orders($page = 1, $perPage = 30, $saleSystem = null, array $statuses = []) { $filters = []; if (!is_null($saleSystem)) { $filters['sale_system'] = (string) $saleSystem; } if (!is_null($statuses)) { $filters['statuses'] = (array) $statuses; } $query = [ 'page' => (int) $page, 'per_page' => (int) $perPage, 'filters' => (array) $filters, ]; /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->get($this->baseUrlPath(null, $query)); return $responseHandler; }
php
public function orders($page = 1, $perPage = 30, $saleSystem = null, array $statuses = []) { $filters = []; if (!is_null($saleSystem)) { $filters['sale_system'] = (string) $saleSystem; } if (!is_null($statuses)) { $filters['statuses'] = (array) $statuses; } $query = [ 'page' => (int) $page, 'per_page' => (int) $perPage, 'filters' => (array) $filters, ]; /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->get($this->baseUrlPath(null, $query)); return $responseHandler; }
[ "public", "function", "orders", "(", "$", "page", "=", "1", ",", "$", "perPage", "=", "30", ",", "$", "saleSystem", "=", "null", ",", "array", "$", "statuses", "=", "[", "]", ")", "{", "$", "filters", "=", "[", "]", ";", "if", "(", "!", "is_nul...
Retrieves a list of all orders available in SkyHub. @param int $page @param int $perPage @param string $saleSystem @param array $statuses @return \SkyHub\Api\Handler\Response\HandlerInterface
[ "Retrieves", "a", "list", "of", "all", "orders", "available", "in", "SkyHub", "." ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api/Handler/Request/Sales/OrderHandler.php#L53-L74
train
bittools/skyhub-php
src/Api/Handler/Request/Sales/OrderHandler.php
OrderHandler.invoice
public function invoice($orderId, $invoiceKey) { $transformer = new InvoiceTransformer(self::STATUS_PAID, $invoiceKey); $body = $transformer->output(); /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->post($this->baseUrlPath("$orderId/invoice"), $body); return $responseHandler; }
php
public function invoice($orderId, $invoiceKey) { $transformer = new InvoiceTransformer(self::STATUS_PAID, $invoiceKey); $body = $transformer->output(); /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->post($this->baseUrlPath("$orderId/invoice"), $body); return $responseHandler; }
[ "public", "function", "invoice", "(", "$", "orderId", ",", "$", "invoiceKey", ")", "{", "$", "transformer", "=", "new", "InvoiceTransformer", "(", "self", "::", "STATUS_PAID", ",", "$", "invoiceKey", ")", ";", "$", "body", "=", "$", "transformer", "->", ...
Invoice an order in SkyHub. @var string $orderId @var string $invoiceKey @return \SkyHub\Api\Handler\Response\HandlerInterface
[ "Invoice", "an", "order", "in", "SkyHub", "." ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api/Handler/Request/Sales/OrderHandler.php#L137-L145
train
bittools/skyhub-php
src/Api/Handler/Request/Sales/OrderHandler.php
OrderHandler.cancel
public function cancel($orderId) { $transformer = new CancelTransformer(self::STATUS_CANCELLED); $body = $transformer->output(); /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->post($this->baseUrlPath("$orderId/cancel"), $body); return $responseHandler; }
php
public function cancel($orderId) { $transformer = new CancelTransformer(self::STATUS_CANCELLED); $body = $transformer->output(); /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->post($this->baseUrlPath("$orderId/cancel"), $body); return $responseHandler; }
[ "public", "function", "cancel", "(", "$", "orderId", ")", "{", "$", "transformer", "=", "new", "CancelTransformer", "(", "self", "::", "STATUS_CANCELLED", ")", ";", "$", "body", "=", "$", "transformer", "->", "output", "(", ")", ";", "/** @var \\SkyHub\\Api\...
Cancel an order in SkyHub. @var string $orderId @return \SkyHub\Api\Handler\Response\HandlerInterface
[ "Cancel", "an", "order", "in", "SkyHub", "." ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api/Handler/Request/Sales/OrderHandler.php#L155-L163
train
bittools/skyhub-php
src/Api/Handler/Request/Shipment/PlpHandler.php
PlpHandler.group
public function group(array $orders) { $transformer = new GroupTransformer($orders); $body = $transformer->output(); /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->post($this->baseUrlPath(), $body); return $responseHandler; }
php
public function group(array $orders) { $transformer = new GroupTransformer($orders); $body = $transformer->output(); /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->post($this->baseUrlPath(), $body); return $responseHandler; }
[ "public", "function", "group", "(", "array", "$", "orders", ")", "{", "$", "transformer", "=", "new", "GroupTransformer", "(", "$", "orders", ")", ";", "$", "body", "=", "$", "transformer", "->", "output", "(", ")", ";", "/** @var \\SkyHub\\Api\\Handler\\Res...
Group multiple orders in a PLP. @param array $orders @return \SkyHub\Api\Handler\Response\HandlerInterface
[ "Group", "multiple", "orders", "in", "a", "PLP", "." ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api/Handler/Request/Shipment/PlpHandler.php#L65-L74
train
bittools/skyhub-php
src/Api/Handler/Request/Shipment/PlpHandler.php
PlpHandler.viewFile
public function viewFile($id) { $query = [ 'plp_id' => $id ]; /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->get($this->baseUrlPath('/view', $query)); return $responseHandler; }
php
public function viewFile($id) { $query = [ 'plp_id' => $id ]; /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->get($this->baseUrlPath('/view', $query)); return $responseHandler; }
[ "public", "function", "viewFile", "(", "$", "id", ")", "{", "$", "query", "=", "[", "'plp_id'", "=>", "$", "id", "]", ";", "/** @var \\SkyHub\\Api\\Handler\\Response\\HandlerInterface $responseHandler */", "$", "responseHandler", "=", "$", "this", "->", "service", ...
Get PLP file @param string $id @return \SkyHub\Api\Handler\Response\HandlerInterface
[ "Get", "PLP", "file" ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api/Handler/Request/Shipment/PlpHandler.php#L84-L94
train
bittools/skyhub-php
src/Api/Handler/Request/Shipment/PlpHandler.php
PlpHandler.ungroup
public function ungroup($id) { $params = [ 'plp_id' => $id, ]; /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->delete($this->baseUrlPath(), $params); return $responseHandler; }
php
public function ungroup($id) { $params = [ 'plp_id' => $id, ]; /** @var \SkyHub\Api\Handler\Response\HandlerInterface $responseHandler */ $responseHandler = $this->service()->delete($this->baseUrlPath(), $params); return $responseHandler; }
[ "public", "function", "ungroup", "(", "$", "id", ")", "{", "$", "params", "=", "[", "'plp_id'", "=>", "$", "id", ",", "]", ";", "/** @var \\SkyHub\\Api\\Handler\\Response\\HandlerInterface $responseHandler */", "$", "responseHandler", "=", "$", "this", "->", "serv...
Ungroup a PLP. @param string $id @return \SkyHub\Api\Handler\Response\HandlerInterface
[ "Ungroup", "a", "PLP", "." ]
e57a62a953a0fe79c69181c8cc069b29c91cf743
https://github.com/bittools/skyhub-php/blob/e57a62a953a0fe79c69181c8cc069b29c91cf743/src/Api/Handler/Request/Shipment/PlpHandler.php#L104-L113
train
digitickets/omnipay-barclays-epdq
src/Omnipay/BarclaysEpdq/Message/EssentialPurchaseRequest.php
EssentialPurchaseRequest.setReturnUrl
public function setReturnUrl($value) { $value = substr($value, 0, 200); $this->setParameter('returnUrl', $value); $this->setParameter('declineUrl', $value); $this->setParameter('exceptionUrl', $value); return $this; }
php
public function setReturnUrl($value) { $value = substr($value, 0, 200); $this->setParameter('returnUrl', $value); $this->setParameter('declineUrl', $value); $this->setParameter('exceptionUrl', $value); return $this; }
[ "public", "function", "setReturnUrl", "(", "$", "value", ")", "{", "$", "value", "=", "substr", "(", "$", "value", ",", "0", ",", "200", ")", ";", "$", "this", "->", "setParameter", "(", "'returnUrl'", ",", "$", "value", ")", ";", "$", "this", "->"...
This method keeps the backward compatibility with setDeclineUrl and setExceptionUrl. It fills returnUrl, declineUrl and exceptionUrl with the same value. @param string $value Max length of 200 @return $this
[ "This", "method", "keeps", "the", "backward", "compatibility", "with", "setDeclineUrl", "and", "setExceptionUrl", ".", "It", "fills", "returnUrl", "declineUrl", "and", "exceptionUrl", "with", "the", "same", "value", "." ]
34d1dcac8325d206b7da8878aea1993083781a6c
https://github.com/digitickets/omnipay-barclays-epdq/blob/34d1dcac8325d206b7da8878aea1993083781a6c/src/Omnipay/BarclaysEpdq/Message/EssentialPurchaseRequest.php#L80-L88
train
digitickets/omnipay-barclays-epdq
src/Omnipay/BarclaysEpdq/Message/EssentialPurchaseRequest.php
EssentialPurchaseRequest.setItems
public function setItems($items) { $newItems = new ItemBag(); foreach ($items as $item) { $newItems->add(new Item($item->getParameters())); } return parent::setItems($newItems); }
php
public function setItems($items) { $newItems = new ItemBag(); foreach ($items as $item) { $newItems->add(new Item($item->getParameters())); } return parent::setItems($newItems); }
[ "public", "function", "setItems", "(", "$", "items", ")", "{", "$", "newItems", "=", "new", "ItemBag", "(", ")", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "newItems", "->", "add", "(", "new", "Item", "(", "$", "item", "...
Set items for request Cast the items to instances of \Omnipay\BarclaysEpdq\Item @param array|\Omnipay\Common\ItemBag|\Omnipay\Common\Item[] $items @return AbstractRequest
[ "Set", "items", "for", "request" ]
34d1dcac8325d206b7da8878aea1993083781a6c
https://github.com/digitickets/omnipay-barclays-epdq/blob/34d1dcac8325d206b7da8878aea1993083781a6c/src/Omnipay/BarclaysEpdq/Message/EssentialPurchaseRequest.php#L337-L345
train
limen/redisun
src/Model.php
Model.newQuery
public function newQuery() { $this->orderBys = []; $this->limit = null; $this->offset = null; return $this->freshQueryBuilder(); }
php
public function newQuery() { $this->orderBys = []; $this->limit = null; $this->offset = null; return $this->freshQueryBuilder(); }
[ "public", "function", "newQuery", "(", ")", "{", "$", "this", "->", "orderBys", "=", "[", "]", ";", "$", "this", "->", "limit", "=", "null", ";", "$", "this", "->", "offset", "=", "null", ";", "return", "$", "this", "->", "freshQueryBuilder", "(", ...
Refresh query builder @return $this
[ "Refresh", "query", "builder" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L128-L135
train
limen/redisun
src/Model.php
Model.createNotExists
public function createNotExists($id, $value, $ttl = null) { return $this->create($id, $value, $ttl, false); }
php
public function createNotExists($id, $value, $ttl = null) { return $this->create($id, $value, $ttl, false); }
[ "public", "function", "createNotExists", "(", "$", "id", ",", "$", "value", ",", "$", "ttl", "=", "null", ")", "{", "return", "$", "this", "->", "create", "(", "$", "id", ",", "$", "value", ",", "$", "ttl", ",", "false", ")", ";", "}" ]
Similar to setnx @param $id @param $value @param null $ttl @return bool
[ "Similar", "to", "setnx" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L396-L399
train
limen/redisun
src/Model.php
Model.createExists
public function createExists($id, $value, $ttl = null) { return $this->create($id, $value, $ttl, true); }
php
public function createExists($id, $value, $ttl = null) { return $this->create($id, $value, $ttl, true); }
[ "public", "function", "createExists", "(", "$", "id", ",", "$", "value", ",", "$", "ttl", "=", "null", ")", "{", "return", "$", "this", "->", "create", "(", "$", "id", ",", "$", "value", ",", "$", "ttl", ",", "true", ")", ";", "}" ]
Similar to setxx @param $id @param $value @param null $ttl @return bool
[ "Similar", "to", "setxx" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L408-L411
train
limen/redisun
src/Model.php
Model.insertExists
public function insertExists(array $bindings, $value, $ttl = null) { return $this->insert($bindings, $value, $ttl, true); }
php
public function insertExists(array $bindings, $value, $ttl = null) { return $this->insert($bindings, $value, $ttl, true); }
[ "public", "function", "insertExists", "(", "array", "$", "bindings", ",", "$", "value", ",", "$", "ttl", "=", "null", ")", "{", "return", "$", "this", "->", "insert", "(", "$", "bindings", ",", "$", "value", ",", "$", "ttl", ",", "true", ")", ";", ...
Insert when key exists @param array $bindings @param $value @param null $ttl @return mixed
[ "Insert", "when", "key", "exists" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L445-L448
train
limen/redisun
src/Model.php
Model.insertNotExists
public function insertNotExists(array $bindings, $value, $ttl = null) { return $this->insert($bindings, $value, $ttl, false); }
php
public function insertNotExists(array $bindings, $value, $ttl = null) { return $this->insert($bindings, $value, $ttl, false); }
[ "public", "function", "insertNotExists", "(", "array", "$", "bindings", ",", "$", "value", ",", "$", "ttl", "=", "null", ")", "{", "return", "$", "this", "->", "insert", "(", "$", "bindings", ",", "$", "value", ",", "$", "ttl", ",", "false", ")", "...
Insert when key not exists @param array $bindings @param $value @param null $ttl @return mixed
[ "Insert", "when", "key", "not", "exists" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L458-L461
train
limen/redisun
src/Model.php
Model.find
public function find($id) { $this->newQuery(); $this->queryBuilder->whereEqual($this->primaryFieldName, $id); $queryKey = $this->queryBuilder->firstQueryKey(); if (!$this->isCompleteKey($queryKey)) { return null; } list($method, $parameters) = $this->getFindMethodAndParameters(); array_unshift($parameters, $queryKey); $value = call_user_func_array([$this->redClient, $method], $parameters); return $value; }
php
public function find($id) { $this->newQuery(); $this->queryBuilder->whereEqual($this->primaryFieldName, $id); $queryKey = $this->queryBuilder->firstQueryKey(); if (!$this->isCompleteKey($queryKey)) { return null; } list($method, $parameters) = $this->getFindMethodAndParameters(); array_unshift($parameters, $queryKey); $value = call_user_func_array([$this->redClient, $method], $parameters); return $value; }
[ "public", "function", "find", "(", "$", "id", ")", "{", "$", "this", "->", "newQuery", "(", ")", ";", "$", "this", "->", "queryBuilder", "->", "whereEqual", "(", "$", "this", "->", "primaryFieldName", ",", "$", "id", ")", ";", "$", "queryKey", "=", ...
find an item @param $id int|string Primary key @return mixed
[ "find", "an", "item" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L468-L486
train
limen/redisun
src/Model.php
Model.getAndSet
public function getAndSet($value, $ttl = null) { $keys = $this->queryBuilder->getQueryKeys(); if (count($keys) > 1) { throw new Exception('GetAndSet doesnt support multiple keys'); } elseif (count($keys) == 0) { throw new Exception('No query keys'); } $key = $keys[0]; if (!$this->isCompleteKey($key)) { throw new Exception('Not complete key'); } $value = $this->castValueForUpdate($value); $commandName = 'getset' . ucfirst($this->type); $command = $this->commandFactory->getCommand($commandName, [$key], $value); if (!is_null($ttl)) { $command->setTtl($ttl); } $result = $this->executeCommand($command); $data = isset($result[$key]) ? $result[$key] : null; if ($data && $this->type == static::TYPE_HASH) { $data = $this->resolveHash($data); } return $data; }
php
public function getAndSet($value, $ttl = null) { $keys = $this->queryBuilder->getQueryKeys(); if (count($keys) > 1) { throw new Exception('GetAndSet doesnt support multiple keys'); } elseif (count($keys) == 0) { throw new Exception('No query keys'); } $key = $keys[0]; if (!$this->isCompleteKey($key)) { throw new Exception('Not complete key'); } $value = $this->castValueForUpdate($value); $commandName = 'getset' . ucfirst($this->type); $command = $this->commandFactory->getCommand($commandName, [$key], $value); if (!is_null($ttl)) { $command->setTtl($ttl); } $result = $this->executeCommand($command); $data = isset($result[$key]) ? $result[$key] : null; if ($data && $this->type == static::TYPE_HASH) { $data = $this->resolveHash($data); } return $data; }
[ "public", "function", "getAndSet", "(", "$", "value", ",", "$", "ttl", "=", "null", ")", "{", "$", "keys", "=", "$", "this", "->", "queryBuilder", "->", "getQueryKeys", "(", ")", ";", "if", "(", "count", "(", "$", "keys", ")", ">", "1", ")", "{",...
Get key and set new value @param string|array $value @param null $ttl @return mixed @throws Exception
[ "Get", "key", "and", "set", "new", "value" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L617-L644
train
limen/redisun
src/Model.php
Model.prepareKeys
protected function prepareKeys($forGet = true) { $queryKeys = $this->queryBuilder->getQueryKeys(); // Caution! Would get all items. if (!$queryKeys) { $queryKeys = [$this->key]; } $existKeys = $this->getExistKeys($queryKeys); if ($forGet) { $this->setOrderByFieldIndices(); if ($this->orderByFieldIndices) { uasort($existKeys, [$this, 'sortByFields']); } if ($this->offset || $this->limit) { $existKeys = array_slice($existKeys, (int)$this->offset, $this->limit); } } return $existKeys; }
php
protected function prepareKeys($forGet = true) { $queryKeys = $this->queryBuilder->getQueryKeys(); // Caution! Would get all items. if (!$queryKeys) { $queryKeys = [$this->key]; } $existKeys = $this->getExistKeys($queryKeys); if ($forGet) { $this->setOrderByFieldIndices(); if ($this->orderByFieldIndices) { uasort($existKeys, [$this, 'sortByFields']); } if ($this->offset || $this->limit) { $existKeys = array_slice($existKeys, (int)$this->offset, $this->limit); } } return $existKeys; }
[ "protected", "function", "prepareKeys", "(", "$", "forGet", "=", "true", ")", "{", "$", "queryKeys", "=", "$", "this", "->", "queryBuilder", "->", "getQueryKeys", "(", ")", ";", "// Caution! Would get all items.", "if", "(", "!", "$", "queryKeys", ")", "{", ...
Prepare query keys @param bool $forGet @return array
[ "Prepare", "query", "keys" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L704-L728
train
limen/redisun
src/Model.php
Model.getUpdateMethod
protected function getUpdateMethod() { $method = ''; switch ($this->type) { case 'string': $method = 'set'; break; case 'list': $method = $this->listPushMethod; break; case 'set': $method = 'sadd'; break; case 'zset': $method = 'zadd'; break; case 'hash': $method = 'hmset'; break; default: break; } return $method; }
php
protected function getUpdateMethod() { $method = ''; switch ($this->type) { case 'string': $method = 'set'; break; case 'list': $method = $this->listPushMethod; break; case 'set': $method = 'sadd'; break; case 'zset': $method = 'zadd'; break; case 'hash': $method = 'hmset'; break; default: break; } return $method; }
[ "protected", "function", "getUpdateMethod", "(", ")", "{", "$", "method", "=", "''", ";", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "'string'", ":", "$", "method", "=", "'set'", ";", "break", ";", "case", "'list'", ":", "$", "method...
Get update method according to redis data type @return string
[ "Get", "update", "method", "according", "to", "redis", "data", "type" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L853-L877
train
limen/redisun
src/Model.php
Model.castValueForUpdate
protected function castValueForUpdate($value) { switch ($this->type) { case 'string': $value = [(string)$value]; break; case 'list': case 'set': $value = (array)$value; break; case 'zset': $casted = []; foreach ($value as $k => $v) { $casted[] = $v; $casted[] = $k; } $value = $casted; break; case 'hash': $casted = []; foreach ($value as $k => $v) { $casted[] = $k; $casted[] = $v; } $value = $casted; break; default: break; } return $value; }
php
protected function castValueForUpdate($value) { switch ($this->type) { case 'string': $value = [(string)$value]; break; case 'list': case 'set': $value = (array)$value; break; case 'zset': $casted = []; foreach ($value as $k => $v) { $casted[] = $v; $casted[] = $k; } $value = $casted; break; case 'hash': $casted = []; foreach ($value as $k => $v) { $casted[] = $k; $casted[] = $v; } $value = $casted; break; default: break; } return $value; }
[ "protected", "function", "castValueForUpdate", "(", "$", "value", ")", "{", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "'string'", ":", "$", "value", "=", "[", "(", "string", ")", "$", "value", "]", ";", "break", ";", "case", "'list'...
Cast value data type for update according to redis data type @param $value @return array
[ "Cast", "value", "data", "type", "for", "update", "according", "to", "redis", "data", "type" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L885-L916
train
limen/redisun
src/Model.php
Model.getFindMethodAndParameters
protected function getFindMethodAndParameters() { $method = ''; $parameters = []; switch ($this->type) { case 'string': $method = 'get'; break; case 'list': $method = 'lrange'; $parameters = [0, -1]; break; case 'set': $method = 'smembers'; break; case 'zset': $method = 'zrange'; $parameters = [0, -1]; break; case 'hash': $method = 'hgetall'; break; default: break; } return [$method, $parameters]; }
php
protected function getFindMethodAndParameters() { $method = ''; $parameters = []; switch ($this->type) { case 'string': $method = 'get'; break; case 'list': $method = 'lrange'; $parameters = [0, -1]; break; case 'set': $method = 'smembers'; break; case 'zset': $method = 'zrange'; $parameters = [0, -1]; break; case 'hash': $method = 'hgetall'; break; default: break; } return [$method, $parameters]; }
[ "protected", "function", "getFindMethodAndParameters", "(", ")", "{", "$", "method", "=", "''", ";", "$", "parameters", "=", "[", "]", ";", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "'string'", ":", "$", "method", "=", "'get'", ";", ...
Get find method and default parameters according to redis data type. @return array
[ "Get", "find", "method", "and", "default", "parameters", "according", "to", "redis", "data", "type", "." ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L922-L950
train
limen/redisun
src/Model.php
Model.getExistKeys
protected function getExistKeys($queryKeys) { $keys = $this->markUnboundFields($queryKeys); $exist = []; if ($keys) { $command = $this->commandFactory->getCommand('keys', $keys); $exist = $this->executeCommand($command); $exist = array_unique($exist); } return $exist; }
php
protected function getExistKeys($queryKeys) { $keys = $this->markUnboundFields($queryKeys); $exist = []; if ($keys) { $command = $this->commandFactory->getCommand('keys', $keys); $exist = $this->executeCommand($command); $exist = array_unique($exist); } return $exist; }
[ "protected", "function", "getExistKeys", "(", "$", "queryKeys", ")", "{", "$", "keys", "=", "$", "this", "->", "markUnboundFields", "(", "$", "queryKeys", ")", ";", "$", "exist", "=", "[", "]", ";", "if", "(", "$", "keys", ")", "{", "$", "command", ...
Get existed keys in redis database @param $queryKeys @return array|mixed
[ "Get", "existed", "keys", "in", "redis", "database" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L958-L973
train
limen/redisun
src/Model.php
Model.hasUnboundField
protected function hasUnboundField($key) { $parts = $this->explodeKey($key); foreach ($parts as $part) { if ($this->isUnboundField($part)) { return true; } } return false; }
php
protected function hasUnboundField($key) { $parts = $this->explodeKey($key); foreach ($parts as $part) { if ($this->isUnboundField($part)) { return true; } } return false; }
[ "protected", "function", "hasUnboundField", "(", "$", "key", ")", "{", "$", "parts", "=", "$", "this", "->", "explodeKey", "(", "$", "key", ")", ";", "foreach", "(", "$", "parts", "as", "$", "part", ")", "{", "if", "(", "$", "this", "->", "isUnboun...
Check a key whether has unbound field @param $key @return bool
[ "Check", "a", "key", "whether", "has", "unbound", "field" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L1007-L1018
train
limen/redisun
src/Model.php
Model.setOrderByFieldIndices
private function setOrderByFieldIndices() { $keyParts = $this->explodeKey($this->key); foreach ($this->orderBys as $field => $order) { $needle = $this->fieldWrapper[0] . $field . $this->fieldWrapper[1]; $this->orderByFieldIndices[array_search($needle, $keyParts)] = $order; } }
php
private function setOrderByFieldIndices() { $keyParts = $this->explodeKey($this->key); foreach ($this->orderBys as $field => $order) { $needle = $this->fieldWrapper[0] . $field . $this->fieldWrapper[1]; $this->orderByFieldIndices[array_search($needle, $keyParts)] = $order; } }
[ "private", "function", "setOrderByFieldIndices", "(", ")", "{", "$", "keyParts", "=", "$", "this", "->", "explodeKey", "(", "$", "this", "->", "key", ")", ";", "foreach", "(", "$", "this", "->", "orderBys", "as", "$", "field", "=>", "$", "order", ")", ...
Set order by field and order
[ "Set", "order", "by", "field", "and", "order" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L1120-L1128
train
limen/redisun
src/Model.php
Model.resolveHashes
private function resolveHashes(array $hashes) { $assoc = []; foreach ($hashes as $k => $hash) { $item = $this->resolveHash($hash); if ($item) { $assoc[$k] = $item; } } return $assoc; }
php
private function resolveHashes(array $hashes) { $assoc = []; foreach ($hashes as $k => $hash) { $item = $this->resolveHash($hash); if ($item) { $assoc[$k] = $item; } } return $assoc; }
[ "private", "function", "resolveHashes", "(", "array", "$", "hashes", ")", "{", "$", "assoc", "=", "[", "]", ";", "foreach", "(", "$", "hashes", "as", "$", "k", "=>", "$", "hash", ")", "{", "$", "item", "=", "$", "this", "->", "resolveHash", "(", ...
raw hash data to associate array @param array $hashes @return array
[ "raw", "hash", "data", "to", "associate", "array" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Model.php#L1172-L1183
train
limen/redisun
src/Commands/Command.php
Command.parseResponse
function parseResponse($data) { if (empty($data)) { return []; } if (isset($data[0]) && count($data[0]) === $this->getKeysCount()) { $items = array_combine($data[0], $data[1]); return array_filter($items, [$this, 'notNil']); } throw new Exception('Error when evaluate lua script. Response is: ' . json_encode($data)); }
php
function parseResponse($data) { if (empty($data)) { return []; } if (isset($data[0]) && count($data[0]) === $this->getKeysCount()) { $items = array_combine($data[0], $data[1]); return array_filter($items, [$this, 'notNil']); } throw new Exception('Error when evaluate lua script. Response is: ' . json_encode($data)); }
[ "function", "parseResponse", "(", "$", "data", ")", "{", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "return", "[", "]", ";", "}", "if", "(", "isset", "(", "$", "data", "[", "0", "]", ")", "&&", "count", "(", "$", "data", "[", "0", ...
Resolve data returned from "eval" @param $data @return mixed @throws Exception
[ "Resolve", "data", "returned", "from", "eval" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/Commands/Command.php#L99-L112
train
limen/redisun
src/QueryBuilder.php
QueryBuilder.getValidQueryKeys
protected function getValidQueryKeys() { $whereIns = []; foreach ($this->whereBetweens as $field => $range) { $whereIns[$field] = range($range[0], $range[1]); } foreach ($whereIns as $key => $value) { $this->whereIn($key, $value); } $this->queryKeys = []; foreach ($this->whereIns as $field => $range) { if ($this->queryKeys === []) { foreach ($range as $value) { $this->queryKeys[] = $this->bindValue($this->key, $field, $value); } } else { $queryKeys = $this->queryKeys; $this->queryKeys = []; foreach ($queryKeys as $item) { foreach ($range as $value) { $this->queryKeys[] = $this->bindValue($item, $field, $value); } } } } $this->queryKeys = array_unique(array_values($this->queryKeys)); return $this; }
php
protected function getValidQueryKeys() { $whereIns = []; foreach ($this->whereBetweens as $field => $range) { $whereIns[$field] = range($range[0], $range[1]); } foreach ($whereIns as $key => $value) { $this->whereIn($key, $value); } $this->queryKeys = []; foreach ($this->whereIns as $field => $range) { if ($this->queryKeys === []) { foreach ($range as $value) { $this->queryKeys[] = $this->bindValue($this->key, $field, $value); } } else { $queryKeys = $this->queryKeys; $this->queryKeys = []; foreach ($queryKeys as $item) { foreach ($range as $value) { $this->queryKeys[] = $this->bindValue($item, $field, $value); } } } } $this->queryKeys = array_unique(array_values($this->queryKeys)); return $this; }
[ "protected", "function", "getValidQueryKeys", "(", ")", "{", "$", "whereIns", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "whereBetweens", "as", "$", "field", "=>", "$", "range", ")", "{", "$", "whereIns", "[", "$", "field", "]", "=", "ran...
Get valid query keys @return $this
[ "Get", "valid", "query", "keys" ]
c9c8f91a761b5e893415d28615f0bdf9dbc34fd4
https://github.com/limen/redisun/blob/c9c8f91a761b5e893415d28615f0bdf9dbc34fd4/src/QueryBuilder.php#L157-L190
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.addLikeTo
public function addLikeTo(LikeableContract $likeable, $type, $userId) { $userId = $this->getLikerUserId($userId); $like = $likeable->likesAndDislikes()->where([ 'user_id' => $userId, ])->first(); if (!$like) { $likeable->likes()->create([ 'user_id' => $userId, 'type_id' => $this->getLikeTypeId($type), ]); return; } if ($like->type_id == $this->getLikeTypeId($type)) { return; } $like->delete(); $likeable->likes()->create([ 'user_id' => $userId, 'type_id' => $this->getLikeTypeId($type), ]); }
php
public function addLikeTo(LikeableContract $likeable, $type, $userId) { $userId = $this->getLikerUserId($userId); $like = $likeable->likesAndDislikes()->where([ 'user_id' => $userId, ])->first(); if (!$like) { $likeable->likes()->create([ 'user_id' => $userId, 'type_id' => $this->getLikeTypeId($type), ]); return; } if ($like->type_id == $this->getLikeTypeId($type)) { return; } $like->delete(); $likeable->likes()->create([ 'user_id' => $userId, 'type_id' => $this->getLikeTypeId($type), ]); }
[ "public", "function", "addLikeTo", "(", "LikeableContract", "$", "likeable", ",", "$", "type", ",", "$", "userId", ")", "{", "$", "userId", "=", "$", "this", "->", "getLikerUserId", "(", "$", "userId", ")", ";", "$", "like", "=", "$", "likeable", "->",...
Add a like to likeable model by user. @param \Cog\Likeable\Contracts\Likeable $likeable @param string $type @param string $userId @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Add", "a", "like", "to", "likeable", "model", "by", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L43-L70
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.removeLikeFrom
public function removeLikeFrom(LikeableContract $likeable, $type, $userId) { $like = $likeable->likesAndDislikes()->where([ 'user_id' => $this->getLikerUserId($userId), 'type_id' => $this->getLikeTypeId($type), ])->first(); if (!$like) { return; } $like->delete(); }
php
public function removeLikeFrom(LikeableContract $likeable, $type, $userId) { $like = $likeable->likesAndDislikes()->where([ 'user_id' => $this->getLikerUserId($userId), 'type_id' => $this->getLikeTypeId($type), ])->first(); if (!$like) { return; } $like->delete(); }
[ "public", "function", "removeLikeFrom", "(", "LikeableContract", "$", "likeable", ",", "$", "type", ",", "$", "userId", ")", "{", "$", "like", "=", "$", "likeable", "->", "likesAndDislikes", "(", ")", "->", "where", "(", "[", "'user_id'", "=>", "$", "thi...
Remove a like to likeable model by user. @param \Cog\Likeable\Contracts\Likeable $likeable @param string $type @param int|null $userId @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Remove", "a", "like", "to", "likeable", "model", "by", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L83-L95
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.decrementLikesCount
public function decrementLikesCount(LikeableContract $likeable) { $counter = $likeable->likesCounter()->first(); if (!$counter) { return; } $counter->decrement('count'); }
php
public function decrementLikesCount(LikeableContract $likeable) { $counter = $likeable->likesCounter()->first(); if (!$counter) { return; } $counter->decrement('count'); }
[ "public", "function", "decrementLikesCount", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "counter", "=", "$", "likeable", "->", "likesCounter", "(", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "counter", ")", "{", "return", ";", ...
Decrement the total like count stored in the counter. @param \Cog\Likeable\Contracts\Likeable $likeable @return void
[ "Decrement", "the", "total", "like", "count", "stored", "in", "the", "counter", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L163-L172
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.incrementLikesCount
public function incrementLikesCount(LikeableContract $likeable) { $counter = $likeable->likesCounter()->first(); if (!$counter) { $counter = $likeable->likesCounter()->create([ 'count' => 0, 'type_id' => LikeType::LIKE, ]); } $counter->increment('count'); }
php
public function incrementLikesCount(LikeableContract $likeable) { $counter = $likeable->likesCounter()->first(); if (!$counter) { $counter = $likeable->likesCounter()->create([ 'count' => 0, 'type_id' => LikeType::LIKE, ]); } $counter->increment('count'); }
[ "public", "function", "incrementLikesCount", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "counter", "=", "$", "likeable", "->", "likesCounter", "(", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "counter", ")", "{", "$", "counter",...
Increment the total like count stored in the counter. @param \Cog\Likeable\Contracts\Likeable $likeable @return void
[ "Increment", "the", "total", "like", "count", "stored", "in", "the", "counter", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L180-L192
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.decrementDislikesCount
public function decrementDislikesCount(LikeableContract $likeable) { $counter = $likeable->dislikesCounter()->first(); if (!$counter) { return; } $counter->decrement('count'); }
php
public function decrementDislikesCount(LikeableContract $likeable) { $counter = $likeable->dislikesCounter()->first(); if (!$counter) { return; } $counter->decrement('count'); }
[ "public", "function", "decrementDislikesCount", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "counter", "=", "$", "likeable", "->", "dislikesCounter", "(", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "counter", ")", "{", "return", ...
Decrement the total dislike count stored in the counter. @param \Cog\Likeable\Contracts\Likeable $likeable @return void
[ "Decrement", "the", "total", "dislike", "count", "stored", "in", "the", "counter", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L200-L209
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.incrementDislikesCount
public function incrementDislikesCount(LikeableContract $likeable) { $counter = $likeable->dislikesCounter()->first(); if (!$counter) { $counter = $likeable->dislikesCounter()->create([ 'count' => 0, 'type_id' => LikeType::DISLIKE, ]); } $counter->increment('count'); }
php
public function incrementDislikesCount(LikeableContract $likeable) { $counter = $likeable->dislikesCounter()->first(); if (!$counter) { $counter = $likeable->dislikesCounter()->create([ 'count' => 0, 'type_id' => LikeType::DISLIKE, ]); } $counter->increment('count'); }
[ "public", "function", "incrementDislikesCount", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "counter", "=", "$", "likeable", "->", "dislikesCounter", "(", ")", "->", "first", "(", ")", ";", "if", "(", "!", "$", "counter", ")", "{", "$", "cou...
Increment the total dislike count stored in the counter. @param \Cog\Likeable\Contracts\Likeable $likeable @return void
[ "Increment", "the", "total", "dislike", "count", "stored", "in", "the", "counter", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L217-L229
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.removeLikeCountersOfType
public function removeLikeCountersOfType($likeableType, $type = null) { if (class_exists($likeableType)) { /** @var \Cog\Likeable\Contracts\Likeable $likeable */ $likeable = new $likeableType; $likeableType = $likeable->getMorphClass(); } /** @var \Illuminate\Database\Eloquent\Builder $counters */ $counters = app(LikeCounterContract::class)->where('likeable_type', $likeableType); if (!is_null($type)) { $counters->where('type_id', $this->getLikeTypeId($type)); } $counters->delete(); }
php
public function removeLikeCountersOfType($likeableType, $type = null) { if (class_exists($likeableType)) { /** @var \Cog\Likeable\Contracts\Likeable $likeable */ $likeable = new $likeableType; $likeableType = $likeable->getMorphClass(); } /** @var \Illuminate\Database\Eloquent\Builder $counters */ $counters = app(LikeCounterContract::class)->where('likeable_type', $likeableType); if (!is_null($type)) { $counters->where('type_id', $this->getLikeTypeId($type)); } $counters->delete(); }
[ "public", "function", "removeLikeCountersOfType", "(", "$", "likeableType", ",", "$", "type", "=", "null", ")", "{", "if", "(", "class_exists", "(", "$", "likeableType", ")", ")", "{", "/** @var \\Cog\\Likeable\\Contracts\\Likeable $likeable */", "$", "likeable", "=...
Remove like counters by likeable type. @param string $likeableType @param string|null $type @return void @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Remove", "like", "counters", "by", "likeable", "type", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L240-L254
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.removeModelLikes
public function removeModelLikes(LikeableContract $likeable, $type) { app(LikeContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); app(LikeCounterContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); }
php
public function removeModelLikes(LikeableContract $likeable, $type) { app(LikeContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); app(LikeCounterContract::class)->where([ 'likeable_id' => $likeable->getKey(), 'likeable_type' => $likeable->getMorphClass(), 'type_id' => $this->getLikeTypeId($type), ])->delete(); }
[ "public", "function", "removeModelLikes", "(", "LikeableContract", "$", "likeable", ",", "$", "type", ")", "{", "app", "(", "LikeContract", "::", "class", ")", "->", "where", "(", "[", "'likeable_id'", "=>", "$", "likeable", "->", "getKey", "(", ")", ",", ...
Remove all likes from likeable model. @param \Cog\Likeable\Contracts\Likeable $likeable @param string $type @return void @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Remove", "all", "likes", "from", "likeable", "model", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L265-L278
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.collectLikersOf
public function collectLikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->likes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
php
public function collectLikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->likes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
[ "public", "function", "collectLikersOf", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "userModel", "=", "$", "this", "->", "resolveUserModel", "(", ")", ";", "$", "likersIds", "=", "$", "likeable", "->", "likes", "->", "pluck", "(", "'user_id'", ...
Get collection of users who liked entity. @param \Cog\Likeable\Contracts\Likeable $likeable @return \Illuminate\Support\Collection
[ "Get", "collection", "of", "users", "who", "liked", "entity", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L286-L293
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.collectDislikersOf
public function collectDislikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->dislikes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
php
public function collectDislikersOf(LikeableContract $likeable) { $userModel = $this->resolveUserModel(); $likersIds = $likeable->dislikes->pluck('user_id'); return $userModel::whereKey($likersIds)->get(); }
[ "public", "function", "collectDislikersOf", "(", "LikeableContract", "$", "likeable", ")", "{", "$", "userModel", "=", "$", "this", "->", "resolveUserModel", "(", ")", ";", "$", "likersIds", "=", "$", "likeable", "->", "dislikes", "->", "pluck", "(", "'user_...
Get collection of users who disliked entity. @param \Cog\Likeable\Contracts\Likeable $likeable @return \Illuminate\Support\Collection
[ "Get", "collection", "of", "users", "who", "disliked", "entity", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L301-L308
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.fetchLikesCounters
public function fetchLikesCounters($likeableType, $likeType) { /** @var \Illuminate\Database\Eloquent\Builder $likesCount */ $likesCount = app(LikeContract::class) ->select([ DB::raw('COUNT(*) AS count'), 'likeable_type', 'likeable_id', 'type_id', ]) ->where('likeable_type', $likeableType); if (!is_null($likeType)) { $likesCount->where('type_id', $this->getLikeTypeId($likeType)); } $likesCount->groupBy('likeable_id', 'type_id'); return $likesCount->get()->toArray(); }
php
public function fetchLikesCounters($likeableType, $likeType) { /** @var \Illuminate\Database\Eloquent\Builder $likesCount */ $likesCount = app(LikeContract::class) ->select([ DB::raw('COUNT(*) AS count'), 'likeable_type', 'likeable_id', 'type_id', ]) ->where('likeable_type', $likeableType); if (!is_null($likeType)) { $likesCount->where('type_id', $this->getLikeTypeId($likeType)); } $likesCount->groupBy('likeable_id', 'type_id'); return $likesCount->get()->toArray(); }
[ "public", "function", "fetchLikesCounters", "(", "$", "likeableType", ",", "$", "likeType", ")", "{", "/** @var \\Illuminate\\Database\\Eloquent\\Builder $likesCount */", "$", "likesCount", "=", "app", "(", "LikeContract", "::", "class", ")", "->", "select", "(", "[",...
Fetch likes counters data. @param string $likeableType @param string $likeType @return array @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Fetch", "likes", "counters", "data", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L362-L381
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.getLikerUserId
protected function getLikerUserId($userId) { if (is_null($userId)) { $userId = $this->loggedInUserId(); } if (!$userId) { throw new LikerNotDefinedException(); } return $userId; }
php
protected function getLikerUserId($userId) { if (is_null($userId)) { $userId = $this->loggedInUserId(); } if (!$userId) { throw new LikerNotDefinedException(); } return $userId; }
[ "protected", "function", "getLikerUserId", "(", "$", "userId", ")", "{", "if", "(", "is_null", "(", "$", "userId", ")", ")", "{", "$", "userId", "=", "$", "this", "->", "loggedInUserId", "(", ")", ";", "}", "if", "(", "!", "$", "userId", ")", "{", ...
Get current user id or get user id passed in. @param int $userId @return int @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Get", "current", "user", "id", "or", "get", "user", "id", "passed", "in", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L391-L402
train
cybercog/laravel-likeable
src/Services/LikeableService.php
LikeableService.likeTypeRelations
private function likeTypeRelations($type) { $relations = [ LikeType::LIKE => [ 'likes', 'likesAndDislikes', ], LikeType::DISLIKE => [ 'dislikes', 'likesAndDislikes', ], ]; if (!isset($relations[$type])) { throw new LikeTypeInvalidException("Like type `{$type}` not supported"); } return $relations[$type]; }
php
private function likeTypeRelations($type) { $relations = [ LikeType::LIKE => [ 'likes', 'likesAndDislikes', ], LikeType::DISLIKE => [ 'dislikes', 'likesAndDislikes', ], ]; if (!isset($relations[$type])) { throw new LikeTypeInvalidException("Like type `{$type}` not supported"); } return $relations[$type]; }
[ "private", "function", "likeTypeRelations", "(", "$", "type", ")", "{", "$", "relations", "=", "[", "LikeType", "::", "LIKE", "=>", "[", "'likes'", ",", "'likesAndDislikes'", ",", "]", ",", "LikeType", "::", "DISLIKE", "=>", "[", "'dislikes'", ",", "'likes...
Resolve list of likeable relations by like type. @param string $type @return array @throws \Cog\Likeable\Exceptions\LikeTypeInvalidException
[ "Resolve", "list", "of", "likeable", "relations", "by", "like", "type", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Services/LikeableService.php#L476-L494
train
cybercog/laravel-likeable
src/Providers/LikeableServiceProvider.php
LikeableServiceProvider.registerContracts
protected function registerContracts() { $this->app->bind(LikeContract::class, Like::class); $this->app->bind(LikeCounterContract::class, LikeCounter::class); $this->app->singleton(LikeableServiceContract::class, LikeableService::class); }
php
protected function registerContracts() { $this->app->bind(LikeContract::class, Like::class); $this->app->bind(LikeCounterContract::class, LikeCounter::class); $this->app->singleton(LikeableServiceContract::class, LikeableService::class); }
[ "protected", "function", "registerContracts", "(", ")", "{", "$", "this", "->", "app", "->", "bind", "(", "LikeContract", "::", "class", ",", "Like", "::", "class", ")", ";", "$", "this", "->", "app", "->", "bind", "(", "LikeCounterContract", "::", "clas...
Register Likeable's classes in the container. @return void
[ "Register", "Likeable", "s", "classes", "in", "the", "container", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Providers/LikeableServiceProvider.php#L82-L87
train
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.scopeWhereDislikedBy
public function scopeWhereDislikedBy(Builder $query, $userId = null) { return app(LikeableServiceContract::class) ->scopeWhereLikedBy($query, LikeType::DISLIKE, $userId); }
php
public function scopeWhereDislikedBy(Builder $query, $userId = null) { return app(LikeableServiceContract::class) ->scopeWhereLikedBy($query, LikeType::DISLIKE, $userId); }
[ "public", "function", "scopeWhereDislikedBy", "(", "Builder", "$", "query", ",", "$", "userId", "=", "null", ")", "{", "return", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "scopeWhereLikedBy", "(", "$", "query", ",", "LikeType", "::", "...
Fetch records that are disliked by a given user id. @param \Illuminate\Database\Eloquent\Builder $query @param int|null $userId @return \Illuminate\Database\Eloquent\Builder @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Fetch", "records", "that", "are", "disliked", "by", "a", "given", "user", "id", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L184-L188
train
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.like
public function like($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::LIKE, $userId); }
php
public function like($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::LIKE, $userId); }
[ "public", "function", "like", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "addLikeTo", "(", "$", "this", ",", "LikeType", "::", "LIKE", ",", "$", "userId", ")", ";", "}" ]
Add a like for model by the given user. @param mixed $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Add", "a", "like", "for", "model", "by", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L224-L227
train
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.dislike
public function dislike($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::DISLIKE, $userId); }
php
public function dislike($userId = null) { app(LikeableServiceContract::class)->addLikeTo($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "dislike", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "addLikeTo", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Add a dislike for model by the given user. @param mixed $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Add", "a", "dislike", "for", "model", "by", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L284-L287
train
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.undislike
public function undislike($userId = null) { app(LikeableServiceContract::class)->removeLikeFrom($this, LikeType::DISLIKE, $userId); }
php
public function undislike($userId = null) { app(LikeableServiceContract::class)->removeLikeFrom($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "undislike", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "removeLikeFrom", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Remove a dislike from this record for the given user. @param int|null $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Remove", "a", "dislike", "from", "this", "record", "for", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L297-L300
train
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.dislikeToggle
public function dislikeToggle($userId = null) { app(LikeableServiceContract::class)->toggleLikeOf($this, LikeType::DISLIKE, $userId); }
php
public function dislikeToggle($userId = null) { app(LikeableServiceContract::class)->toggleLikeOf($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "dislikeToggle", "(", "$", "userId", "=", "null", ")", "{", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "toggleLikeOf", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Toggle dislike for model by the given user. @param mixed $userId If null will use currently logged in user. @return void @throws \Cog\Likeable\Exceptions\LikerNotDefinedException
[ "Toggle", "dislike", "for", "model", "by", "the", "given", "user", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L310-L313
train
cybercog/laravel-likeable
src/Traits/Likeable.php
Likeable.disliked
public function disliked($userId = null) { return app(LikeableServiceContract::class)->isLiked($this, LikeType::DISLIKE, $userId); }
php
public function disliked($userId = null) { return app(LikeableServiceContract::class)->isLiked($this, LikeType::DISLIKE, $userId); }
[ "public", "function", "disliked", "(", "$", "userId", "=", "null", ")", "{", "return", "app", "(", "LikeableServiceContract", "::", "class", ")", "->", "isLiked", "(", "$", "this", ",", "LikeType", "::", "DISLIKE", ",", "$", "userId", ")", ";", "}" ]
Has the user already disliked likeable model. @param int|null $userId @return bool
[ "Has", "the", "user", "already", "disliked", "likeable", "model", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Traits/Likeable.php#L321-L324
train
cybercog/laravel-likeable
src/Console/LikeableRecountCommand.php
LikeableRecountCommand.recountLikesOfAllModelTypes
protected function recountLikesOfAllModelTypes() { $likeableTypes = app(LikeContract::class)->groupBy('likeable_type')->get(); foreach ($likeableTypes as $like) { $this->recountLikesOfModelType($like->likeable_type); } }
php
protected function recountLikesOfAllModelTypes() { $likeableTypes = app(LikeContract::class)->groupBy('likeable_type')->get(); foreach ($likeableTypes as $like) { $this->recountLikesOfModelType($like->likeable_type); } }
[ "protected", "function", "recountLikesOfAllModelTypes", "(", ")", "{", "$", "likeableTypes", "=", "app", "(", "LikeContract", "::", "class", ")", "->", "groupBy", "(", "'likeable_type'", ")", "->", "get", "(", ")", ";", "foreach", "(", "$", "likeableTypes", ...
Recount likes of all model types. @return void @throws \Cog\Likeable\Exceptions\ModelInvalidException
[ "Recount", "likes", "of", "all", "model", "types", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Console/LikeableRecountCommand.php#L87-L93
train
cybercog/laravel-likeable
src/Console/LikeableRecountCommand.php
LikeableRecountCommand.recountLikesOfModelType
protected function recountLikesOfModelType($modelType) { $modelType = $this->normalizeModelType($modelType); $counters = $this->service->fetchLikesCounters($modelType, $this->likeType); $this->service->removeLikeCountersOfType($modelType, $this->likeType); DB::table(app(LikeCounterContract::class)->getTable())->insert($counters); $this->info('All [' . $modelType . '] records likes has been recounted.'); }
php
protected function recountLikesOfModelType($modelType) { $modelType = $this->normalizeModelType($modelType); $counters = $this->service->fetchLikesCounters($modelType, $this->likeType); $this->service->removeLikeCountersOfType($modelType, $this->likeType); DB::table(app(LikeCounterContract::class)->getTable())->insert($counters); $this->info('All [' . $modelType . '] records likes has been recounted.'); }
[ "protected", "function", "recountLikesOfModelType", "(", "$", "modelType", ")", "{", "$", "modelType", "=", "$", "this", "->", "normalizeModelType", "(", "$", "modelType", ")", ";", "$", "counters", "=", "$", "this", "->", "service", "->", "fetchLikesCounters"...
Recount likes of model type. @param string $modelType @return void @throws \Cog\Likeable\Exceptions\ModelInvalidException
[ "Recount", "likes", "of", "model", "type", "." ]
1d5a39b3bc33fc168e7530504a2e84f96f8e90d2
https://github.com/cybercog/laravel-likeable/blob/1d5a39b3bc33fc168e7530504a2e84f96f8e90d2/src/Console/LikeableRecountCommand.php#L103-L114
train
waza-ari/monolog-mysql
src/MySQLHandler/MySQLHandler.php
MySQLHandler.prepareStatement
private function prepareStatement() { //Prepare statement $columns = ""; $fields = ""; foreach ($this->fields as $key => $f) { if ($f == 'id') { continue; } if ($key == 1) { $columns .= "$f"; $fields .= ":$f"; continue; } $columns .= ", $f"; $fields .= ", :$f"; } $this->statement = $this->pdo->prepare( 'INSERT INTO `' . $this->table . '` (' . $columns . ') VALUES (' . $fields . ')' ); }
php
private function prepareStatement() { //Prepare statement $columns = ""; $fields = ""; foreach ($this->fields as $key => $f) { if ($f == 'id') { continue; } if ($key == 1) { $columns .= "$f"; $fields .= ":$f"; continue; } $columns .= ", $f"; $fields .= ", :$f"; } $this->statement = $this->pdo->prepare( 'INSERT INTO `' . $this->table . '` (' . $columns . ') VALUES (' . $fields . ')' ); }
[ "private", "function", "prepareStatement", "(", ")", "{", "//Prepare statement", "$", "columns", "=", "\"\"", ";", "$", "fields", "=", "\"\"", ";", "foreach", "(", "$", "this", "->", "fields", "as", "$", "key", "=>", "$", "f", ")", "{", "if", "(", "$...
Prepare the sql statment depending on the fields that should be written to the database
[ "Prepare", "the", "sql", "statment", "depending", "on", "the", "fields", "that", "should", "be", "written", "to", "the", "database" ]
5b3d75a59254f27b05f528a74df82bd1dd87f182
https://github.com/waza-ari/monolog-mysql/blob/5b3d75a59254f27b05f528a74df82bd1dd87f182/src/MySQLHandler/MySQLHandler.php#L133-L155
train
laravel-admin-extensions/env-manager
src/Env.php
Env.getEnv
private function getEnv($id = null) { $string = file_get_contents($this->env); $string = preg_split('/\n+/', $string); $array = []; foreach ($string as $k => $one) { if (preg_match('/^(#\s)/', $one) === 1 || preg_match('/^([\\n\\r]+)/', $one)) { continue; } $entry = explode("=", $one, 2); if (!empty($entry[0])) { $array[] = ['id' => $k + 1, 'key' => $entry[0], 'value' => isset($entry[1]) ? $entry[1] : null]; } } if (empty($id)) { return $array; } $index = array_search($id, array_column($array, 'id')); return $array[$index]; }
php
private function getEnv($id = null) { $string = file_get_contents($this->env); $string = preg_split('/\n+/', $string); $array = []; foreach ($string as $k => $one) { if (preg_match('/^(#\s)/', $one) === 1 || preg_match('/^([\\n\\r]+)/', $one)) { continue; } $entry = explode("=", $one, 2); if (!empty($entry[0])) { $array[] = ['id' => $k + 1, 'key' => $entry[0], 'value' => isset($entry[1]) ? $entry[1] : null]; } } if (empty($id)) { return $array; } $index = array_search($id, array_column($array, 'id')); return $array[$index]; }
[ "private", "function", "getEnv", "(", "$", "id", "=", "null", ")", "{", "$", "string", "=", "file_get_contents", "(", "$", "this", "->", "env", ")", ";", "$", "string", "=", "preg_split", "(", "'/\\n+/'", ",", "$", "string", ")", ";", "$", "array", ...
Get .env variable. @param null $id @return array|mixed
[ "Get", ".", "env", "variable", "." ]
f9c83b213e97a36bb500b25a5357aae2d6435958
https://github.com/laravel-admin-extensions/env-manager/blob/f9c83b213e97a36bb500b25a5357aae2d6435958/src/Env.php#L74-L94
train
laravel-admin-extensions/env-manager
src/Env.php
Env.setEnv
private function setEnv($key, $value) { $array = $this->getEnv(); $index = array_search($key, array_column($array, 'key')); if ($index !== false) { $array[$index]['value'] = $value; // 更新 } else { array_push($array, ['key' => $key, 'value' => $value]); // 新增 } return $this->saveEnv($array); }
php
private function setEnv($key, $value) { $array = $this->getEnv(); $index = array_search($key, array_column($array, 'key')); if ($index !== false) { $array[$index]['value'] = $value; // 更新 } else { array_push($array, ['key' => $key, 'value' => $value]); // 新增 } return $this->saveEnv($array); }
[ "private", "function", "setEnv", "(", "$", "key", ",", "$", "value", ")", "{", "$", "array", "=", "$", "this", "->", "getEnv", "(", ")", ";", "$", "index", "=", "array_search", "(", "$", "key", ",", "array_column", "(", "$", "array", ",", "'key'", ...
Update or create .env variable. @param $key @param $value @return bool
[ "Update", "or", "create", ".", "env", "variable", "." ]
f9c83b213e97a36bb500b25a5357aae2d6435958
https://github.com/laravel-admin-extensions/env-manager/blob/f9c83b213e97a36bb500b25a5357aae2d6435958/src/Env.php#L102-L112
train
laravel-admin-extensions/env-manager
src/Env.php
Env.saveEnv
private function saveEnv($array) { if (is_array($array)) { $newArray = []; $i = 0; foreach ($array as $env) { if (preg_match('/\s/', $env['value']) > 0 && (strpos($env['value'], '"') > 0 && strpos($env['value'], '"', -0) > 0)) { $env['value'] = '"'.$env['value'].'"'; } $newArray[$i] = $env['key']."=".$env['value']; $i++; } $newArray = implode("\n", $newArray); file_put_contents($this->env, $newArray); return true; } return false; }
php
private function saveEnv($array) { if (is_array($array)) { $newArray = []; $i = 0; foreach ($array as $env) { if (preg_match('/\s/', $env['value']) > 0 && (strpos($env['value'], '"') > 0 && strpos($env['value'], '"', -0) > 0)) { $env['value'] = '"'.$env['value'].'"'; } $newArray[$i] = $env['key']."=".$env['value']; $i++; } $newArray = implode("\n", $newArray); file_put_contents($this->env, $newArray); return true; } return false; }
[ "private", "function", "saveEnv", "(", "$", "array", ")", "{", "if", "(", "is_array", "(", "$", "array", ")", ")", "{", "$", "newArray", "=", "[", "]", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "array", "as", "$", "env", ")", "{", "i...
Save .env variable. @param $array @return bool
[ "Save", ".", "env", "variable", "." ]
f9c83b213e97a36bb500b25a5357aae2d6435958
https://github.com/laravel-admin-extensions/env-manager/blob/f9c83b213e97a36bb500b25a5357aae2d6435958/src/Env.php#L119-L137
train
LeaseWeb/LswMemcacheBundle
Command/StatisticsCommand.php
StatisticsCommand.interact
protected function interact(InputInterface $input, OutputInterface $output) { if (!$input->getArgument('pool')) { $pool = (new InteractHelper())->askForPool($this, $input, $output); $input->setArgument('pool', $pool); } }
php
protected function interact(InputInterface $input, OutputInterface $output) { if (!$input->getArgument('pool')) { $pool = (new InteractHelper())->askForPool($this, $input, $output); $input->setArgument('pool', $pool); } }
[ "protected", "function", "interact", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "if", "(", "!", "$", "input", "->", "getArgument", "(", "'pool'", ")", ")", "{", "$", "pool", "=", "(", "new", "InteractHelper", "(...
Choose the pool @param InputInterface $input Input interface @param OutputInterface $output Output interface @see Command @return mixed
[ "Choose", "the", "pool" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/StatisticsCommand.php#L62-L68
train
LeaseWeb/LswMemcacheBundle
Command/StatisticsCommand.php
StatisticsCommand.formatStats
protected function formatStats($stats) { if (!$stats) { return "No statistics returned.\n"; } $out = "Servers found: " . count($stats) . "\n\n"; foreach ($stats as $host => $item) { if (!is_array($item) || count($item) == 0) { $out .= " <error>" . $host . "</error>\n"; continue; } $out .= "<info>Host:\t" . $host . "</info>\n"; $out .= "\tUsage: " . $this->formatUsage($item['bytes'], $item['limit_maxbytes']) . "\n"; $out .= "\tUptime: " . $this->formatUptime($item['uptime']) . "\n"; $out .= "\tOpen Connections: " . $item['curr_connections'] . "\n"; $out .= "\tHits: " . $item['get_hits'] . "\n"; $out .= "\tMisses: " . $item['get_misses'] . "\n"; if ($item['get_hits'] + $item['get_misses'] > 0 ) { $out .= "\tHelpfulness: " . round($item['get_hits'] / ($item['get_hits'] + $item['get_misses']) * 100, 2) . "%\n"; } } return $out; }
php
protected function formatStats($stats) { if (!$stats) { return "No statistics returned.\n"; } $out = "Servers found: " . count($stats) . "\n\n"; foreach ($stats as $host => $item) { if (!is_array($item) || count($item) == 0) { $out .= " <error>" . $host . "</error>\n"; continue; } $out .= "<info>Host:\t" . $host . "</info>\n"; $out .= "\tUsage: " . $this->formatUsage($item['bytes'], $item['limit_maxbytes']) . "\n"; $out .= "\tUptime: " . $this->formatUptime($item['uptime']) . "\n"; $out .= "\tOpen Connections: " . $item['curr_connections'] . "\n"; $out .= "\tHits: " . $item['get_hits'] . "\n"; $out .= "\tMisses: " . $item['get_misses'] . "\n"; if ($item['get_hits'] + $item['get_misses'] > 0 ) { $out .= "\tHelpfulness: " . round($item['get_hits'] / ($item['get_hits'] + $item['get_misses']) * 100, 2) . "%\n"; } } return $out; }
[ "protected", "function", "formatStats", "(", "$", "stats", ")", "{", "if", "(", "!", "$", "stats", ")", "{", "return", "\"No statistics returned.\\n\"", ";", "}", "$", "out", "=", "\"Servers found: \"", ".", "count", "(", "$", "stats", ")", ".", "\"\\n\\n\...
Format the raw array for the command line report @param array $stats An array of memcache::extendedstats @return string ConsoleComponent-formatted output, suitable for ->writeln() usage
[ "Format", "the", "raw", "array", "for", "the", "command", "line", "report" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/StatisticsCommand.php#L77-L103
train
LeaseWeb/LswMemcacheBundle
Command/StatisticsCommand.php
StatisticsCommand.formatUptime
protected function formatUptime($uptime ) { $days = floor($uptime / 24 / 60 / 60); $daysRemainder = $uptime - ($days * 24 * 60 * 60); $hours = floor($daysRemainder / 60 / 60); $hoursRemainder = $daysRemainder - ($hours * 60 * 60); $minutes = floor($hoursRemainder / 60); $minutesRemainder = $hoursRemainder - ($minutes * 60); $seconds = $minutesRemainder; $out = $uptime . ' seconds ('; if ($days > 0) { $out .= $days . ' days, '; } if ($hours > 0) { $out .= $hours . ' hours, '; } if ($minutes > 0) { $out .= $minutes . ' minutes, '; } if ($seconds > 0) { $out .= $seconds . ' seconds'; } return $out . ')'; }
php
protected function formatUptime($uptime ) { $days = floor($uptime / 24 / 60 / 60); $daysRemainder = $uptime - ($days * 24 * 60 * 60); $hours = floor($daysRemainder / 60 / 60); $hoursRemainder = $daysRemainder - ($hours * 60 * 60); $minutes = floor($hoursRemainder / 60); $minutesRemainder = $hoursRemainder - ($minutes * 60); $seconds = $minutesRemainder; $out = $uptime . ' seconds ('; if ($days > 0) { $out .= $days . ' days, '; } if ($hours > 0) { $out .= $hours . ' hours, '; } if ($minutes > 0) { $out .= $minutes . ' minutes, '; } if ($seconds > 0) { $out .= $seconds . ' seconds'; } return $out . ')'; }
[ "protected", "function", "formatUptime", "(", "$", "uptime", ")", "{", "$", "days", "=", "floor", "(", "$", "uptime", "/", "24", "/", "60", "/", "60", ")", ";", "$", "daysRemainder", "=", "$", "uptime", "-", "(", "$", "days", "*", "24", "*", "60"...
Formats the uptime to be friendlier @param integer $uptime Cache server uptime (in seconds) @return string A short string with friendly formatting
[ "Formats", "the", "uptime", "to", "be", "friendlier" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/StatisticsCommand.php#L133-L158
train
LeaseWeb/LswMemcacheBundle
Firewall/FirewallHandler.php
FirewallHandler.onKernelRequest
public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($this->reverseProxies) { $request->setTrustedProxies($this->reverseProxies); } if ($this->xForwardedFor) { $request->setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->xForwardedFor); } $ip = $request->getClientIp(); $start = microtime(true); $this->key=$this->prefix.'_'.$ip; $this->memcache->add($this->key,0,false,$this->lockMaxWait); while (true) { $this->incremented = true; if ($this->memcache->increment($this->key)<=$this->concurrency) { break; } $this->incremented = false; $this->memcache->decrement($this->key); if (!$this->spinLockWait || microtime(true)-$start>$this->lockMaxWait) { throw new TooManyRequestsHttpException(); } usleep($this->spinLockWait); } }
php
public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); if ($this->reverseProxies) { $request->setTrustedProxies($this->reverseProxies); } if ($this->xForwardedFor) { $request->setTrustedHeaderName(Request::HEADER_CLIENT_IP, $this->xForwardedFor); } $ip = $request->getClientIp(); $start = microtime(true); $this->key=$this->prefix.'_'.$ip; $this->memcache->add($this->key,0,false,$this->lockMaxWait); while (true) { $this->incremented = true; if ($this->memcache->increment($this->key)<=$this->concurrency) { break; } $this->incremented = false; $this->memcache->decrement($this->key); if (!$this->spinLockWait || microtime(true)-$start>$this->lockMaxWait) { throw new TooManyRequestsHttpException(); } usleep($this->spinLockWait); } }
[ "public", "function", "onKernelRequest", "(", "GetResponseEvent", "$", "event", ")", "{", "if", "(", "!", "$", "event", "->", "isMasterRequest", "(", ")", ")", "{", "return", ";", "}", "$", "request", "=", "$", "event", "->", "getRequest", "(", ")", ";...
If the current concurrency is too high, delay or throw a TooManyRequestsHttpException @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event Event @throws \Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException
[ "If", "the", "current", "concurrency", "is", "too", "high", "delay", "or", "throw", "a", "TooManyRequestsHttpException" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Firewall/FirewallHandler.php#L107-L139
train
LeaseWeb/LswMemcacheBundle
Firewall/FirewallHandler.php
FirewallHandler.onKernelTerminate
public function onKernelTerminate(PostResponseEvent $event) { if (!$this->incremented) { return; } $this->incremented = false; $this->memcache->decrement($this->key); }
php
public function onKernelTerminate(PostResponseEvent $event) { if (!$this->incremented) { return; } $this->incremented = false; $this->memcache->decrement($this->key); }
[ "public", "function", "onKernelTerminate", "(", "PostResponseEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "incremented", ")", "{", "return", ";", "}", "$", "this", "->", "incremented", "=", "false", ";", "$", "this", "->", "memcache...
If the current request has ended, decrement concurrency counter @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event Event
[ "If", "the", "current", "request", "has", "ended", "decrement", "concurrency", "counter" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Firewall/FirewallHandler.php#L147-L155
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addClientsSection
private function addClientsSection() { $tree = new TreeBuilder(); $node = $tree->root('pools'); $node ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ->children() ->arrayNode('servers') ->requiresAtLeastOneElement() ->prototype('array') ->children() ->scalarNode('host') ->cannotBeEmpty() ->isRequired() ->end() ->scalarNode('tcp_port') ->defaultValue(11211) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->scalarNode('udp_port') ->defaultValue(0) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->booleanNode('persistent') ->defaultTrue() ->end() ->scalarNode('weight') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('weight must be numeric') ->end() ->end() ->scalarNode('timeout') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('timeout must be numeric') ->end() ->end() ->scalarNode('retry_interval') ->defaultValue(15) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('retry_interval must be numeric') ->end() ->end() ->end() ->end() ->end() ->append($this->addMemcacheOptionsSection()) ->end() ->end() ->end(); return $node; }
php
private function addClientsSection() { $tree = new TreeBuilder(); $node = $tree->root('pools'); $node ->requiresAtLeastOneElement() ->useAttributeAsKey('name') ->prototype('array') ->children() ->arrayNode('servers') ->requiresAtLeastOneElement() ->prototype('array') ->children() ->scalarNode('host') ->cannotBeEmpty() ->isRequired() ->end() ->scalarNode('tcp_port') ->defaultValue(11211) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->scalarNode('udp_port') ->defaultValue(0) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('port must be numeric') ->end() ->end() ->booleanNode('persistent') ->defaultTrue() ->end() ->scalarNode('weight') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('weight must be numeric') ->end() ->end() ->scalarNode('timeout') ->defaultValue(1) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('timeout must be numeric') ->end() ->end() ->scalarNode('retry_interval') ->defaultValue(15) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('retry_interval must be numeric') ->end() ->end() ->end() ->end() ->end() ->append($this->addMemcacheOptionsSection()) ->end() ->end() ->end(); return $node; }
[ "private", "function", "addClientsSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'pools'", ")", ";", "$", "node", "->", "requiresAtLeastOneElement", "(", ")", "->", "us...
Configure the "lsw_memcache.pools" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "pools", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L40-L105
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addSessionSupportSection
private function addSessionSupportSection() { $tree = new TreeBuilder(); $node = $tree->root('session'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->booleanNode('auto_load')->defaultTrue()->end() ->scalarNode('prefix')->defaultValue('lmbs')->end() ->scalarNode('ttl')->end() ->booleanNode('locking')->defaultTrue()->end() ->scalarNode('spin_lock_wait')->defaultValue(150000)->end() ->scalarNode('lock_max_wait') ->defaultNull() ->validate() ->always(function($v) { if (null === $v) { return $v; } if (!is_numeric($v)) { throw new InvalidConfigurationException("Option 'lock_max_wait' must either be NULL or an integer value"); } return (int) $v; }) ->end() ->end() ->end(); return $node; }
php
private function addSessionSupportSection() { $tree = new TreeBuilder(); $node = $tree->root('session'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->booleanNode('auto_load')->defaultTrue()->end() ->scalarNode('prefix')->defaultValue('lmbs')->end() ->scalarNode('ttl')->end() ->booleanNode('locking')->defaultTrue()->end() ->scalarNode('spin_lock_wait')->defaultValue(150000)->end() ->scalarNode('lock_max_wait') ->defaultNull() ->validate() ->always(function($v) { if (null === $v) { return $v; } if (!is_numeric($v)) { throw new InvalidConfigurationException("Option 'lock_max_wait' must either be NULL or an integer value"); } return (int) $v; }) ->end() ->end() ->end(); return $node; }
[ "private", "function", "addSessionSupportSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'session'", ")", ";", "$", "node", "->", "children", "(", ")", "->", "scalarNode...
Configure the "lsw_memcache.session" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "session", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L112-L144
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addDoctrineSection
private function addDoctrineSection() { $tree = new TreeBuilder(); $node = $tree->root('doctrine'); foreach (array('metadata_cache', 'result_cache', 'query_cache') as $type) { $node->children() ->arrayNode($type) ->canBeUnset() ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbd')->end() ->end() ->fixXmlConfig('entity_manager') ->children() ->arrayNode('entity_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('document_manager') ->children() ->arrayNode('document_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->end() ->end(); } return $node; }
php
private function addDoctrineSection() { $tree = new TreeBuilder(); $node = $tree->root('doctrine'); foreach (array('metadata_cache', 'result_cache', 'query_cache') as $type) { $node->children() ->arrayNode($type) ->canBeUnset() ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbd')->end() ->end() ->fixXmlConfig('entity_manager') ->children() ->arrayNode('entity_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->fixXmlConfig('document_manager') ->children() ->arrayNode('document_managers') ->defaultValue(array()) ->beforeNormalization()->ifString()->then(function($v) { return (array) $v; })->end() ->prototype('scalar')->end() ->end() ->end() ->end() ->end(); } return $node; }
[ "private", "function", "addDoctrineSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'doctrine'", ")", ";", "foreach", "(", "array", "(", "'metadata_cache'", ",", "'result_c...
Configure the "lsw_memcache.doctrine" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "doctrine", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L151-L185
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addFirewallSection
private function addFirewallSection() { $tree = new TreeBuilder(); $node = $tree->root('firewall'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbf')->end() ->scalarNode('concurrency') ->defaultValue(10) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('concurrency must be numeric') ->end() ->end() ->scalarNode('spin_lock_wait') ->defaultValue(150000) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('spin_lock_wait must be numeric') ->end() ->end() ->scalarNode('lock_max_wait') ->defaultValue(300) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('lock_max_wait must be numeric') ->end() ->end() ->arrayNode('reverse_proxies') ->defaultValue(array()) ->prototype('scalar')->end() ->end() ->scalarNode('x_forwarded_for')->defaultFalse()->end() ->end() ->end(); return $node; }
php
private function addFirewallSection() { $tree = new TreeBuilder(); $node = $tree->root('firewall'); $node ->children() ->scalarNode('pool')->isRequired()->end() ->scalarNode('prefix')->defaultValue('lmbf')->end() ->scalarNode('concurrency') ->defaultValue(10) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('concurrency must be numeric') ->end() ->end() ->scalarNode('spin_lock_wait') ->defaultValue(150000) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('spin_lock_wait must be numeric') ->end() ->end() ->scalarNode('lock_max_wait') ->defaultValue(300) ->validate() ->ifTrue(function ($v) { return !is_numeric($v); }) ->thenInvalid('lock_max_wait must be numeric') ->end() ->end() ->arrayNode('reverse_proxies') ->defaultValue(array()) ->prototype('scalar')->end() ->end() ->scalarNode('x_forwarded_for')->defaultFalse()->end() ->end() ->end(); return $node; }
[ "private", "function", "addFirewallSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'firewall'", ")", ";", "$", "node", "->", "children", "(", ")", "->", "scalarNode", ...
Configure the "lsw_memcache.firewall" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "firewall", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L192-L231
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/Configuration.php
Configuration.addMemcacheOptionsSection
private function addMemcacheOptionsSection() { $tree = new TreeBuilder(); $node = $tree->root('options'); // Memcache only configs $node ->addDefaultsIfNotSet() ->children() ->booleanNode('allow_failover')->defaultTrue()->end() ->scalarNode('max_failover_attempts') ->defaultValue(20) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('max_failover_attempts option must be numeric') ->end() ->end() ->scalarNode('default_port') ->defaultValue(11211) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('default_port option must be numeric') ->end() ->end() ->scalarNode('chunk_size') ->defaultValue(32768) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('chunk_size option must be numeric') ->end() ->end() ->scalarNode('protocol') ->defaultValue('ascii') ->validate() ->ifNotInArray(array('ascii', 'binary')) ->thenInvalid('protocol option must be: ascii or binary') ->end() ->end() ->scalarNode('hash_strategy') ->defaultValue('consistent') ->validate() ->ifNotInArray(array('standard', 'consistent')) ->thenInvalid('hash_strategy option must be: standard or consistent') ->end() ->end() ->scalarNode('hash_function') ->defaultValue('crc32') ->validate() ->ifNotInArray(array('crc32', 'fnv')) ->thenInvalid('hash_function option must be: crc32 or fnv') ->end() ->end() ->booleanNode('redundancy')->defaultTrue()->end() ->scalarNode('session_redundancy') ->defaultValue(2) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('session_redundancy option must be numeric') ->end() ->end() ->scalarNode('compress_threshold') ->defaultValue(20000) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('compress_threshold option must be numeric') ->end() ->end() ->scalarNode('lock_timeout') ->defaultValue(15) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('lock_timeout option must be numeric') ->end() ->end() ->end() ->end(); return $node; }
php
private function addMemcacheOptionsSection() { $tree = new TreeBuilder(); $node = $tree->root('options'); // Memcache only configs $node ->addDefaultsIfNotSet() ->children() ->booleanNode('allow_failover')->defaultTrue()->end() ->scalarNode('max_failover_attempts') ->defaultValue(20) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('max_failover_attempts option must be numeric') ->end() ->end() ->scalarNode('default_port') ->defaultValue(11211) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('default_port option must be numeric') ->end() ->end() ->scalarNode('chunk_size') ->defaultValue(32768) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('chunk_size option must be numeric') ->end() ->end() ->scalarNode('protocol') ->defaultValue('ascii') ->validate() ->ifNotInArray(array('ascii', 'binary')) ->thenInvalid('protocol option must be: ascii or binary') ->end() ->end() ->scalarNode('hash_strategy') ->defaultValue('consistent') ->validate() ->ifNotInArray(array('standard', 'consistent')) ->thenInvalid('hash_strategy option must be: standard or consistent') ->end() ->end() ->scalarNode('hash_function') ->defaultValue('crc32') ->validate() ->ifNotInArray(array('crc32', 'fnv')) ->thenInvalid('hash_function option must be: crc32 or fnv') ->end() ->end() ->booleanNode('redundancy')->defaultTrue()->end() ->scalarNode('session_redundancy') ->defaultValue(2) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('session_redundancy option must be numeric') ->end() ->end() ->scalarNode('compress_threshold') ->defaultValue(20000) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('compress_threshold option must be numeric') ->end() ->end() ->scalarNode('lock_timeout') ->defaultValue(15) ->validate() ->ifTrue(function($v) { return !is_numeric($v); }) ->thenInvalid('lock_timeout option must be numeric') ->end() ->end() ->end() ->end(); return $node; }
[ "private", "function", "addMemcacheOptionsSection", "(", ")", "{", "$", "tree", "=", "new", "TreeBuilder", "(", ")", ";", "$", "node", "=", "$", "tree", "->", "root", "(", "'options'", ")", ";", "// Memcache only configs", "$", "node", "->", "addDefaultsIfNo...
Configure the "lsw_memcache.options" section @return ArrayNodeDefinition
[ "Configure", "the", "lsw_memcache", ".", "options", "section" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/Configuration.php#L238-L317
train
LeaseWeb/LswMemcacheBundle
Command/ClearCommand.php
ClearCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $pool = $input->getArgument('pool'); try { $this->memcache = $this->getContainer()->get('memcache.'.$pool); $output->writeln($this->memcache->flush()?'<info>OK</info>':'<error>ERROR</error>'); } catch (ServiceNotFoundException $e) { $output->writeln("<error>pool '$pool' is not found</error>"); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $pool = $input->getArgument('pool'); try { $this->memcache = $this->getContainer()->get('memcache.'.$pool); $output->writeln($this->memcache->flush()?'<info>OK</info>':'<error>ERROR</error>'); } catch (ServiceNotFoundException $e) { $output->writeln("<error>pool '$pool' is not found</error>"); } }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "$", "pool", "=", "$", "input", "->", "getArgument", "(", "'pool'", ")", ";", "try", "{", "$", "this", "->", "memcache", "=", "$", ...
Execute the CLI task @param InputInterface $input Command input @param OutputInterface $output Command output @return void
[ "Execute", "the", "CLI", "task" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/Command/ClearCommand.php#L46-L57
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/LswMemcacheExtension.php
LswMemcacheExtension.enableSessionSupport
private function enableSessionSupport($config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['session']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the session support!', $pool)); } // calculate options $sessionOptions = $container->getParameter('session.storage.options'); $options = array(); if (isset($config['session']['ttl'])) { $options['expiretime'] = $config['session']['ttl']; } elseif (isset($sessionOptions['cookie_lifetime'])) { $options['expiretime'] = $sessionOptions['cookie_lifetime']; } $options['prefix'] = $config['session']['prefix']; $options['locking'] = $config['session']['locking']; $options['spin_lock_wait'] = $config['session']['spin_lock_wait']; $options['lock_max_wait'] = $config['session']['lock_max_wait']; // set the auto_load parameter $container->setParameter('memcache.session_handler.auto_load', $config['session']['auto_load']); // load the session handler $definition = new Definition($container->getParameter('memcache.session_handler.class')); $container->setDefinition('memcache.session_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $this->addClassesToCompile(array($definition->getClass())); }
php
private function enableSessionSupport($config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['session']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the session support!', $pool)); } // calculate options $sessionOptions = $container->getParameter('session.storage.options'); $options = array(); if (isset($config['session']['ttl'])) { $options['expiretime'] = $config['session']['ttl']; } elseif (isset($sessionOptions['cookie_lifetime'])) { $options['expiretime'] = $sessionOptions['cookie_lifetime']; } $options['prefix'] = $config['session']['prefix']; $options['locking'] = $config['session']['locking']; $options['spin_lock_wait'] = $config['session']['spin_lock_wait']; $options['lock_max_wait'] = $config['session']['lock_max_wait']; // set the auto_load parameter $container->setParameter('memcache.session_handler.auto_load', $config['session']['auto_load']); // load the session handler $definition = new Definition($container->getParameter('memcache.session_handler.class')); $container->setDefinition('memcache.session_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $this->addClassesToCompile(array($definition->getClass())); }
[ "private", "function", "enableSessionSupport", "(", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "// make sure the pool is specified and it exists", "$", "pool", "=", "$", "config", "[", "'session'", "]", "[", "'pool'", "]", ";", "if", "(", ...
Enables session support using Memcache based on the configuration @param string $config Configuration for bundle @param ContainerBuilder $container Service container @return void
[ "Enables", "session", "support", "using", "Memcache", "based", "on", "the", "configuration" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/LswMemcacheExtension.php#L58-L89
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/LswMemcacheExtension.php
LswMemcacheExtension.loadFirewall
protected function loadFirewall(array $config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['firewall']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the firewall!', $pool)); } // calculate options $options = array(); $options['prefix'] = $config['firewall']['prefix']; $options['concurrency'] = $config['firewall']['concurrency']; $options['spin_lock_wait'] = $config['firewall']['spin_lock_wait']; $options['lock_max_wait'] = $config['firewall']['lock_max_wait']; $options['reverse_proxies'] = $config['firewall']['reverse_proxies']; $options['x_forwarded_for'] = $config['firewall']['x_forwarded_for']; // load the firewall handler $definition = new Definition($container->getParameter('memcache.firewall_handler.class')); $container->setDefinition('memcache.firewall_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $definition->addTag('kernel.event_listener', array('event'=>'kernel.request','method'=>'onKernelRequest')); $definition->addTag('kernel.event_listener', array('event'=>'kernel.terminate','method'=>'onKernelTerminate')); $this->addClassesToCompile(array($definition->getClass())); }
php
protected function loadFirewall(array $config, ContainerBuilder $container) { // make sure the pool is specified and it exists $pool = $config['firewall']['pool']; if (null === $pool) { return; } if (!isset($config['pools']) || !isset($config['pools'][$pool])) { throw new \LogicException(sprintf('The pool "%s" does not exist! Cannot enable the firewall!', $pool)); } // calculate options $options = array(); $options['prefix'] = $config['firewall']['prefix']; $options['concurrency'] = $config['firewall']['concurrency']; $options['spin_lock_wait'] = $config['firewall']['spin_lock_wait']; $options['lock_max_wait'] = $config['firewall']['lock_max_wait']; $options['reverse_proxies'] = $config['firewall']['reverse_proxies']; $options['x_forwarded_for'] = $config['firewall']['x_forwarded_for']; // load the firewall handler $definition = new Definition($container->getParameter('memcache.firewall_handler.class')); $container->setDefinition('memcache.firewall_handler', $definition); $definition ->addArgument(new Reference(sprintf('memcache.%s', $pool))) ->addArgument($options); $definition->addTag('kernel.event_listener', array('event'=>'kernel.request','method'=>'onKernelRequest')); $definition->addTag('kernel.event_listener', array('event'=>'kernel.terminate','method'=>'onKernelTerminate')); $this->addClassesToCompile(array($definition->getClass())); }
[ "protected", "function", "loadFirewall", "(", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "// make sure the pool is specified and it exists", "$", "pool", "=", "$", "config", "[", "'firewall'", "]", "[", "'pool'", "]", ";", "if", ...
Loads the Firewall configuration. @param array $config A configuration array @param ContainerBuilder $container A ContainerBuilder instance
[ "Loads", "the", "Firewall", "configuration", "." ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/LswMemcacheExtension.php#L136-L163
train
LeaseWeb/LswMemcacheBundle
DependencyInjection/LswMemcacheExtension.php
LswMemcacheExtension.newMemcacheClient
private function newMemcacheClient($name, array $config, ContainerBuilder $container) { // Check if the Memcache extension is loaded if (!extension_loaded('memcache')) { throw new \LogicException('Memcache extension is not loaded! To configure pools it MUST be loaded!'); } $memcache = new Definition('Lsw\MemcacheBundle\Cache\AntiDogPileMemcache'); $memcache->addArgument(new Parameter('kernel.debug')); // Add servers to the memcache pool foreach ($config['servers'] as $s) { $server = array( $s['host'], $s['tcp_port'], $s['udp_port'], $s['persistent'], $s['weight'], $s['timeout'], $s['retry_interval'] ); if ($s['host']) { $memcache->addMethodCall('addServer', $server); } } $memcache->addArgument($config['options']); $options = array(); // Make sure that config values are human readable foreach ($config['options'] as $key => $value) { $options[$key] = var_export($value, true); } // Add the service to the container $serviceName = sprintf('memcache.%s', $name); $container->setDefinition($serviceName, $memcache); // Add the service to the data collector if ($container->hasDefinition('memcache.data_collector')) { $definition = $container->getDefinition('memcache.data_collector'); $definition->addMethodCall('addClient', array($name, $options, new Reference($serviceName))); } }
php
private function newMemcacheClient($name, array $config, ContainerBuilder $container) { // Check if the Memcache extension is loaded if (!extension_loaded('memcache')) { throw new \LogicException('Memcache extension is not loaded! To configure pools it MUST be loaded!'); } $memcache = new Definition('Lsw\MemcacheBundle\Cache\AntiDogPileMemcache'); $memcache->addArgument(new Parameter('kernel.debug')); // Add servers to the memcache pool foreach ($config['servers'] as $s) { $server = array( $s['host'], $s['tcp_port'], $s['udp_port'], $s['persistent'], $s['weight'], $s['timeout'], $s['retry_interval'] ); if ($s['host']) { $memcache->addMethodCall('addServer', $server); } } $memcache->addArgument($config['options']); $options = array(); // Make sure that config values are human readable foreach ($config['options'] as $key => $value) { $options[$key] = var_export($value, true); } // Add the service to the container $serviceName = sprintf('memcache.%s', $name); $container->setDefinition($serviceName, $memcache); // Add the service to the data collector if ($container->hasDefinition('memcache.data_collector')) { $definition = $container->getDefinition('memcache.data_collector'); $definition->addMethodCall('addClient', array($name, $options, new Reference($serviceName))); } }
[ "private", "function", "newMemcacheClient", "(", "$", "name", ",", "array", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "// Check if the Memcache extension is loaded", "if", "(", "!", "extension_loaded", "(", "'memcache'", ")", ")", "{", "t...
Creates a new Memcache definition @param string $name Client name @param array $config Client configuration @param ContainerBuilder $container Service container @throws \LogicException
[ "Creates", "a", "new", "Memcache", "definition" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DependencyInjection/LswMemcacheExtension.php#L189-L231
train
LeaseWeb/LswMemcacheBundle
DataCollector/MemcacheDataCollector.php
MemcacheDataCollector.addClient
public function addClient($name, $options, LoggingMemcacheInterface $memcache) { $this->pools[$name] = $memcache; $this->options[$name] = $options; }
php
public function addClient($name, $options, LoggingMemcacheInterface $memcache) { $this->pools[$name] = $memcache; $this->options[$name] = $options; }
[ "public", "function", "addClient", "(", "$", "name", ",", "$", "options", ",", "LoggingMemcacheInterface", "$", "memcache", ")", "{", "$", "this", "->", "pools", "[", "$", "name", "]", "=", "$", "memcache", ";", "$", "this", "->", "options", "[", "$", ...
Add a Memcache object to the collector @param string $name Name of the Memcache pool @param array $options Options for Memcache pool @param LoggingMemcacheInterface $memcache Logging Memcache object @return void
[ "Add", "a", "Memcache", "object", "to", "the", "collector" ]
da91b5b1dbbc8a3f27f203325398607a7eaa00a1
https://github.com/LeaseWeb/LswMemcacheBundle/blob/da91b5b1dbbc8a3f27f203325398607a7eaa00a1/DataCollector/MemcacheDataCollector.php#L40-L44
train
geerlingguy/Request
JJG/Request.php
Request.checkResponseForContent
public function checkResponseForContent($content = '') { if ($this->httpCode == 200 && !empty($this->responseBody)) { if (strpos($this->responseBody, $content) !== FALSE) { return TRUE; } } return FALSE; }
php
public function checkResponseForContent($content = '') { if ($this->httpCode == 200 && !empty($this->responseBody)) { if (strpos($this->responseBody, $content) !== FALSE) { return TRUE; } } return FALSE; }
[ "public", "function", "checkResponseForContent", "(", "$", "content", "=", "''", ")", "{", "if", "(", "$", "this", "->", "httpCode", "==", "200", "&&", "!", "empty", "(", "$", "this", "->", "responseBody", ")", ")", "{", "if", "(", "strpos", "(", "$"...
Check for content in the HTTP response body. This method should not be called until after execute(), and will only check for the content if the response code is 200 OK. @param string $content String for which the response will be checked. @return bool TRUE if $content was found in the response, FALSE otherwise.
[ "Check", "for", "content", "in", "the", "HTTP", "response", "body", "." ]
16d33dd56f2332fe259f6acfd0bdc2bb571738f2
https://github.com/geerlingguy/Request/blob/16d33dd56f2332fe259f6acfd0bdc2bb571738f2/JJG/Request.php#L249-L256
train
geerlingguy/Request
JJG/Request.php
Request.execute
public function execute() { // Set a default latency value. $latency = 0; // Set up cURL options. $ch = curl_init(); // If there are basic authentication credentials, use them. if (isset($this->userpwd)) { curl_setopt($ch, CURLOPT_USERPWD, $this->userpwd); } // If cookies are enabled, use them. if ($this->cookiesEnabled) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiePath); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiePath); } // Send a custom request if set (instead of standard GET). if (isset($this->requestType)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->requestType); // If POST fields are given, and this is a POST request, add fields. if ($this->requestType == 'POST' && isset($this->postFields)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postFields); } } // Don't print the response; return it from curl_exec(). curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $this->address); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); // Follow redirects (maximum of 5). curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // SSL support. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl); // Set a custom UA string so people can identify our requests. curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent); // Output the header in the response. curl_setopt($ch, CURLOPT_HEADER, TRUE); $response = curl_exec($ch); $error = curl_error($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $time = curl_getinfo($ch, CURLINFO_TOTAL_TIME); curl_close($ch); // Set the header, response, error and http code. $this->responseHeader = substr($response, 0, $header_size); $this->responseBody = substr($response, $header_size); $this->error = $error; $this->httpCode = $http_code; // Convert the latency to ms. $this->latency = round($time * 1000); }
php
public function execute() { // Set a default latency value. $latency = 0; // Set up cURL options. $ch = curl_init(); // If there are basic authentication credentials, use them. if (isset($this->userpwd)) { curl_setopt($ch, CURLOPT_USERPWD, $this->userpwd); } // If cookies are enabled, use them. if ($this->cookiesEnabled) { curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookiePath); curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookiePath); } // Send a custom request if set (instead of standard GET). if (isset($this->requestType)) { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->requestType); // If POST fields are given, and this is a POST request, add fields. if ($this->requestType == 'POST' && isset($this->postFields)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $this->postFields); } } // Don't print the response; return it from curl_exec(). curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $this->address); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout); curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); // Follow redirects (maximum of 5). curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($ch, CURLOPT_MAXREDIRS, 5); // SSL support. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->ssl); // Set a custom UA string so people can identify our requests. curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent); // Output the header in the response. curl_setopt($ch, CURLOPT_HEADER, TRUE); $response = curl_exec($ch); $error = curl_error($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $time = curl_getinfo($ch, CURLINFO_TOTAL_TIME); curl_close($ch); // Set the header, response, error and http code. $this->responseHeader = substr($response, 0, $header_size); $this->responseBody = substr($response, $header_size); $this->error = $error; $this->httpCode = $http_code; // Convert the latency to ms. $this->latency = round($time * 1000); }
[ "public", "function", "execute", "(", ")", "{", "// Set a default latency value.", "$", "latency", "=", "0", ";", "// Set up cURL options.", "$", "ch", "=", "curl_init", "(", ")", ";", "// If there are basic authentication credentials, use them.", "if", "(", "isset", ...
Check a given address with cURL. After this method is completed, the response body, headers, latency, etc. will be populated, and can be accessed with the appropriate methods.
[ "Check", "a", "given", "address", "with", "cURL", "." ]
16d33dd56f2332fe259f6acfd0bdc2bb571738f2
https://github.com/geerlingguy/Request/blob/16d33dd56f2332fe259f6acfd0bdc2bb571738f2/JJG/Request.php#L264-L316
train
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/tcpdf/tcpdf_import.php
TCPDF_IMPORT.importPDF
public function importPDF($filename) { // load document $rawdata = file_get_contents($filename); if ($rawdata === false) { $this->Error('Unable to get the content of the file: '.$filename); } // configuration parameters for parser $cfg = array( 'die_for_errors' => false, 'ignore_filter_decoding_errors' => true, 'ignore_missing_filter_decoders' => true, ); try { // parse PDF data $pdf = new TCPDF_PARSER($rawdata, $cfg); } catch (Exception $e) { die($e->getMessage()); } // get the parsed data $data = $pdf->getParsedData(); // release some memory unset($rawdata); // ... print_r($data); // DEBUG unset($pdf); }
php
public function importPDF($filename) { // load document $rawdata = file_get_contents($filename); if ($rawdata === false) { $this->Error('Unable to get the content of the file: '.$filename); } // configuration parameters for parser $cfg = array( 'die_for_errors' => false, 'ignore_filter_decoding_errors' => true, 'ignore_missing_filter_decoders' => true, ); try { // parse PDF data $pdf = new TCPDF_PARSER($rawdata, $cfg); } catch (Exception $e) { die($e->getMessage()); } // get the parsed data $data = $pdf->getParsedData(); // release some memory unset($rawdata); // ... print_r($data); // DEBUG unset($pdf); }
[ "public", "function", "importPDF", "(", "$", "filename", ")", "{", "// load document", "$", "rawdata", "=", "file_get_contents", "(", "$", "filename", ")", ";", "if", "(", "$", "rawdata", "===", "false", ")", "{", "$", "this", "->", "Error", "(", "'Unabl...
Import an existing PDF document @param $filename (string) Filename of the PDF document to import. @return true in case of success, false otherwise @public @since 1.0.000 (2011-05-24)
[ "Import", "an", "existing", "PDF", "document" ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/tcpdf/tcpdf_import.php#L68-L98
train
deltaaskii/lara-pdf-merger
src/LynX39/LaraPdfMerger/tcpdf/tcpdi_parser.php
tcpdi_parser.cleanUp
public function cleanUp() { unset($this->pdfdata); $this->pdfdata = ''; unset($this->objstreams); $this->objstreams = array(); unset($this->objects); $this->objects = array(); unset($this->objstreamobjs); $this->objstreamobjs = array(); unset($this->xref); $this->xref = array(); unset($this->objoffsets); $this->objoffsets = array(); unset($this->pages); $this->pages = array(); }
php
public function cleanUp() { unset($this->pdfdata); $this->pdfdata = ''; unset($this->objstreams); $this->objstreams = array(); unset($this->objects); $this->objects = array(); unset($this->objstreamobjs); $this->objstreamobjs = array(); unset($this->xref); $this->xref = array(); unset($this->objoffsets); $this->objoffsets = array(); unset($this->pages); $this->pages = array(); }
[ "public", "function", "cleanUp", "(", ")", "{", "unset", "(", "$", "this", "->", "pdfdata", ")", ";", "$", "this", "->", "pdfdata", "=", "''", ";", "unset", "(", "$", "this", "->", "objstreams", ")", ";", "$", "this", "->", "objstreams", "=", "arra...
Clean up when done, to free memory etc
[ "Clean", "up", "when", "done", "to", "free", "memory", "etc" ]
8cede29130ba6b60d33481b4067a8cba24c21753
https://github.com/deltaaskii/lara-pdf-merger/blob/8cede29130ba6b60d33481b4067a8cba24c21753/src/LynX39/LaraPdfMerger/tcpdf/tcpdi_parser.php#L212-L227
train