id
int32
0
241k
repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
1,700
SergioMadness/framework
framework/components/swiftmailer/SwiftMailer.php
SwiftMailer.send
public function send() { foreach ($this->messages as $mail) { $this->mailer->send($mail); } return $this; }
php
public function send() { foreach ($this->messages as $mail) { $this->mailer->send($mail); } return $this; }
[ "public", "function", "send", "(", ")", "{", "foreach", "(", "$", "this", "->", "messages", "as", "$", "mail", ")", "{", "$", "this", "->", "mailer", "->", "send", "(", "$", "mail", ")", ";", "}", "return", "$", "this", ";", "}" ]
Send all messages @return \pwf\components\swiftmailer\SwiftMailer
[ "Send", "all", "messages" ]
a5038eb926a5038b9a331d0cb6a68d7fc3cf1f1e
https://github.com/SergioMadness/framework/blob/a5038eb926a5038b9a331d0cb6a68d7fc3cf1f1e/framework/components/swiftmailer/SwiftMailer.php#L117-L123
1,701
vansanblch/browshot-api-client
src/BrowshotAPI.php
BrowshotAPI.getScreenshotStatus
private function getScreenshotStatus($status): int { switch (mb_strtoupper($status)) { case 'IN_QUEUE': return ScreenshotStatus::IN_QUEUE; case 'IN_PROCESS': return ScreenshotStatus::IN_PROCESS; case 'FINISHED': return ScreenshotStatus::FINISHED; case 'ERROR': return ScreenshotStatus::ERROR; } return ScreenshotStatus::UNKNOWN; }
php
private function getScreenshotStatus($status): int { switch (mb_strtoupper($status)) { case 'IN_QUEUE': return ScreenshotStatus::IN_QUEUE; case 'IN_PROCESS': return ScreenshotStatus::IN_PROCESS; case 'FINISHED': return ScreenshotStatus::FINISHED; case 'ERROR': return ScreenshotStatus::ERROR; } return ScreenshotStatus::UNKNOWN; }
[ "private", "function", "getScreenshotStatus", "(", "$", "status", ")", ":", "int", "{", "switch", "(", "mb_strtoupper", "(", "$", "status", ")", ")", "{", "case", "'IN_QUEUE'", ":", "return", "ScreenshotStatus", "::", "IN_QUEUE", ";", "case", "'IN_PROCESS'", ":", "return", "ScreenshotStatus", "::", "IN_PROCESS", ";", "case", "'FINISHED'", ":", "return", "ScreenshotStatus", "::", "FINISHED", ";", "case", "'ERROR'", ":", "return", "ScreenshotStatus", "::", "ERROR", ";", "}", "return", "ScreenshotStatus", "::", "UNKNOWN", ";", "}" ]
Get screenshot status by its name @param $status @return int
[ "Get", "screenshot", "status", "by", "its", "name" ]
3a84432b6548ce01060f7757f5c5ba5ac3b08eca
https://github.com/vansanblch/browshot-api-client/blob/3a84432b6548ce01060f7757f5c5ba5ac3b08eca/src/BrowshotAPI.php#L143-L157
1,702
orbital-framework/framework
src/Header.php
Header.send
public static function send($clean = TRUE){ if( !headers_sent() ){ foreach( self::$headers as $header ){ if( is_array($header) ){ call_user_func_array('header', $header); }else{ header($header); } } if( $clean ){ self::$headers = array(); } } self::$sent = TRUE; }
php
public static function send($clean = TRUE){ if( !headers_sent() ){ foreach( self::$headers as $header ){ if( is_array($header) ){ call_user_func_array('header', $header); }else{ header($header); } } if( $clean ){ self::$headers = array(); } } self::$sent = TRUE; }
[ "public", "static", "function", "send", "(", "$", "clean", "=", "TRUE", ")", "{", "if", "(", "!", "headers_sent", "(", ")", ")", "{", "foreach", "(", "self", "::", "$", "headers", "as", "$", "header", ")", "{", "if", "(", "is_array", "(", "$", "header", ")", ")", "{", "call_user_func_array", "(", "'header'", ",", "$", "header", ")", ";", "}", "else", "{", "header", "(", "$", "header", ")", ";", "}", "}", "if", "(", "$", "clean", ")", "{", "self", "::", "$", "headers", "=", "array", "(", ")", ";", "}", "}", "self", "::", "$", "sent", "=", "TRUE", ";", "}" ]
Send HTTP Headers @param boolean $clean @return void
[ "Send", "HTTP", "Headers" ]
9e7457638206077134f1b4d0759632bd2ea87917
https://github.com/orbital-framework/framework/blob/9e7457638206077134f1b4d0759632bd2ea87917/src/Header.php#L169-L190
1,703
orbital-framework/framework
src/Header.php
Header.location
public static function location($url, $code = 301){ self::set(array( 'Location: '. $url, TRUE, $code )); return self::send(); }
php
public static function location($url, $code = 301){ self::set(array( 'Location: '. $url, TRUE, $code )); return self::send(); }
[ "public", "static", "function", "location", "(", "$", "url", ",", "$", "code", "=", "301", ")", "{", "self", "::", "set", "(", "array", "(", "'Location: '", ".", "$", "url", ",", "TRUE", ",", "$", "code", ")", ")", ";", "return", "self", "::", "send", "(", ")", ";", "}" ]
Set and redirect HTTP Header Location @see Header::set() @param string $url @param int $code @return void
[ "Set", "and", "redirect", "HTTP", "Header", "Location" ]
9e7457638206077134f1b4d0759632bd2ea87917
https://github.com/orbital-framework/framework/blob/9e7457638206077134f1b4d0759632bd2ea87917/src/Header.php#L224-L233
1,704
orbital-framework/framework
src/Header.php
Header.contentType
public static function contentType($type, $charset = 'utf-8'){ $type = isset( self::$types[$type] ) ? self::$types[$type] : $type; self::set('Content-Type: '. $type. '; charset='. $charset); }
php
public static function contentType($type, $charset = 'utf-8'){ $type = isset( self::$types[$type] ) ? self::$types[$type] : $type; self::set('Content-Type: '. $type. '; charset='. $charset); }
[ "public", "static", "function", "contentType", "(", "$", "type", ",", "$", "charset", "=", "'utf-8'", ")", "{", "$", "type", "=", "isset", "(", "self", "::", "$", "types", "[", "$", "type", "]", ")", "?", "self", "::", "$", "types", "[", "$", "type", "]", ":", "$", "type", ";", "self", "::", "set", "(", "'Content-Type: '", ".", "$", "type", ".", "'; charset='", ".", "$", "charset", ")", ";", "}" ]
Set HTTP Content-Type @param string $type @param string $charset @return void
[ "Set", "HTTP", "Content", "-", "Type" ]
9e7457638206077134f1b4d0759632bd2ea87917
https://github.com/orbital-framework/framework/blob/9e7457638206077134f1b4d0759632bd2ea87917/src/Header.php#L241-L244
1,705
Apatis/Config
src/ConfigAdapterAbstract.php
ConfigAdapterAbstract.readFile
protected function readFile(string $file) : array { if (!file_exists($file)) { throw new \InvalidArgumentException( sprintf( 'Configuration %s is not exists', $file ), E_WARNING ); } if (!is_array(($configs = $this->parseFromFile($file)))) { throw new \RuntimeException( sprintf( 'Invalid %s configuration from file: %s', ltrim(strrchr(get_class($this), '\\'), '\\'), $file ), E_NOTICE ); } return $configs; }
php
protected function readFile(string $file) : array { if (!file_exists($file)) { throw new \InvalidArgumentException( sprintf( 'Configuration %s is not exists', $file ), E_WARNING ); } if (!is_array(($configs = $this->parseFromFile($file)))) { throw new \RuntimeException( sprintf( 'Invalid %s configuration from file: %s', ltrim(strrchr(get_class($this), '\\'), '\\'), $file ), E_NOTICE ); } return $configs; }
[ "protected", "function", "readFile", "(", "string", "$", "file", ")", ":", "array", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf", "(", "'Configuration %s is not exists'", ",", "$", "file", ")", ",", "E_WARNING", ")", ";", "}", "if", "(", "!", "is_array", "(", "(", "$", "configs", "=", "$", "this", "->", "parseFromFile", "(", "$", "file", ")", ")", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "sprintf", "(", "'Invalid %s configuration from file: %s'", ",", "ltrim", "(", "strrchr", "(", "get_class", "(", "$", "this", ")", ",", "'\\\\'", ")", ",", "'\\\\'", ")", ",", "$", "file", ")", ",", "E_NOTICE", ")", ";", "}", "return", "$", "configs", ";", "}" ]
Read current file @param string $file @return array @throws \InvalidArgumentException @throws \RuntimeException
[ "Read", "current", "file" ]
f93d1761e5ea84185f563fb9c7a113e64c4623ba
https://github.com/Apatis/Config/blob/f93d1761e5ea84185f563fb9c7a113e64c4623ba/src/ConfigAdapterAbstract.php#L53-L77
1,706
loevgaard/dandomain-stock-entities
src/Entity/StockMovement.php
StockMovement.getTypes
public static function getTypes(): array { return [ self::TYPE_DELIVERY => self::TYPE_DELIVERY, self::TYPE_SALE => self::TYPE_SALE, self::TYPE_REGULATION => self::TYPE_REGULATION, self::TYPE_RETURN => self::TYPE_RETURN, ]; }
php
public static function getTypes(): array { return [ self::TYPE_DELIVERY => self::TYPE_DELIVERY, self::TYPE_SALE => self::TYPE_SALE, self::TYPE_REGULATION => self::TYPE_REGULATION, self::TYPE_RETURN => self::TYPE_RETURN, ]; }
[ "public", "static", "function", "getTypes", "(", ")", ":", "array", "{", "return", "[", "self", "::", "TYPE_DELIVERY", "=>", "self", "::", "TYPE_DELIVERY", ",", "self", "::", "TYPE_SALE", "=>", "self", "::", "TYPE_SALE", ",", "self", "::", "TYPE_REGULATION", "=>", "self", "::", "TYPE_REGULATION", ",", "self", "::", "TYPE_RETURN", "=>", "self", "::", "TYPE_RETURN", ",", "]", ";", "}" ]
Returns the valid types. @return array
[ "Returns", "the", "valid", "types", "." ]
28a3bfe4c0c5c27d2ba5d5564f8b2a6ee68b64c8
https://github.com/loevgaard/dandomain-stock-entities/blob/28a3bfe4c0c5c27d2ba5d5564f8b2a6ee68b64c8/src/Entity/StockMovement.php#L449-L457
1,707
loevgaard/dandomain-stock-entities
src/Entity/StockMovement.php
StockMovement.updateCurrency
protected function updateCurrency(Money $money): self { if ($this->currency && $money->getCurrency()->getCode() !== $this->currency) { throw new CurrencyMismatchException('The currency on this stock movement is not the same as the one your Money object'); } $this->currency = $money->getCurrency()->getCode(); return $this; }
php
protected function updateCurrency(Money $money): self { if ($this->currency && $money->getCurrency()->getCode() !== $this->currency) { throw new CurrencyMismatchException('The currency on this stock movement is not the same as the one your Money object'); } $this->currency = $money->getCurrency()->getCode(); return $this; }
[ "protected", "function", "updateCurrency", "(", "Money", "$", "money", ")", ":", "self", "{", "if", "(", "$", "this", "->", "currency", "&&", "$", "money", "->", "getCurrency", "(", ")", "->", "getCode", "(", ")", "!==", "$", "this", "->", "currency", ")", "{", "throw", "new", "CurrencyMismatchException", "(", "'The currency on this stock movement is not the same as the one your Money object'", ")", ";", "}", "$", "this", "->", "currency", "=", "$", "money", "->", "getCurrency", "(", ")", "->", "getCode", "(", ")", ";", "return", "$", "this", ";", "}" ]
Updates the shared currency. If the currency is already set and the new currency is not the same, it throws an exception @param Money $money @return StockMovement @throws \Loevgaard\DandomainStock\Exception\CurrencyMismatchException
[ "Updates", "the", "shared", "currency", "." ]
28a3bfe4c0c5c27d2ba5d5564f8b2a6ee68b64c8
https://github.com/loevgaard/dandomain-stock-entities/blob/28a3bfe4c0c5c27d2ba5d5564f8b2a6ee68b64c8/src/Entity/StockMovement.php#L798-L807
1,708
loevgaard/dandomain-stock-entities
src/Entity/StockMovement.php
StockMovement.money
protected function money(int $val): Money { if (!$this->currency) { throw new UnsetCurrencyException('The currency is not set on this stock movement'); } return new Money($val, new Currency($this->currency)); }
php
protected function money(int $val): Money { if (!$this->currency) { throw new UnsetCurrencyException('The currency is not set on this stock movement'); } return new Money($val, new Currency($this->currency)); }
[ "protected", "function", "money", "(", "int", "$", "val", ")", ":", "Money", "{", "if", "(", "!", "$", "this", "->", "currency", ")", "{", "throw", "new", "UnsetCurrencyException", "(", "'The currency is not set on this stock movement'", ")", ";", "}", "return", "new", "Money", "(", "$", "val", ",", "new", "Currency", "(", "$", "this", "->", "currency", ")", ")", ";", "}" ]
Returns a new Money object based on the shared currency If no currency is set, it throws an exception. @param int $val @return Money @throws \Loevgaard\DandomainStock\Exception\UnsetCurrencyException
[ "Returns", "a", "new", "Money", "object", "based", "on", "the", "shared", "currency", "If", "no", "currency", "is", "set", "it", "throws", "an", "exception", "." ]
28a3bfe4c0c5c27d2ba5d5564f8b2a6ee68b64c8
https://github.com/loevgaard/dandomain-stock-entities/blob/28a3bfe4c0c5c27d2ba5d5564f8b2a6ee68b64c8/src/Entity/StockMovement.php#L819-L826
1,709
DevGroup-ru/dotplant-entity-structure
src/actions/BaseEntityTreeAction.php
BaseEntityTreeAction.treeGoDown
private static function treeGoDown($id, $data, &$hidden) { foreach ($data as $row) { if ($row['parent_id'] == $id) { if (false === in_array($row['id'], $hidden)) { $hidden[] = $row['id']; } self::treeGoDown($row['id'], $data, $hidden); } } }
php
private static function treeGoDown($id, $data, &$hidden) { foreach ($data as $row) { if ($row['parent_id'] == $id) { if (false === in_array($row['id'], $hidden)) { $hidden[] = $row['id']; } self::treeGoDown($row['id'], $data, $hidden); } } }
[ "private", "static", "function", "treeGoDown", "(", "$", "id", ",", "$", "data", ",", "&", "$", "hidden", ")", "{", "foreach", "(", "$", "data", "as", "$", "row", ")", "{", "if", "(", "$", "row", "[", "'parent_id'", "]", "==", "$", "id", ")", "{", "if", "(", "false", "===", "in_array", "(", "$", "row", "[", "'id'", "]", ",", "$", "hidden", ")", ")", "{", "$", "hidden", "[", "]", "=", "$", "row", "[", "'id'", "]", ";", "}", "self", "::", "treeGoDown", "(", "$", "row", "[", "'id'", "]", ",", "$", "data", ",", "$", "hidden", ")", ";", "}", "}", "}" ]
Recursively finds all children of node with given id @param $id @param $data @param $hidden
[ "Recursively", "finds", "all", "children", "of", "node", "with", "given", "id" ]
43e3354b5ebf9171e9afef38d82dccb02357bfed
https://github.com/DevGroup-ru/dotplant-entity-structure/blob/43e3354b5ebf9171e9afef38d82dccb02357bfed/src/actions/BaseEntityTreeAction.php#L210-L220
1,710
nano7/Http
src/Kernel.php
Kernel.handle
public function handle() { $response = ''; try { // Set running mode $this->app->instance('mode', 'web'); // App boot $this->app->boot(); // Prepare request $request = $this->prepareRequest(); // Preparar rotas $response = $this->runRoute($request); } catch (\Exception $e) { $this->reportException($e); $response = Router::toResponse($request, $this->renderException($request, $e)); } // Call terminate $this->terminate($request, $response); return $response; }
php
public function handle() { $response = ''; try { // Set running mode $this->app->instance('mode', 'web'); // App boot $this->app->boot(); // Prepare request $request = $this->prepareRequest(); // Preparar rotas $response = $this->runRoute($request); } catch (\Exception $e) { $this->reportException($e); $response = Router::toResponse($request, $this->renderException($request, $e)); } // Call terminate $this->terminate($request, $response); return $response; }
[ "public", "function", "handle", "(", ")", "{", "$", "response", "=", "''", ";", "try", "{", "// Set running mode", "$", "this", "->", "app", "->", "instance", "(", "'mode'", ",", "'web'", ")", ";", "// App boot", "$", "this", "->", "app", "->", "boot", "(", ")", ";", "// Prepare request", "$", "request", "=", "$", "this", "->", "prepareRequest", "(", ")", ";", "// Preparar rotas", "$", "response", "=", "$", "this", "->", "runRoute", "(", "$", "request", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "this", "->", "reportException", "(", "$", "e", ")", ";", "$", "response", "=", "Router", "::", "toResponse", "(", "$", "request", ",", "$", "this", "->", "renderException", "(", "$", "request", ",", "$", "e", ")", ")", ";", "}", "// Call terminate", "$", "this", "->", "terminate", "(", "$", "request", ",", "$", "response", ")", ";", "return", "$", "response", ";", "}" ]
Handle web. @return \Illuminate\Http\JsonResponse|JsonResponse|Response
[ "Handle", "web", "." ]
9af795646ceb3cf1364160a71e339cb79d63773f
https://github.com/nano7/Http/blob/9af795646ceb3cf1364160a71e339cb79d63773f/src/Kernel.php#L43-L70
1,711
bishopb/vanilla
library/core/class.filesystem.php
Gdn_FileSystem.Folders
public static function Folders($SourceFolders) { if(!is_array($SourceFolders)) $SourceFolders = array($SourceFolders); $BlackList = Gdn::Config('Garden.FolderBlacklist'); if (!is_array($BlackList)) $BlackList = array('.', '..'); $Result = array(); foreach($SourceFolders as $SourceFolder) { if ($DirectoryHandle = opendir($SourceFolder)) { while (($Item = readdir($DirectoryHandle)) !== FALSE) { $SubFolder = CombinePaths(array($SourceFolder, $Item)); if (!in_array($Item, $BlackList) && is_dir($SubFolder)) $Result[] = $Item; } closedir($DirectoryHandle); } } if(count($Result) == 0) return FALSE; return $Result; }
php
public static function Folders($SourceFolders) { if(!is_array($SourceFolders)) $SourceFolders = array($SourceFolders); $BlackList = Gdn::Config('Garden.FolderBlacklist'); if (!is_array($BlackList)) $BlackList = array('.', '..'); $Result = array(); foreach($SourceFolders as $SourceFolder) { if ($DirectoryHandle = opendir($SourceFolder)) { while (($Item = readdir($DirectoryHandle)) !== FALSE) { $SubFolder = CombinePaths(array($SourceFolder, $Item)); if (!in_array($Item, $BlackList) && is_dir($SubFolder)) $Result[] = $Item; } closedir($DirectoryHandle); } } if(count($Result) == 0) return FALSE; return $Result; }
[ "public", "static", "function", "Folders", "(", "$", "SourceFolders", ")", "{", "if", "(", "!", "is_array", "(", "$", "SourceFolders", ")", ")", "$", "SourceFolders", "=", "array", "(", "$", "SourceFolders", ")", ";", "$", "BlackList", "=", "Gdn", "::", "Config", "(", "'Garden.FolderBlacklist'", ")", ";", "if", "(", "!", "is_array", "(", "$", "BlackList", ")", ")", "$", "BlackList", "=", "array", "(", "'.'", ",", "'..'", ")", ";", "$", "Result", "=", "array", "(", ")", ";", "foreach", "(", "$", "SourceFolders", "as", "$", "SourceFolder", ")", "{", "if", "(", "$", "DirectoryHandle", "=", "opendir", "(", "$", "SourceFolder", ")", ")", "{", "while", "(", "(", "$", "Item", "=", "readdir", "(", "$", "DirectoryHandle", ")", ")", "!==", "FALSE", ")", "{", "$", "SubFolder", "=", "CombinePaths", "(", "array", "(", "$", "SourceFolder", ",", "$", "Item", ")", ")", ";", "if", "(", "!", "in_array", "(", "$", "Item", ",", "$", "BlackList", ")", "&&", "is_dir", "(", "$", "SubFolder", ")", ")", "$", "Result", "[", "]", "=", "$", "Item", ";", "}", "closedir", "(", "$", "DirectoryHandle", ")", ";", "}", "}", "if", "(", "count", "(", "$", "Result", ")", "==", "0", ")", "return", "FALSE", ";", "return", "$", "Result", ";", "}" ]
Returns an array of all folder names within the source folder or FALSE if SourceFolder does not exist. @param string $SourceFolder @todo Documentation and variable type is needed for $SourceFolder.
[ "Returns", "an", "array", "of", "all", "folder", "names", "within", "the", "source", "folder", "or", "FALSE", "if", "SourceFolder", "does", "not", "exist", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/library/core/class.filesystem.php#L56-L79
1,712
bishopb/vanilla
library/core/class.filesystem.php
Gdn_FileSystem.GetContents
public static function GetContents() { $File = CombinePaths(func_get_args()); if (file_exists($File) && is_file($File)) return self::_GetContents($File); else return FALSE; }
php
public static function GetContents() { $File = CombinePaths(func_get_args()); if (file_exists($File) && is_file($File)) return self::_GetContents($File); else return FALSE; }
[ "public", "static", "function", "GetContents", "(", ")", "{", "$", "File", "=", "CombinePaths", "(", "func_get_args", "(", ")", ")", ";", "if", "(", "file_exists", "(", "$", "File", ")", "&&", "is_file", "(", "$", "File", ")", ")", "return", "self", "::", "_GetContents", "(", "$", "File", ")", ";", "else", "return", "FALSE", ";", "}" ]
Returns the contents of the specified file, or FALSE if it does not exist. Note that this is only useful for static content since any php code will be parsed as if it were within this method of this object.
[ "Returns", "the", "contents", "of", "the", "specified", "file", "or", "FALSE", "if", "it", "does", "not", "exist", ".", "Note", "that", "this", "is", "only", "useful", "for", "static", "content", "since", "any", "php", "code", "will", "be", "parsed", "as", "if", "it", "were", "within", "this", "method", "of", "this", "object", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/library/core/class.filesystem.php#L229-L235
1,713
bishopb/vanilla
library/core/class.filesystem.php
Gdn_FileSystem.SaveFile
public static function SaveFile($FileName, $FileContents, $Flags = VANILLA_FILE_PUT_FLAGS) { // Check that the folder exists and is writable $DirName = dirname($FileName); $FileBaseName = basename($FileName); if (!is_dir($DirName)) throw new Exception(sprintf('Requested save operation [%1$s] could not be completed because target folder [%2$s] does not exist.',$FileBaseName,$DirName)); if (!IsWritable($DirName)) throw new Exception(sprintf('Requested save operation [%1$s] could not be completed because target folder [%2$s] is not writable.',$FileBaseName,$DirName)); if (file_put_contents($FileName, $FileContents, $Flags) === FALSE) throw new Exception(sprintf('Requested save operation [%1$s] could not be completed!',$FileBaseName)); return TRUE; }
php
public static function SaveFile($FileName, $FileContents, $Flags = VANILLA_FILE_PUT_FLAGS) { // Check that the folder exists and is writable $DirName = dirname($FileName); $FileBaseName = basename($FileName); if (!is_dir($DirName)) throw new Exception(sprintf('Requested save operation [%1$s] could not be completed because target folder [%2$s] does not exist.',$FileBaseName,$DirName)); if (!IsWritable($DirName)) throw new Exception(sprintf('Requested save operation [%1$s] could not be completed because target folder [%2$s] is not writable.',$FileBaseName,$DirName)); if (file_put_contents($FileName, $FileContents, $Flags) === FALSE) throw new Exception(sprintf('Requested save operation [%1$s] could not be completed!',$FileBaseName)); return TRUE; }
[ "public", "static", "function", "SaveFile", "(", "$", "FileName", ",", "$", "FileContents", ",", "$", "Flags", "=", "VANILLA_FILE_PUT_FLAGS", ")", "{", "// Check that the folder exists and is writable", "$", "DirName", "=", "dirname", "(", "$", "FileName", ")", ";", "$", "FileBaseName", "=", "basename", "(", "$", "FileName", ")", ";", "if", "(", "!", "is_dir", "(", "$", "DirName", ")", ")", "throw", "new", "Exception", "(", "sprintf", "(", "'Requested save operation [%1$s] could not be completed because target folder [%2$s] does not exist.'", ",", "$", "FileBaseName", ",", "$", "DirName", ")", ")", ";", "if", "(", "!", "IsWritable", "(", "$", "DirName", ")", ")", "throw", "new", "Exception", "(", "sprintf", "(", "'Requested save operation [%1$s] could not be completed because target folder [%2$s] is not writable.'", ",", "$", "FileBaseName", ",", "$", "DirName", ")", ")", ";", "if", "(", "file_put_contents", "(", "$", "FileName", ",", "$", "FileContents", ",", "$", "Flags", ")", "===", "FALSE", ")", "throw", "new", "Exception", "(", "sprintf", "(", "'Requested save operation [%1$s] could not be completed!'", ",", "$", "FileBaseName", ")", ")", ";", "return", "TRUE", ";", "}" ]
Saves the specified file with the provided file contents. @param string $FileName The full path and name of the file to be saved. @param string $FileContents The contents of the file being saved.
[ "Saves", "the", "specified", "file", "with", "the", "provided", "file", "contents", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/library/core/class.filesystem.php#L258-L273
1,714
bishopb/vanilla
library/core/class.filesystem.php
Gdn_FileSystem.ServeFile
public static function ServeFile($File, $Name = '', $MimeType = '', $ServeMode = 'attachment') { $FileIsLocal = (substr($File, 0, 4) == 'http') ? FALSE : TRUE; $FileAvailable = ($FileIsLocal) ? is_readable($File) : TRUE; if ($FileAvailable) { // Close the database connection Gdn::Database()->CloseConnection(); // Determine if Path extension should be appended to Name $NameExtension = strtolower(pathinfo($Name, PATHINFO_EXTENSION)); $FileExtension = strtolower(pathinfo($File, PATHINFO_EXTENSION)); if ($NameExtension == '') { if ($Name == '') { $Name = pathinfo($File, PATHINFO_FILENAME) . '.' . $FileExtension; } elseif (!StringEndsWith($Name, '.'.$FileExtension)) { $Name .= '.'.$FileExtension; } } else { $Extension = $NameExtension; } $Name = rawurldecode($Name); // Figure out the MIME type $MimeTypes = array( "pdf" => "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "php" => "text/plain", "ico" => "image/vnd.microsoft.icon" ); if ($MimeType == '') { if (array_key_exists($FileExtension, $MimeTypes)){ $MimeType = $MimeTypes[$FileExtension]; } else { $MimeType = 'application/force-download'; }; }; @ob_end_clean(); // required for IE, otherwise Content-Disposition may be ignored if (ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); if ($ServeMode == 'inline') header('Content-Disposition: inline; filename="'.$Name.'"'); else header('Content-Disposition: attachment; filename="'.$Name.'"'); header('Content-Type: '.$MimeType); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); header("Cache-control: private"); header('Pragma: private'); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); readfile($File); exit(); } else { die('not readable'); } }
php
public static function ServeFile($File, $Name = '', $MimeType = '', $ServeMode = 'attachment') { $FileIsLocal = (substr($File, 0, 4) == 'http') ? FALSE : TRUE; $FileAvailable = ($FileIsLocal) ? is_readable($File) : TRUE; if ($FileAvailable) { // Close the database connection Gdn::Database()->CloseConnection(); // Determine if Path extension should be appended to Name $NameExtension = strtolower(pathinfo($Name, PATHINFO_EXTENSION)); $FileExtension = strtolower(pathinfo($File, PATHINFO_EXTENSION)); if ($NameExtension == '') { if ($Name == '') { $Name = pathinfo($File, PATHINFO_FILENAME) . '.' . $FileExtension; } elseif (!StringEndsWith($Name, '.'.$FileExtension)) { $Name .= '.'.$FileExtension; } } else { $Extension = $NameExtension; } $Name = rawurldecode($Name); // Figure out the MIME type $MimeTypes = array( "pdf" => "application/pdf", "txt" => "text/plain", "html" => "text/html", "htm" => "text/html", "exe" => "application/octet-stream", "zip" => "application/zip", "doc" => "application/msword", "xls" => "application/vnd.ms-excel", "ppt" => "application/vnd.ms-powerpoint", "gif" => "image/gif", "png" => "image/png", "jpeg" => "image/jpg", "jpg" => "image/jpg", "php" => "text/plain", "ico" => "image/vnd.microsoft.icon" ); if ($MimeType == '') { if (array_key_exists($FileExtension, $MimeTypes)){ $MimeType = $MimeTypes[$FileExtension]; } else { $MimeType = 'application/force-download'; }; }; @ob_end_clean(); // required for IE, otherwise Content-Disposition may be ignored if (ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); if ($ServeMode == 'inline') header('Content-Disposition: inline; filename="'.$Name.'"'); else header('Content-Disposition: attachment; filename="'.$Name.'"'); header('Content-Type: '.$MimeType); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); header("Cache-control: private"); header('Pragma: private'); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); readfile($File); exit(); } else { die('not readable'); } }
[ "public", "static", "function", "ServeFile", "(", "$", "File", ",", "$", "Name", "=", "''", ",", "$", "MimeType", "=", "''", ",", "$", "ServeMode", "=", "'attachment'", ")", "{", "$", "FileIsLocal", "=", "(", "substr", "(", "$", "File", ",", "0", ",", "4", ")", "==", "'http'", ")", "?", "FALSE", ":", "TRUE", ";", "$", "FileAvailable", "=", "(", "$", "FileIsLocal", ")", "?", "is_readable", "(", "$", "File", ")", ":", "TRUE", ";", "if", "(", "$", "FileAvailable", ")", "{", "// Close the database connection", "Gdn", "::", "Database", "(", ")", "->", "CloseConnection", "(", ")", ";", "// Determine if Path extension should be appended to Name", "$", "NameExtension", "=", "strtolower", "(", "pathinfo", "(", "$", "Name", ",", "PATHINFO_EXTENSION", ")", ")", ";", "$", "FileExtension", "=", "strtolower", "(", "pathinfo", "(", "$", "File", ",", "PATHINFO_EXTENSION", ")", ")", ";", "if", "(", "$", "NameExtension", "==", "''", ")", "{", "if", "(", "$", "Name", "==", "''", ")", "{", "$", "Name", "=", "pathinfo", "(", "$", "File", ",", "PATHINFO_FILENAME", ")", ".", "'.'", ".", "$", "FileExtension", ";", "}", "elseif", "(", "!", "StringEndsWith", "(", "$", "Name", ",", "'.'", ".", "$", "FileExtension", ")", ")", "{", "$", "Name", ".=", "'.'", ".", "$", "FileExtension", ";", "}", "}", "else", "{", "$", "Extension", "=", "$", "NameExtension", ";", "}", "$", "Name", "=", "rawurldecode", "(", "$", "Name", ")", ";", "// Figure out the MIME type", "$", "MimeTypes", "=", "array", "(", "\"pdf\"", "=>", "\"application/pdf\"", ",", "\"txt\"", "=>", "\"text/plain\"", ",", "\"html\"", "=>", "\"text/html\"", ",", "\"htm\"", "=>", "\"text/html\"", ",", "\"exe\"", "=>", "\"application/octet-stream\"", ",", "\"zip\"", "=>", "\"application/zip\"", ",", "\"doc\"", "=>", "\"application/msword\"", ",", "\"xls\"", "=>", "\"application/vnd.ms-excel\"", ",", "\"ppt\"", "=>", "\"application/vnd.ms-powerpoint\"", ",", "\"gif\"", "=>", "\"image/gif\"", ",", "\"png\"", "=>", "\"image/png\"", ",", "\"jpeg\"", "=>", "\"image/jpg\"", ",", "\"jpg\"", "=>", "\"image/jpg\"", ",", "\"php\"", "=>", "\"text/plain\"", ",", "\"ico\"", "=>", "\"image/vnd.microsoft.icon\"", ")", ";", "if", "(", "$", "MimeType", "==", "''", ")", "{", "if", "(", "array_key_exists", "(", "$", "FileExtension", ",", "$", "MimeTypes", ")", ")", "{", "$", "MimeType", "=", "$", "MimeTypes", "[", "$", "FileExtension", "]", ";", "}", "else", "{", "$", "MimeType", "=", "'application/force-download'", ";", "}", ";", "}", ";", "@", "ob_end_clean", "(", ")", ";", "// required for IE, otherwise Content-Disposition may be ignored", "if", "(", "ini_get", "(", "'zlib.output_compression'", ")", ")", "ini_set", "(", "'zlib.output_compression'", ",", "'Off'", ")", ";", "if", "(", "$", "ServeMode", "==", "'inline'", ")", "header", "(", "'Content-Disposition: inline; filename=\"'", ".", "$", "Name", ".", "'\"'", ")", ";", "else", "header", "(", "'Content-Disposition: attachment; filename=\"'", ".", "$", "Name", ".", "'\"'", ")", ";", "header", "(", "'Content-Type: '", ".", "$", "MimeType", ")", ";", "header", "(", "\"Content-Transfer-Encoding: binary\"", ")", ";", "header", "(", "'Accept-Ranges: bytes'", ")", ";", "header", "(", "\"Cache-control: private\"", ")", ";", "header", "(", "'Pragma: private'", ")", ";", "header", "(", "\"Expires: Mon, 26 Jul 1997 05:00:00 GMT\"", ")", ";", "readfile", "(", "$", "File", ")", ";", "exit", "(", ")", ";", "}", "else", "{", "die", "(", "'not readable'", ")", ";", "}", "}" ]
Serves a file to the browser. @param string $File Full path to the file being served. @param string $Name Name to give the file being served. Including extension overrides $File extension. Uses $File filename if empty. @param string $MimeType The mime type of the file. @param string $ServeMode Whether to download the file as an attachment, or inline
[ "Serves", "a", "file", "to", "the", "browser", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/library/core/class.filesystem.php#L294-L366
1,715
bishopb/vanilla
library/core/class.filesystem.php
Gdn_FileSystem.Copy
public static function Copy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755)){ $result=false; if (is_file($source)) { if ($dest[strlen($dest)-1]=='/') { if (!file_exists($dest)) { cmfcDirectory::makeAll($dest,$options['folderPermission'],true); } $__dest=$dest."/".basename($source); } else { $__dest=$dest; } $result=copy($source, $__dest); chmod($__dest,$options['filePermission']); } elseif(is_dir($source)) { if ($dest[strlen($dest)-1]=='/') { if ($source[strlen($source)-1]=='/') { //Copy only contents } else { //Change parent itself and its contents $dest=$dest.basename($source); @mkdir($dest); chmod($dest,$options['filePermission']); } } else { if ($source[strlen($source)-1]=='/') { //Copy parent directory with new name and all its content @mkdir($dest,$options['folderPermission']); chmod($dest,$options['filePermission']); } else { //Copy parent directory with new name and all its content @mkdir($dest,$options['folderPermission']); chmod($dest,$options['filePermission']); } } $dirHandle=opendir($source); while($file=readdir($dirHandle)) { if($file!="." && $file!="..") { if(!is_dir($source."/".$file)) { $__dest=$dest."/".$file; } else { $__dest=$dest."/".$file; } $result=Gdn_FileSystem::Copy($source."/".$file, $__dest, $options); } } closedir($dirHandle); } else { $result=false; } return $result; }
php
public static function Copy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755)){ $result=false; if (is_file($source)) { if ($dest[strlen($dest)-1]=='/') { if (!file_exists($dest)) { cmfcDirectory::makeAll($dest,$options['folderPermission'],true); } $__dest=$dest."/".basename($source); } else { $__dest=$dest; } $result=copy($source, $__dest); chmod($__dest,$options['filePermission']); } elseif(is_dir($source)) { if ($dest[strlen($dest)-1]=='/') { if ($source[strlen($source)-1]=='/') { //Copy only contents } else { //Change parent itself and its contents $dest=$dest.basename($source); @mkdir($dest); chmod($dest,$options['filePermission']); } } else { if ($source[strlen($source)-1]=='/') { //Copy parent directory with new name and all its content @mkdir($dest,$options['folderPermission']); chmod($dest,$options['filePermission']); } else { //Copy parent directory with new name and all its content @mkdir($dest,$options['folderPermission']); chmod($dest,$options['filePermission']); } } $dirHandle=opendir($source); while($file=readdir($dirHandle)) { if($file!="." && $file!="..") { if(!is_dir($source."/".$file)) { $__dest=$dest."/".$file; } else { $__dest=$dest."/".$file; } $result=Gdn_FileSystem::Copy($source."/".$file, $__dest, $options); } } closedir($dirHandle); } else { $result=false; } return $result; }
[ "public", "static", "function", "Copy", "(", "$", "source", ",", "$", "dest", ",", "$", "options", "=", "array", "(", "'folderPermission'", "=>", "0755", ",", "'filePermission'", "=>", "0755", ")", ")", "{", "$", "result", "=", "false", ";", "if", "(", "is_file", "(", "$", "source", ")", ")", "{", "if", "(", "$", "dest", "[", "strlen", "(", "$", "dest", ")", "-", "1", "]", "==", "'/'", ")", "{", "if", "(", "!", "file_exists", "(", "$", "dest", ")", ")", "{", "cmfcDirectory", "::", "makeAll", "(", "$", "dest", ",", "$", "options", "[", "'folderPermission'", "]", ",", "true", ")", ";", "}", "$", "__dest", "=", "$", "dest", ".", "\"/\"", ".", "basename", "(", "$", "source", ")", ";", "}", "else", "{", "$", "__dest", "=", "$", "dest", ";", "}", "$", "result", "=", "copy", "(", "$", "source", ",", "$", "__dest", ")", ";", "chmod", "(", "$", "__dest", ",", "$", "options", "[", "'filePermission'", "]", ")", ";", "}", "elseif", "(", "is_dir", "(", "$", "source", ")", ")", "{", "if", "(", "$", "dest", "[", "strlen", "(", "$", "dest", ")", "-", "1", "]", "==", "'/'", ")", "{", "if", "(", "$", "source", "[", "strlen", "(", "$", "source", ")", "-", "1", "]", "==", "'/'", ")", "{", "//Copy only contents", "}", "else", "{", "//Change parent itself and its contents", "$", "dest", "=", "$", "dest", ".", "basename", "(", "$", "source", ")", ";", "@", "mkdir", "(", "$", "dest", ")", ";", "chmod", "(", "$", "dest", ",", "$", "options", "[", "'filePermission'", "]", ")", ";", "}", "}", "else", "{", "if", "(", "$", "source", "[", "strlen", "(", "$", "source", ")", "-", "1", "]", "==", "'/'", ")", "{", "//Copy parent directory with new name and all its content", "@", "mkdir", "(", "$", "dest", ",", "$", "options", "[", "'folderPermission'", "]", ")", ";", "chmod", "(", "$", "dest", ",", "$", "options", "[", "'filePermission'", "]", ")", ";", "}", "else", "{", "//Copy parent directory with new name and all its content", "@", "mkdir", "(", "$", "dest", ",", "$", "options", "[", "'folderPermission'", "]", ")", ";", "chmod", "(", "$", "dest", ",", "$", "options", "[", "'filePermission'", "]", ")", ";", "}", "}", "$", "dirHandle", "=", "opendir", "(", "$", "source", ")", ";", "while", "(", "$", "file", "=", "readdir", "(", "$", "dirHandle", ")", ")", "{", "if", "(", "$", "file", "!=", "\".\"", "&&", "$", "file", "!=", "\"..\"", ")", "{", "if", "(", "!", "is_dir", "(", "$", "source", ".", "\"/\"", ".", "$", "file", ")", ")", "{", "$", "__dest", "=", "$", "dest", ".", "\"/\"", ".", "$", "file", ";", "}", "else", "{", "$", "__dest", "=", "$", "dest", ".", "\"/\"", ".", "$", "file", ";", "}", "$", "result", "=", "Gdn_FileSystem", "::", "Copy", "(", "$", "source", ".", "\"/\"", ".", "$", "file", ",", "$", "__dest", ",", "$", "options", ")", ";", "}", "}", "closedir", "(", "$", "dirHandle", ")", ";", "}", "else", "{", "$", "result", "=", "false", ";", "}", "return", "$", "result", ";", "}" ]
Copy file or folder from source to destination It can do recursive copy as well and is very smart It recursively creates the dest file or directory path if there weren't exists Situtaions : - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name @author Sina Salek - http://sina.salek.ws/en/contact @param $source //file or folder @param $dest ///file or folder @param $options //folderPermission,filePermission @return boolean
[ "Copy", "file", "or", "folder", "from", "source", "to", "destination" ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/library/core/class.filesystem.php#L455-L511
1,716
Celarius/nofuzz-framework
src/Config/Config.php
Config.save
function save(string $filename=null): bool { if (!empty($filename)) $this->filename = $filename; return ( file_put_contents($this->filename, json_encode($this->confValues,JSON_PRETTY_PRINT))!==false ); }
php
function save(string $filename=null): bool { if (!empty($filename)) $this->filename = $filename; return ( file_put_contents($this->filename, json_encode($this->confValues,JSON_PRETTY_PRINT))!==false ); }
[ "function", "save", "(", "string", "$", "filename", "=", "null", ")", ":", "bool", "{", "if", "(", "!", "empty", "(", "$", "filename", ")", ")", "$", "this", "->", "filename", "=", "$", "filename", ";", "return", "(", "file_put_contents", "(", "$", "this", "->", "filename", ",", "json_encode", "(", "$", "this", "->", "confValues", ",", "JSON_PRETTY_PRINT", ")", ")", "!==", "false", ")", ";", "}" ]
Save Configuration file @param string $filename If null the last used filename is used @return bool
[ "Save", "Configuration", "file" ]
867c5150baa431e8f800624a26ba80e95eebd4e5
https://github.com/Celarius/nofuzz-framework/blob/867c5150baa431e8f800624a26ba80e95eebd4e5/src/Config/Config.php#L104-L109
1,717
Celarius/nofuzz-framework
src/Config/Config.php
Config.get
public function get(string $key,string $default=null) { $keys = explode('.',$key); $val = $this->confValues; for ($i=0; $i<count($keys); $i++) { $val = ( $val[ $keys[$i] ] ?? null); if (is_null($val)) break; } return $val ?? $default; }
php
public function get(string $key,string $default=null) { $keys = explode('.',$key); $val = $this->confValues; for ($i=0; $i<count($keys); $i++) { $val = ( $val[ $keys[$i] ] ?? null); if (is_null($val)) break; } return $val ?? $default; }
[ "public", "function", "get", "(", "string", "$", "key", ",", "string", "$", "default", "=", "null", ")", "{", "$", "keys", "=", "explode", "(", "'.'", ",", "$", "key", ")", ";", "$", "val", "=", "$", "this", "->", "confValues", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "keys", ")", ";", "$", "i", "++", ")", "{", "$", "val", "=", "(", "$", "val", "[", "$", "keys", "[", "$", "i", "]", "]", "??", "null", ")", ";", "if", "(", "is_null", "(", "$", "val", ")", ")", "break", ";", "}", "return", "$", "val", "??", "$", "default", ";", "}" ]
Get a config item @param string $key "." notationed key to retreive @param string $default Optional Default value if group::section::key not found @return mixed
[ "Get", "a", "config", "item" ]
867c5150baa431e8f800624a26ba80e95eebd4e5
https://github.com/Celarius/nofuzz-framework/blob/867c5150baa431e8f800624a26ba80e95eebd4e5/src/Config/Config.php#L118-L129
1,718
tux-rampage/rampage-php
library/rampage/core/resources/Theme.php
Theme.resolveThemeFile
protected function resolveThemeFile($type, $file, $scope, $asFileInfo = false) { $themePath = ($scope)? $scope . '/' . ltrim($file, '/') : ltrim($file, '/'); $path = false; $stack = $this->getFallbackThemes(); array_unshift($stack, $this->getCurrentTheme()); while (($path === false) && ($theme = array_shift($stack))) { $path = $this->findThemeFile($type, $theme, $themePath); } if (!$asFileInfo && ($path !== false)) { $path = $path->getPathname(); } return $path; }
php
protected function resolveThemeFile($type, $file, $scope, $asFileInfo = false) { $themePath = ($scope)? $scope . '/' . ltrim($file, '/') : ltrim($file, '/'); $path = false; $stack = $this->getFallbackThemes(); array_unshift($stack, $this->getCurrentTheme()); while (($path === false) && ($theme = array_shift($stack))) { $path = $this->findThemeFile($type, $theme, $themePath); } if (!$asFileInfo && ($path !== false)) { $path = $path->getPathname(); } return $path; }
[ "protected", "function", "resolveThemeFile", "(", "$", "type", ",", "$", "file", ",", "$", "scope", ",", "$", "asFileInfo", "=", "false", ")", "{", "$", "themePath", "=", "(", "$", "scope", ")", "?", "$", "scope", ".", "'/'", ".", "ltrim", "(", "$", "file", ",", "'/'", ")", ":", "ltrim", "(", "$", "file", ",", "'/'", ")", ";", "$", "path", "=", "false", ";", "$", "stack", "=", "$", "this", "->", "getFallbackThemes", "(", ")", ";", "array_unshift", "(", "$", "stack", ",", "$", "this", "->", "getCurrentTheme", "(", ")", ")", ";", "while", "(", "(", "$", "path", "===", "false", ")", "&&", "(", "$", "theme", "=", "array_shift", "(", "$", "stack", ")", ")", ")", "{", "$", "path", "=", "$", "this", "->", "findThemeFile", "(", "$", "type", ",", "$", "theme", ",", "$", "themePath", ")", ";", "}", "if", "(", "!", "$", "asFileInfo", "&&", "(", "$", "path", "!==", "false", ")", ")", "{", "$", "path", "=", "$", "path", "->", "getPathname", "(", ")", ";", "}", "return", "$", "path", ";", "}" ]
Internal resolve theme file @param string $type @param string $file @param string $scope @param string $asFileInfo
[ "Internal", "resolve", "theme", "file" ]
1c679b04a6d477e2f8fdb86135e1d9f0c128b1cf
https://github.com/tux-rampage/rampage-php/blob/1c679b04a6d477e2f8fdb86135e1d9f0c128b1cf/library/rampage/core/resources/Theme.php#L181-L198
1,719
vincenttouzet/AdminConfigurationBundle
Entity/ConfigValue.php
ConfigValue.getPath
public function getPath() { $sname = ''; $gname = ''; $vname = $this->getName(); if ( $this->getConfigGroup() ) { if ( $this->getConfigGroup()->getConfigSection() ) { $sname = $this->getConfigGroup()->getConfigSection()->getName(); } $gname = $this->getConfigGroup()->getName(); } return sprintf( '%s:%s:%s', $sname, $gname, $vname ); }
php
public function getPath() { $sname = ''; $gname = ''; $vname = $this->getName(); if ( $this->getConfigGroup() ) { if ( $this->getConfigGroup()->getConfigSection() ) { $sname = $this->getConfigGroup()->getConfigSection()->getName(); } $gname = $this->getConfigGroup()->getName(); } return sprintf( '%s:%s:%s', $sname, $gname, $vname ); }
[ "public", "function", "getPath", "(", ")", "{", "$", "sname", "=", "''", ";", "$", "gname", "=", "''", ";", "$", "vname", "=", "$", "this", "->", "getName", "(", ")", ";", "if", "(", "$", "this", "->", "getConfigGroup", "(", ")", ")", "{", "if", "(", "$", "this", "->", "getConfigGroup", "(", ")", "->", "getConfigSection", "(", ")", ")", "{", "$", "sname", "=", "$", "this", "->", "getConfigGroup", "(", ")", "->", "getConfigSection", "(", ")", "->", "getName", "(", ")", ";", "}", "$", "gname", "=", "$", "this", "->", "getConfigGroup", "(", ")", "->", "getName", "(", ")", ";", "}", "return", "sprintf", "(", "'%s:%s:%s'", ",", "$", "sname", ",", "$", "gname", ",", "$", "vname", ")", ";", "}" ]
Return the path for this ConfigValue @return string
[ "Return", "the", "path", "for", "this", "ConfigValue" ]
8e7edd0810d88aa1d1be4bd303bcc14cbfd0caeb
https://github.com/vincenttouzet/AdminConfigurationBundle/blob/8e7edd0810d88aa1d1be4bd303bcc14cbfd0caeb/Entity/ConfigValue.php#L311-L329
1,720
cityware/city-snmp
src/MIBS/Linux/Host.php
Host.returnFullDataStorage
public function returnFullDataStorage() { $aStorage = $this->getSNMP()->realWalk1d(self::OID_STORAGE); $aReturn = Array(); $aReturn['memory_size'] = $aStorage[self::OID_STORAGE_MEMORY_SIZE][0]; $aReturn['index'] = $aStorage[self::OID_STORAGE_INDEX]; $aReturn['type'] = $aStorage[self::OID_STORAGE_TYPE]; $aReturn['description'] = $aStorage[self::OID_STORAGE_DESCR]; $aReturn['allocation_units'] = $aStorage[self::OID_STORAGE_ALLOCATION_UNITS]; $aReturn['size'] = $aStorage[self::OID_STORAGE_SIZE]; $aReturn['used'] = $aStorage[self::OID_STORAGE_USED]; return $aReturn; }
php
public function returnFullDataStorage() { $aStorage = $this->getSNMP()->realWalk1d(self::OID_STORAGE); $aReturn = Array(); $aReturn['memory_size'] = $aStorage[self::OID_STORAGE_MEMORY_SIZE][0]; $aReturn['index'] = $aStorage[self::OID_STORAGE_INDEX]; $aReturn['type'] = $aStorage[self::OID_STORAGE_TYPE]; $aReturn['description'] = $aStorage[self::OID_STORAGE_DESCR]; $aReturn['allocation_units'] = $aStorage[self::OID_STORAGE_ALLOCATION_UNITS]; $aReturn['size'] = $aStorage[self::OID_STORAGE_SIZE]; $aReturn['used'] = $aStorage[self::OID_STORAGE_USED]; return $aReturn; }
[ "public", "function", "returnFullDataStorage", "(", ")", "{", "$", "aStorage", "=", "$", "this", "->", "getSNMP", "(", ")", "->", "realWalk1d", "(", "self", "::", "OID_STORAGE", ")", ";", "$", "aReturn", "=", "Array", "(", ")", ";", "$", "aReturn", "[", "'memory_size'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_MEMORY_SIZE", "]", "[", "0", "]", ";", "$", "aReturn", "[", "'index'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_INDEX", "]", ";", "$", "aReturn", "[", "'type'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_TYPE", "]", ";", "$", "aReturn", "[", "'description'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_DESCR", "]", ";", "$", "aReturn", "[", "'allocation_units'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_ALLOCATION_UNITS", "]", ";", "$", "aReturn", "[", "'size'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_SIZE", "]", ";", "$", "aReturn", "[", "'used'", "]", "=", "$", "aStorage", "[", "self", "::", "OID_STORAGE_USED", "]", ";", "return", "$", "aReturn", ";", "}" ]
Returns Full Data Storage @return int
[ "Returns", "Full", "Data", "Storage" ]
831b7485b6c932a84f081d5ceeb9c5f4e7a8641d
https://github.com/cityware/city-snmp/blob/831b7485b6c932a84f081d5ceeb9c5f4e7a8641d/src/MIBS/Linux/Host.php#L64-L80
1,721
crazedsanity/session
src/session/Session.class.php
Session.get_cookie
public function get_cookie($name) { $retval = NULL; if(isset($_COOKIE) && isset($_COOKIE[$name])) { $retval = $_COOKIE[$name]; } return($retval); }
php
public function get_cookie($name) { $retval = NULL; if(isset($_COOKIE) && isset($_COOKIE[$name])) { $retval = $_COOKIE[$name]; } return($retval); }
[ "public", "function", "get_cookie", "(", "$", "name", ")", "{", "$", "retval", "=", "NULL", ";", "if", "(", "isset", "(", "$", "_COOKIE", ")", "&&", "isset", "(", "$", "_COOKIE", "[", "$", "name", "]", ")", ")", "{", "$", "retval", "=", "$", "_COOKIE", "[", "$", "name", "]", ";", "}", "return", "(", "$", "retval", ")", ";", "}" ]
Retrieve data for an existing cookie. @param $name (string) Name of cookie to retrieve value for. @return NULL FAIL (?): cookie doesn't exist or has NULL value. @return (string) PASS: value of cookie.
[ "Retrieve", "data", "for", "an", "existing", "cookie", "." ]
67236b90259cc0c7be0eeb2c7d58e13c4cd98b7c
https://github.com/crazedsanity/session/blob/67236b90259cc0c7be0eeb2c7d58e13c4cd98b7c/src/session/Session.class.php#L84-L90
1,722
mtils/collection
src/Collection/StringList.php
StringList.fromString
public static function fromString($string, $separator=' '){ $string = (string)$string; if($separator === ''){ return new StringList(str_split($string),''); } $prefix = ''; $suffix = ''; if($string[0] == $separator){ $prefix = $separator; } if($string[strlen($string)-1] == $separator){ $suffix = $separator; } $strList = new StringList(explode($separator,trim($string,$separator)), $separator); $strList->prefix = $prefix; $strList->suffix = $suffix; return $strList; }
php
public static function fromString($string, $separator=' '){ $string = (string)$string; if($separator === ''){ return new StringList(str_split($string),''); } $prefix = ''; $suffix = ''; if($string[0] == $separator){ $prefix = $separator; } if($string[strlen($string)-1] == $separator){ $suffix = $separator; } $strList = new StringList(explode($separator,trim($string,$separator)), $separator); $strList->prefix = $prefix; $strList->suffix = $suffix; return $strList; }
[ "public", "static", "function", "fromString", "(", "$", "string", ",", "$", "separator", "=", "' '", ")", "{", "$", "string", "=", "(", "string", ")", "$", "string", ";", "if", "(", "$", "separator", "===", "''", ")", "{", "return", "new", "StringList", "(", "str_split", "(", "$", "string", ")", ",", "''", ")", ";", "}", "$", "prefix", "=", "''", ";", "$", "suffix", "=", "''", ";", "if", "(", "$", "string", "[", "0", "]", "==", "$", "separator", ")", "{", "$", "prefix", "=", "$", "separator", ";", "}", "if", "(", "$", "string", "[", "strlen", "(", "$", "string", ")", "-", "1", "]", "==", "$", "separator", ")", "{", "$", "suffix", "=", "$", "separator", ";", "}", "$", "strList", "=", "new", "StringList", "(", "explode", "(", "$", "separator", ",", "trim", "(", "$", "string", ",", "$", "separator", ")", ")", ",", "$", "separator", ")", ";", "$", "strList", "->", "prefix", "=", "$", "prefix", ";", "$", "strList", "->", "suffix", "=", "$", "suffix", ";", "return", "$", "strList", ";", "}" ]
Creates a Stringlist from a string. @param string $string @param string $separator @return StringList
[ "Creates", "a", "Stringlist", "from", "a", "string", "." ]
186f8a6cc68fef1babc486438aa6d6c643186cc8
https://github.com/mtils/collection/blob/186f8a6cc68fef1babc486438aa6d6c643186cc8/src/Collection/StringList.php#L28-L49
1,723
mtils/collection
src/Collection/StringList.php
StringList.copy
public function copy(){ $copy = parent::copy(); $copy->delimiter = $this->delimiter; $copy->prefix = $this->prefix; $copy->suffix = $this->suffix; return $copy; }
php
public function copy(){ $copy = parent::copy(); $copy->delimiter = $this->delimiter; $copy->prefix = $this->prefix; $copy->suffix = $this->suffix; return $copy; }
[ "public", "function", "copy", "(", ")", "{", "$", "copy", "=", "parent", "::", "copy", "(", ")", ";", "$", "copy", "->", "delimiter", "=", "$", "this", "->", "delimiter", ";", "$", "copy", "->", "prefix", "=", "$", "this", "->", "prefix", ";", "$", "copy", "->", "suffix", "=", "$", "this", "->", "suffix", ";", "return", "$", "copy", ";", "}" ]
Returns a copy @return StringList @see OrderedList::copy()
[ "Returns", "a", "copy" ]
186f8a6cc68fef1babc486438aa6d6c643186cc8
https://github.com/mtils/collection/blob/186f8a6cc68fef1babc486438aa6d6c643186cc8/src/Collection/StringList.php#L57-L63
1,724
webriq/core
module/User/src/Grid/User/Datasheet/EventHandler.php
EventHandler.onRegister
public function onRegister(Event\Register $event) { $userModel = $this->getServiceLocator() ->get('Grid\User\Model\User\Model'); $user = $userModel->register( $event->getData() ); $event->setUser($user); if( is_null($event->getUser()) ) { $event->stopPropagation(true); } return $event; }
php
public function onRegister(Event\Register $event) { $userModel = $this->getServiceLocator() ->get('Grid\User\Model\User\Model'); $user = $userModel->register( $event->getData() ); $event->setUser($user); if( is_null($event->getUser()) ) { $event->stopPropagation(true); } return $event; }
[ "public", "function", "onRegister", "(", "Event", "\\", "Register", "$", "event", ")", "{", "$", "userModel", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "'Grid\\User\\Model\\User\\Model'", ")", ";", "$", "user", "=", "$", "userModel", "->", "register", "(", "$", "event", "->", "getData", "(", ")", ")", ";", "$", "event", "->", "setUser", "(", "$", "user", ")", ";", "if", "(", "is_null", "(", "$", "event", "->", "getUser", "(", ")", ")", ")", "{", "$", "event", "->", "stopPropagation", "(", "true", ")", ";", "}", "return", "$", "event", ";", "}" ]
Handles register event @param \Grid\User\Datasheet\Event\Register $event @return \Grid\User\Datasheet\Event\Register
[ "Handles", "register", "event" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/User/src/Grid/User/Datasheet/EventHandler.php#L35-L46
1,725
webriq/core
module/User/src/Grid/User/Datasheet/EventHandler.php
EventHandler.onSave
public function onSave(Event\Save $event) { $success = $event->getUser()->save(); $event->setResult( (bool)$success ); if( $event->getResult() === false ) { $event->stopPropagation(true); } return $event; }
php
public function onSave(Event\Save $event) { $success = $event->getUser()->save(); $event->setResult( (bool)$success ); if( $event->getResult() === false ) { $event->stopPropagation(true); } return $event; }
[ "public", "function", "onSave", "(", "Event", "\\", "Save", "$", "event", ")", "{", "$", "success", "=", "$", "event", "->", "getUser", "(", ")", "->", "save", "(", ")", ";", "$", "event", "->", "setResult", "(", "(", "bool", ")", "$", "success", ")", ";", "if", "(", "$", "event", "->", "getResult", "(", ")", "===", "false", ")", "{", "$", "event", "->", "stopPropagation", "(", "true", ")", ";", "}", "return", "$", "event", ";", "}" ]
Handles save event @param \Grid\User\Datasheet\Event\Save $event @return \Grid\User\Datasheet\Event\Save
[ "Handles", "save", "event" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/User/src/Grid/User/Datasheet/EventHandler.php#L54-L63
1,726
webriq/core
module/User/src/Grid/User/Datasheet/EventHandler.php
EventHandler.onDelete
public function onDelete(Event\Delete $event) { $success = $event->getUser()->delete(); $event->setResult( (bool)$success ); if( $event->getResult() === false ) { $event->stopPropagation(true); } return $event; }
php
public function onDelete(Event\Delete $event) { $success = $event->getUser()->delete(); $event->setResult( (bool)$success ); if( $event->getResult() === false ) { $event->stopPropagation(true); } return $event; }
[ "public", "function", "onDelete", "(", "Event", "\\", "Delete", "$", "event", ")", "{", "$", "success", "=", "$", "event", "->", "getUser", "(", ")", "->", "delete", "(", ")", ";", "$", "event", "->", "setResult", "(", "(", "bool", ")", "$", "success", ")", ";", "if", "(", "$", "event", "->", "getResult", "(", ")", "===", "false", ")", "{", "$", "event", "->", "stopPropagation", "(", "true", ")", ";", "}", "return", "$", "event", ";", "}" ]
Handles delete event @param \Grid\User\Datasheet\Event\Delete $event @return \Grid\User\Datasheet\Event\Delete
[ "Handles", "delete", "event" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/User/src/Grid/User/Datasheet/EventHandler.php#L71-L80
1,727
shov/wpci-core
Core.php
Core.run
public function run(callable $applicationThick) { try { /** @var PromiseManager $promiseManager */ $promiseManager = $this->getContainerManager() ->getContainer() ->get(PromiseManager::class); $promiseManager->addPromise('shutdown', function () { ShutdownPromisePool::callAllPromises(); }); $applicationThick(); RouterStore::makeBinding(); } catch (\Throwable $e) { if (!is_null($this->logger)) { $this->logger->error($e->getMessage(), [ 'stacktrace' => $e->getTrace(), ]); } } finally { ShutdownPromisePool::callAllPromises(); } }
php
public function run(callable $applicationThick) { try { /** @var PromiseManager $promiseManager */ $promiseManager = $this->getContainerManager() ->getContainer() ->get(PromiseManager::class); $promiseManager->addPromise('shutdown', function () { ShutdownPromisePool::callAllPromises(); }); $applicationThick(); RouterStore::makeBinding(); } catch (\Throwable $e) { if (!is_null($this->logger)) { $this->logger->error($e->getMessage(), [ 'stacktrace' => $e->getTrace(), ]); } } finally { ShutdownPromisePool::callAllPromises(); } }
[ "public", "function", "run", "(", "callable", "$", "applicationThick", ")", "{", "try", "{", "/** @var PromiseManager $promiseManager */", "$", "promiseManager", "=", "$", "this", "->", "getContainerManager", "(", ")", "->", "getContainer", "(", ")", "->", "get", "(", "PromiseManager", "::", "class", ")", ";", "$", "promiseManager", "->", "addPromise", "(", "'shutdown'", ",", "function", "(", ")", "{", "ShutdownPromisePool", "::", "callAllPromises", "(", ")", ";", "}", ")", ";", "$", "applicationThick", "(", ")", ";", "RouterStore", "::", "makeBinding", "(", ")", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "if", "(", "!", "is_null", "(", "$", "this", "->", "logger", ")", ")", "{", "$", "this", "->", "logger", "->", "error", "(", "$", "e", "->", "getMessage", "(", ")", ",", "[", "'stacktrace'", "=>", "$", "e", "->", "getTrace", "(", ")", ",", "]", ")", ";", "}", "}", "finally", "{", "ShutdownPromisePool", "::", "callAllPromises", "(", ")", ";", "}", "}" ]
Run the App @param callable $applicationThick
[ "Run", "the", "App" ]
e31084cbc2f310882df2b9b0548330ea5fdb4f26
https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Core.php#L62-L87
1,728
shov/wpci-core
Core.php
Core.setPath
public function setPath(string $appRoot) { $this->path = new Path($appRoot, $this->coreRoot); $this->containerManager ->getContainer() ->instance(Path::class, $this->path); }
php
public function setPath(string $appRoot) { $this->path = new Path($appRoot, $this->coreRoot); $this->containerManager ->getContainer() ->instance(Path::class, $this->path); }
[ "public", "function", "setPath", "(", "string", "$", "appRoot", ")", "{", "$", "this", "->", "path", "=", "new", "Path", "(", "$", "appRoot", ",", "$", "this", "->", "coreRoot", ")", ";", "$", "this", "->", "containerManager", "->", "getContainer", "(", ")", "->", "instance", "(", "Path", "::", "class", ",", "$", "this", "->", "path", ")", ";", "}" ]
Set path instance by App @param string $appRoot
[ "Set", "path", "instance", "by", "App" ]
e31084cbc2f310882df2b9b0548330ea5fdb4f26
https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Core.php#L102-L109
1,729
shov/wpci-core
Core.php
Core.env
public function env(string $var, $default = null) { $value = getenv($var) ?? null; if ($value === false) { return $default instanceof Closure ? $default() : $default; } switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'empty': case '(empty)': return ''; case 'null': case '(null)': return null; } if ( strlen($value) > 1 && (0 === strpos($value, '"')) && (strlen($value) - 1 === strpos($value, '"')) ) { return substr($value, 1, -1); } return $value; }
php
public function env(string $var, $default = null) { $value = getenv($var) ?? null; if ($value === false) { return $default instanceof Closure ? $default() : $default; } switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'empty': case '(empty)': return ''; case 'null': case '(null)': return null; } if ( strlen($value) > 1 && (0 === strpos($value, '"')) && (strlen($value) - 1 === strpos($value, '"')) ) { return substr($value, 1, -1); } return $value; }
[ "public", "function", "env", "(", "string", "$", "var", ",", "$", "default", "=", "null", ")", "{", "$", "value", "=", "getenv", "(", "$", "var", ")", "??", "null", ";", "if", "(", "$", "value", "===", "false", ")", "{", "return", "$", "default", "instanceof", "Closure", "?", "$", "default", "(", ")", ":", "$", "default", ";", "}", "switch", "(", "strtolower", "(", "$", "value", ")", ")", "{", "case", "'true'", ":", "case", "'(true)'", ":", "return", "true", ";", "case", "'false'", ":", "case", "'(false)'", ":", "return", "false", ";", "case", "'empty'", ":", "case", "'(empty)'", ":", "return", "''", ";", "case", "'null'", ":", "case", "'(null)'", ":", "return", "null", ";", "}", "if", "(", "strlen", "(", "$", "value", ")", ">", "1", "&&", "(", "0", "===", "strpos", "(", "$", "value", ",", "'\"'", ")", ")", "&&", "(", "strlen", "(", "$", "value", ")", "-", "1", "===", "strpos", "(", "$", "value", ",", "'\"'", ")", ")", ")", "{", "return", "substr", "(", "$", "value", ",", "1", ",", "-", "1", ")", ";", "}", "return", "$", "value", ";", "}" ]
Accessor to environment vars @param string $var @param $default @return null|mixed
[ "Accessor", "to", "environment", "vars" ]
e31084cbc2f310882df2b9b0548330ea5fdb4f26
https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Core.php#L133-L165
1,730
shov/wpci-core
Core.php
Core.initServiceContainer
protected function initServiceContainer(Container $container) { $sr = new ServiceRegistrator($this->coreRoot, "Wpci\\Core\\", $container); $sr->exclude(Path::class); $sr->prepareArguments(View::class, [ TemplateInterface::class => MustacheTemplate::class, ResponseInterface::class => WpResponse::class ] ); $sr->walkDirForServices('Flow'); $sr->walkDirForServices('DataSource'); $sr->walkDirForServices('Helpers'); $sr->walkDirForServices('Http'); $sr->walkDirForServices('Render'); $sr->walkDirForServices('Wordpress'); $container->singleton('router-store', \Wpci\Core\Http\RouterStore::class); $container->instance('promise-pool.shutdown', new PromisePool()); }
php
protected function initServiceContainer(Container $container) { $sr = new ServiceRegistrator($this->coreRoot, "Wpci\\Core\\", $container); $sr->exclude(Path::class); $sr->prepareArguments(View::class, [ TemplateInterface::class => MustacheTemplate::class, ResponseInterface::class => WpResponse::class ] ); $sr->walkDirForServices('Flow'); $sr->walkDirForServices('DataSource'); $sr->walkDirForServices('Helpers'); $sr->walkDirForServices('Http'); $sr->walkDirForServices('Render'); $sr->walkDirForServices('Wordpress'); $container->singleton('router-store', \Wpci\Core\Http\RouterStore::class); $container->instance('promise-pool.shutdown', new PromisePool()); }
[ "protected", "function", "initServiceContainer", "(", "Container", "$", "container", ")", "{", "$", "sr", "=", "new", "ServiceRegistrator", "(", "$", "this", "->", "coreRoot", ",", "\"Wpci\\\\Core\\\\\"", ",", "$", "container", ")", ";", "$", "sr", "->", "exclude", "(", "Path", "::", "class", ")", ";", "$", "sr", "->", "prepareArguments", "(", "View", "::", "class", ",", "[", "TemplateInterface", "::", "class", "=>", "MustacheTemplate", "::", "class", ",", "ResponseInterface", "::", "class", "=>", "WpResponse", "::", "class", "]", ")", ";", "$", "sr", "->", "walkDirForServices", "(", "'Flow'", ")", ";", "$", "sr", "->", "walkDirForServices", "(", "'DataSource'", ")", ";", "$", "sr", "->", "walkDirForServices", "(", "'Helpers'", ")", ";", "$", "sr", "->", "walkDirForServices", "(", "'Http'", ")", ";", "$", "sr", "->", "walkDirForServices", "(", "'Render'", ")", ";", "$", "sr", "->", "walkDirForServices", "(", "'Wordpress'", ")", ";", "$", "container", "->", "singleton", "(", "'router-store'", ",", "\\", "Wpci", "\\", "Core", "\\", "Http", "\\", "RouterStore", "::", "class", ")", ";", "$", "container", "->", "instance", "(", "'promise-pool.shutdown'", ",", "new", "PromisePool", "(", ")", ")", ";", "}" ]
Service container inti instructions @param ContainerBuilder $container @throws \Exception
[ "Service", "container", "inti", "instructions" ]
e31084cbc2f310882df2b9b0548330ea5fdb4f26
https://github.com/shov/wpci-core/blob/e31084cbc2f310882df2b9b0548330ea5fdb4f26/Core.php#L172-L194
1,731
circle314/collection
src/AbstractCollection.php
AbstractCollection.isCollectionClass
final protected function isCollectionClass($collectionItem) { if(is_null($this->collectionClass)) { return true; } else { return is_a($collectionItem, $this->collectionClass->getValue()); } }
php
final protected function isCollectionClass($collectionItem) { if(is_null($this->collectionClass)) { return true; } else { return is_a($collectionItem, $this->collectionClass->getValue()); } }
[ "final", "protected", "function", "isCollectionClass", "(", "$", "collectionItem", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "collectionClass", ")", ")", "{", "return", "true", ";", "}", "else", "{", "return", "is_a", "(", "$", "collectionItem", ",", "$", "this", "->", "collectionClass", "->", "getValue", "(", ")", ")", ";", "}", "}" ]
Checks if a proposed collection item is the correct collection item class. @param mixed|CollectionItemInterface $collectionItem @return bool
[ "Checks", "if", "a", "proposed", "collection", "item", "is", "the", "correct", "collection", "item", "class", "." ]
66167e4349da7be5f8db824848f9de9b704c5e57
https://github.com/circle314/collection/blob/66167e4349da7be5f8db824848f9de9b704c5e57/src/AbstractCollection.php#L80-L87
1,732
circle314/collection
src/AbstractCollection.php
AbstractCollection.setCollectionClass
final protected function setCollectionClass($class) { try { $this->collectionClass = new StringType($class); } catch (TypeValidationException $e) { $this->collectionClass = CollectionConstants::_UNMAPPABLE_CLASS; } catch (ValueOutOfBoundsException $e) { $this->collectionClass = CollectionConstants::_UNMAPPABLE_CLASS; } }
php
final protected function setCollectionClass($class) { try { $this->collectionClass = new StringType($class); } catch (TypeValidationException $e) { $this->collectionClass = CollectionConstants::_UNMAPPABLE_CLASS; } catch (ValueOutOfBoundsException $e) { $this->collectionClass = CollectionConstants::_UNMAPPABLE_CLASS; } }
[ "final", "protected", "function", "setCollectionClass", "(", "$", "class", ")", "{", "try", "{", "$", "this", "->", "collectionClass", "=", "new", "StringType", "(", "$", "class", ")", ";", "}", "catch", "(", "TypeValidationException", "$", "e", ")", "{", "$", "this", "->", "collectionClass", "=", "CollectionConstants", "::", "_UNMAPPABLE_CLASS", ";", "}", "catch", "(", "ValueOutOfBoundsException", "$", "e", ")", "{", "$", "this", "->", "collectionClass", "=", "CollectionConstants", "::", "_UNMAPPABLE_CLASS", ";", "}", "}" ]
Sets the expected class for the collection's items. This is to be used when extending this class to create a collection of a specific type. The method should be called in the constructor before calling the parent constructor, e.g: ``` public function __construct(Array $collectionItems = []) { $this->setCollectionClass(MyClass::class); parent::__construct($collectionItems); } ``` @param $class string @return void
[ "Sets", "the", "expected", "class", "for", "the", "collection", "s", "items", "." ]
66167e4349da7be5f8db824848f9de9b704c5e57
https://github.com/circle314/collection/blob/66167e4349da7be5f8db824848f9de9b704c5e57/src/AbstractCollection.php#L120-L129
1,733
daniel-melzer/teacup-log
Log.php
Log.log
public function log($message, $level, array $context = array()) { $return = true; if(!isset(self::$levels[$level])) { throw new \OutOfBoundsException('Log level invalid'); } if((int)$level <= $this->level) { $message = sprintf( $this->logFormat . PHP_EOL, date($this->dateFormat), self::$levels[$level], $this->interpolate((string)$message, $context) ); if(false === fwrite($this->handle, $message)) { $return = false; } } return $return; }
php
public function log($message, $level, array $context = array()) { $return = true; if(!isset(self::$levels[$level])) { throw new \OutOfBoundsException('Log level invalid'); } if((int)$level <= $this->level) { $message = sprintf( $this->logFormat . PHP_EOL, date($this->dateFormat), self::$levels[$level], $this->interpolate((string)$message, $context) ); if(false === fwrite($this->handle, $message)) { $return = false; } } return $return; }
[ "public", "function", "log", "(", "$", "message", ",", "$", "level", ",", "array", "$", "context", "=", "array", "(", ")", ")", "{", "$", "return", "=", "true", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "levels", "[", "$", "level", "]", ")", ")", "{", "throw", "new", "\\", "OutOfBoundsException", "(", "'Log level invalid'", ")", ";", "}", "if", "(", "(", "int", ")", "$", "level", "<=", "$", "this", "->", "level", ")", "{", "$", "message", "=", "sprintf", "(", "$", "this", "->", "logFormat", ".", "PHP_EOL", ",", "date", "(", "$", "this", "->", "dateFormat", ")", ",", "self", "::", "$", "levels", "[", "$", "level", "]", ",", "$", "this", "->", "interpolate", "(", "(", "string", ")", "$", "message", ",", "$", "context", ")", ")", ";", "if", "(", "false", "===", "fwrite", "(", "$", "this", "->", "handle", ",", "$", "message", ")", ")", "{", "$", "return", "=", "false", ";", "}", "}", "return", "$", "return", ";", "}" ]
Writes a log message of a given level. @param string $message @param integer $level @param array $context @return boolean @throws \OutOfBoundsException
[ "Writes", "a", "log", "message", "of", "a", "given", "level", "." ]
1c994fede4d77d147f7620f9b3621c5521c56daf
https://github.com/daniel-melzer/teacup-log/blob/1c994fede4d77d147f7620f9b3621c5521c56daf/Log.php#L103-L124
1,734
a2c/BaconUserBundle
Controller/UserController.php
UserController.showAction
public function showAction($id) { $acl = $this->get('bacon_acl.service.authorization'); if (!$acl->authorize('users', 'SHOW')) { throw $this->createAccessDeniedException(); } $breadcumbs = $this->container->get('bacon_breadcrumbs'); $breadcumbs->addItem(array( 'title' => 'User', 'route' => 'admin_user', )); $breadcumbs->addItem(array( 'title' => 'Details', 'route' => '', )); $className = $this->getParameter('fos_user.model.user.class'); $entity = $this->getDoctrine()->getRepository($className)->find($id); if (!$entity) { $this->get('session')->getFlashBag()->add('message', array( 'type' => 'error', 'message' => 'The registry not Found', )); return $this->redirect($this->generateUrl('admin_user')); } $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), ); }
php
public function showAction($id) { $acl = $this->get('bacon_acl.service.authorization'); if (!$acl->authorize('users', 'SHOW')) { throw $this->createAccessDeniedException(); } $breadcumbs = $this->container->get('bacon_breadcrumbs'); $breadcumbs->addItem(array( 'title' => 'User', 'route' => 'admin_user', )); $breadcumbs->addItem(array( 'title' => 'Details', 'route' => '', )); $className = $this->getParameter('fos_user.model.user.class'); $entity = $this->getDoctrine()->getRepository($className)->find($id); if (!$entity) { $this->get('session')->getFlashBag()->add('message', array( 'type' => 'error', 'message' => 'The registry not Found', )); return $this->redirect($this->generateUrl('admin_user')); } $deleteForm = $this->createDeleteForm($id); return array( 'entity' => $entity, 'delete_form' => $deleteForm->createView(), ); }
[ "public", "function", "showAction", "(", "$", "id", ")", "{", "$", "acl", "=", "$", "this", "->", "get", "(", "'bacon_acl.service.authorization'", ")", ";", "if", "(", "!", "$", "acl", "->", "authorize", "(", "'users'", ",", "'SHOW'", ")", ")", "{", "throw", "$", "this", "->", "createAccessDeniedException", "(", ")", ";", "}", "$", "breadcumbs", "=", "$", "this", "->", "container", "->", "get", "(", "'bacon_breadcrumbs'", ")", ";", "$", "breadcumbs", "->", "addItem", "(", "array", "(", "'title'", "=>", "'User'", ",", "'route'", "=>", "'admin_user'", ",", ")", ")", ";", "$", "breadcumbs", "->", "addItem", "(", "array", "(", "'title'", "=>", "'Details'", ",", "'route'", "=>", "''", ",", ")", ")", ";", "$", "className", "=", "$", "this", "->", "getParameter", "(", "'fos_user.model.user.class'", ")", ";", "$", "entity", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getRepository", "(", "$", "className", ")", "->", "find", "(", "$", "id", ")", ";", "if", "(", "!", "$", "entity", ")", "{", "$", "this", "->", "get", "(", "'session'", ")", "->", "getFlashBag", "(", ")", "->", "add", "(", "'message'", ",", "array", "(", "'type'", "=>", "'error'", ",", "'message'", "=>", "'The registry not Found'", ",", ")", ")", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "generateUrl", "(", "'admin_user'", ")", ")", ";", "}", "$", "deleteForm", "=", "$", "this", "->", "createDeleteForm", "(", "$", "id", ")", ";", "return", "array", "(", "'entity'", "=>", "$", "entity", ",", "'delete_form'", "=>", "$", "deleteForm", "->", "createView", "(", ")", ",", ")", ";", "}" ]
Finds and displays a User entity. @Route("/{id}", name="admin_user_show") @Method("GET") @Security("has_role('ROLE_ADMIN')") @Template()
[ "Finds", "and", "displays", "a", "User", "entity", "." ]
2d192aaa05edabb75b66ce8fae02e436333adc03
https://github.com/a2c/BaconUserBundle/blob/2d192aaa05edabb75b66ce8fae02e436333adc03/Controller/UserController.php#L169-L210
1,735
eghojansu/nutrition
src/Security/UserManager.php
UserManager.getUser
public function getUser() { if (null === $this->user && $this->isLogin()) { $username = Base::instance()->get(static::SESSION_USER); $this->user = Security::instance()->getUserProvider()->loadByUsername($username); try { Authentication::instance()->checkUser($this->user); } catch(Exception $e) { $this->user = null; } } return $this->user; }
php
public function getUser() { if (null === $this->user && $this->isLogin()) { $username = Base::instance()->get(static::SESSION_USER); $this->user = Security::instance()->getUserProvider()->loadByUsername($username); try { Authentication::instance()->checkUser($this->user); } catch(Exception $e) { $this->user = null; } } return $this->user; }
[ "public", "function", "getUser", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "user", "&&", "$", "this", "->", "isLogin", "(", ")", ")", "{", "$", "username", "=", "Base", "::", "instance", "(", ")", "->", "get", "(", "static", "::", "SESSION_USER", ")", ";", "$", "this", "->", "user", "=", "Security", "::", "instance", "(", ")", "->", "getUserProvider", "(", ")", "->", "loadByUsername", "(", "$", "username", ")", ";", "try", "{", "Authentication", "::", "instance", "(", ")", "->", "checkUser", "(", "$", "this", "->", "user", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "this", "->", "user", "=", "null", ";", "}", "}", "return", "$", "this", "->", "user", ";", "}" ]
Get user, load from session if needed @return UserInterface
[ "Get", "user", "load", "from", "session", "if", "needed" ]
3941c62aeb6dafda55349a38dd4107d521f8964a
https://github.com/eghojansu/nutrition/blob/3941c62aeb6dafda55349a38dd4107d521f8964a/src/Security/UserManager.php#L57-L71
1,736
webriq/core
module/Menu/src/Grid/Menu/Model/Menu/Structure/Uri.php
Uri.setUri
public function setUri( $uri ) { $uri = (string) $uri; if ( empty( $uri ) ) { $uri = '#'; } else if ( ! preg_match( '(^(' . static::VALID_SCHEMES . '))', $uri ) ) { if ( preg_match( '(^[a-z0-9-]+(\.[a-z0-9-]+)+(/.*)?$)', $uri ) ) { $uri = static::DEFAULT_SCHEME . $uri; } else { $uri = '/' . ltrim( $uri, '/' ); } } $this->uri = $uri; return $this; }
php
public function setUri( $uri ) { $uri = (string) $uri; if ( empty( $uri ) ) { $uri = '#'; } else if ( ! preg_match( '(^(' . static::VALID_SCHEMES . '))', $uri ) ) { if ( preg_match( '(^[a-z0-9-]+(\.[a-z0-9-]+)+(/.*)?$)', $uri ) ) { $uri = static::DEFAULT_SCHEME . $uri; } else { $uri = '/' . ltrim( $uri, '/' ); } } $this->uri = $uri; return $this; }
[ "public", "function", "setUri", "(", "$", "uri", ")", "{", "$", "uri", "=", "(", "string", ")", "$", "uri", ";", "if", "(", "empty", "(", "$", "uri", ")", ")", "{", "$", "uri", "=", "'#'", ";", "}", "else", "if", "(", "!", "preg_match", "(", "'(^('", ".", "static", "::", "VALID_SCHEMES", ".", "'))'", ",", "$", "uri", ")", ")", "{", "if", "(", "preg_match", "(", "'(^[a-z0-9-]+(\\.[a-z0-9-]+)+(/.*)?$)'", ",", "$", "uri", ")", ")", "{", "$", "uri", "=", "static", "::", "DEFAULT_SCHEME", ".", "$", "uri", ";", "}", "else", "{", "$", "uri", "=", "'/'", ".", "ltrim", "(", "$", "uri", ",", "'/'", ")", ";", "}", "}", "$", "this", "->", "uri", "=", "$", "uri", ";", "return", "$", "this", ";", "}" ]
Setter for uri @param string $uri @return Grid\Menu\Model\Menu\Structure\Uri
[ "Setter", "for", "uri" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/Menu/src/Grid/Menu/Model/Menu/Structure/Uri.php#L53-L75
1,737
flowcode/ceibo
src/flowcode/ceibo/builder/QueryBuilder.php
QueryBuilder.buildDeleteRelationQuery
public static function buildDeleteRelationQuery(Relation $relation) { $query = "DELETE FROM `" . $relation->getTable() . "` "; $query .= "WHERE " . $relation->getLocalColumn() . " = :id;"; return $query; }
php
public static function buildDeleteRelationQuery(Relation $relation) { $query = "DELETE FROM `" . $relation->getTable() . "` "; $query .= "WHERE " . $relation->getLocalColumn() . " = :id;"; return $query; }
[ "public", "static", "function", "buildDeleteRelationQuery", "(", "Relation", "$", "relation", ")", "{", "$", "query", "=", "\"DELETE FROM `\"", ".", "$", "relation", "->", "getTable", "(", ")", ".", "\"` \"", ";", "$", "query", ".=", "\"WHERE \"", ".", "$", "relation", "->", "getLocalColumn", "(", ")", ".", "\" = :id;\"", ";", "return", "$", "query", ";", "}" ]
Build a delete query for a relation. @param type $relation @return string
[ "Build", "a", "delete", "query", "for", "a", "relation", "." ]
ba264dc681a9d803885fd35d10b0e37776f66659
https://github.com/flowcode/ceibo/blob/ba264dc681a9d803885fd35d10b0e37776f66659/src/flowcode/ceibo/builder/QueryBuilder.php#L32-L36
1,738
flowcode/ceibo
src/flowcode/ceibo/builder/QueryBuilder.php
QueryBuilder.buildRelationQuery
public static function buildRelationQuery($entity, Relation $relation) { $relQuery = ""; $getid = "getId"; if ($relation->getCardinality() == Relation::$manyToMany) { $m = "get" . $relation->getName(); $relQuery .= "INSERT INTO " . $relation->getTable() . " (" . $relation->getLocalColumn() . ", " . $relation->getForeignColumn() . ") "; $relQuery .= "VALUES (:" . $relation->getLocalColumn() . ", :" . $relation->getForeignColumn() . ");"; } if ($relation->getCardinality() == Relation::$oneToMany) { $relMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity()); $m = "get" . $relation->getName(); foreach ($entity->$m() as $rel) { $setid = "set" . $relMapper->getNameForColumn($relation->getForeignColumn()); $rel->$setid($entity->$getid()); $relQuery .= $this->buildInsertQuery($rel); } } return $relQuery; }
php
public static function buildRelationQuery($entity, Relation $relation) { $relQuery = ""; $getid = "getId"; if ($relation->getCardinality() == Relation::$manyToMany) { $m = "get" . $relation->getName(); $relQuery .= "INSERT INTO " . $relation->getTable() . " (" . $relation->getLocalColumn() . ", " . $relation->getForeignColumn() . ") "; $relQuery .= "VALUES (:" . $relation->getLocalColumn() . ", :" . $relation->getForeignColumn() . ");"; } if ($relation->getCardinality() == Relation::$oneToMany) { $relMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity()); $m = "get" . $relation->getName(); foreach ($entity->$m() as $rel) { $setid = "set" . $relMapper->getNameForColumn($relation->getForeignColumn()); $rel->$setid($entity->$getid()); $relQuery .= $this->buildInsertQuery($rel); } } return $relQuery; }
[ "public", "static", "function", "buildRelationQuery", "(", "$", "entity", ",", "Relation", "$", "relation", ")", "{", "$", "relQuery", "=", "\"\"", ";", "$", "getid", "=", "\"getId\"", ";", "if", "(", "$", "relation", "->", "getCardinality", "(", ")", "==", "Relation", "::", "$", "manyToMany", ")", "{", "$", "m", "=", "\"get\"", ".", "$", "relation", "->", "getName", "(", ")", ";", "$", "relQuery", ".=", "\"INSERT INTO \"", ".", "$", "relation", "->", "getTable", "(", ")", ".", "\" (\"", ".", "$", "relation", "->", "getLocalColumn", "(", ")", ".", "\", \"", ".", "$", "relation", "->", "getForeignColumn", "(", ")", ".", "\") \"", ";", "$", "relQuery", ".=", "\"VALUES (:\"", ".", "$", "relation", "->", "getLocalColumn", "(", ")", ".", "\", :\"", ".", "$", "relation", "->", "getForeignColumn", "(", ")", ".", "\");\"", ";", "}", "if", "(", "$", "relation", "->", "getCardinality", "(", ")", "==", "Relation", "::", "$", "oneToMany", ")", "{", "$", "relMapper", "=", "MapperBuilder", "::", "buildFromName", "(", "$", "this", "->", "mapping", ",", "$", "relation", "->", "getEntity", "(", ")", ")", ";", "$", "m", "=", "\"get\"", ".", "$", "relation", "->", "getName", "(", ")", ";", "foreach", "(", "$", "entity", "->", "$", "m", "(", ")", "as", "$", "rel", ")", "{", "$", "setid", "=", "\"set\"", ".", "$", "relMapper", "->", "getNameForColumn", "(", "$", "relation", "->", "getForeignColumn", "(", ")", ")", ";", "$", "rel", "->", "$", "setid", "(", "$", "entity", "->", "$", "getid", "(", ")", ")", ";", "$", "relQuery", ".=", "$", "this", "->", "buildInsertQuery", "(", "$", "rel", ")", ";", "}", "}", "return", "$", "relQuery", ";", "}" ]
Return the insert relation query. @param type $entity @param Relation $relation @return string $query.
[ "Return", "the", "insert", "relation", "query", "." ]
ba264dc681a9d803885fd35d10b0e37776f66659
https://github.com/flowcode/ceibo/blob/ba264dc681a9d803885fd35d10b0e37776f66659/src/flowcode/ceibo/builder/QueryBuilder.php#L72-L92
1,739
flowcode/ceibo
src/flowcode/ceibo/builder/QueryBuilder.php
QueryBuilder.buildUpdateQuery
public static function buildUpdateQuery($entity, Mapper $mapper) { $fields = ""; foreach ($mapper->getPropertys() as $property) { if ($property->getColumn() != "id") { $method = "get" . $property->getName(); $entity->$method(); if ($property->isNumeric()) { $fieldValue = "`=:" . $property->getColumn() . ", "; } else { $fieldValue = "`=:" . $property->getColumn() . ", "; } $fields .= "`" . $property->getColumn() . $fieldValue; } } $fields = substr_replace($fields, "", -2); $query = "UPDATE `" . $mapper->getTable() . "` SET " . $fields . " WHERE id=:id"; return $query; }
php
public static function buildUpdateQuery($entity, Mapper $mapper) { $fields = ""; foreach ($mapper->getPropertys() as $property) { if ($property->getColumn() != "id") { $method = "get" . $property->getName(); $entity->$method(); if ($property->isNumeric()) { $fieldValue = "`=:" . $property->getColumn() . ", "; } else { $fieldValue = "`=:" . $property->getColumn() . ", "; } $fields .= "`" . $property->getColumn() . $fieldValue; } } $fields = substr_replace($fields, "", -2); $query = "UPDATE `" . $mapper->getTable() . "` SET " . $fields . " WHERE id=:id"; return $query; }
[ "public", "static", "function", "buildUpdateQuery", "(", "$", "entity", ",", "Mapper", "$", "mapper", ")", "{", "$", "fields", "=", "\"\"", ";", "foreach", "(", "$", "mapper", "->", "getPropertys", "(", ")", "as", "$", "property", ")", "{", "if", "(", "$", "property", "->", "getColumn", "(", ")", "!=", "\"id\"", ")", "{", "$", "method", "=", "\"get\"", ".", "$", "property", "->", "getName", "(", ")", ";", "$", "entity", "->", "$", "method", "(", ")", ";", "if", "(", "$", "property", "->", "isNumeric", "(", ")", ")", "{", "$", "fieldValue", "=", "\"`=:\"", ".", "$", "property", "->", "getColumn", "(", ")", ".", "\", \"", ";", "}", "else", "{", "$", "fieldValue", "=", "\"`=:\"", ".", "$", "property", "->", "getColumn", "(", ")", ".", "\", \"", ";", "}", "$", "fields", ".=", "\"`\"", ".", "$", "property", "->", "getColumn", "(", ")", ".", "$", "fieldValue", ";", "}", "}", "$", "fields", "=", "substr_replace", "(", "$", "fields", ",", "\"\"", ",", "-", "2", ")", ";", "$", "query", "=", "\"UPDATE `\"", ".", "$", "mapper", "->", "getTable", "(", ")", ".", "\"` SET \"", ".", "$", "fields", ".", "\" WHERE id=:id\"", ";", "return", "$", "query", ";", "}" ]
Return the update query for the entity. @param type $entity @param Mapper $mapper @return string
[ "Return", "the", "update", "query", "for", "the", "entity", "." ]
ba264dc681a9d803885fd35d10b0e37776f66659
https://github.com/flowcode/ceibo/blob/ba264dc681a9d803885fd35d10b0e37776f66659/src/flowcode/ceibo/builder/QueryBuilder.php#L100-L119
1,740
flowcode/ceibo
src/flowcode/ceibo/builder/QueryBuilder.php
QueryBuilder.buildSelectRelation
public static function buildSelectRelation($relation, $mapperRelation) { $query = ""; $fields = ""; foreach ($mapperRelation->getPropertys() as $property) { $fields .= "c." . $property->getColumn() . ", "; } $fields = substr_replace($fields, "", -2); if ($relation->getCardinality() == Relation::$manyToMany) { $query = "select " . $fields . " from " . $mapperRelation->getTable() . " c "; $query .= "inner join " . $relation->getTable() . " nc on nc." . $relation->getForeignColumn() . " = c.id "; $query .= "where nc." . $relation->getLocalColumn() . " = :id"; } if ($relation->getCardinality() == Relation::$oneToMany) { $query = "select " . $fields . " from " . $mapperRelation->getTable() . " c "; $query .= "where c." . $relation->getForeignColumn() . " = :id"; } return $query; }
php
public static function buildSelectRelation($relation, $mapperRelation) { $query = ""; $fields = ""; foreach ($mapperRelation->getPropertys() as $property) { $fields .= "c." . $property->getColumn() . ", "; } $fields = substr_replace($fields, "", -2); if ($relation->getCardinality() == Relation::$manyToMany) { $query = "select " . $fields . " from " . $mapperRelation->getTable() . " c "; $query .= "inner join " . $relation->getTable() . " nc on nc." . $relation->getForeignColumn() . " = c.id "; $query .= "where nc." . $relation->getLocalColumn() . " = :id"; } if ($relation->getCardinality() == Relation::$oneToMany) { $query = "select " . $fields . " from " . $mapperRelation->getTable() . " c "; $query .= "where c." . $relation->getForeignColumn() . " = :id"; } return $query; }
[ "public", "static", "function", "buildSelectRelation", "(", "$", "relation", ",", "$", "mapperRelation", ")", "{", "$", "query", "=", "\"\"", ";", "$", "fields", "=", "\"\"", ";", "foreach", "(", "$", "mapperRelation", "->", "getPropertys", "(", ")", "as", "$", "property", ")", "{", "$", "fields", ".=", "\"c.\"", ".", "$", "property", "->", "getColumn", "(", ")", ".", "\", \"", ";", "}", "$", "fields", "=", "substr_replace", "(", "$", "fields", ",", "\"\"", ",", "-", "2", ")", ";", "if", "(", "$", "relation", "->", "getCardinality", "(", ")", "==", "Relation", "::", "$", "manyToMany", ")", "{", "$", "query", "=", "\"select \"", ".", "$", "fields", ".", "\" from \"", ".", "$", "mapperRelation", "->", "getTable", "(", ")", ".", "\" c \"", ";", "$", "query", ".=", "\"inner join \"", ".", "$", "relation", "->", "getTable", "(", ")", ".", "\" nc on nc.\"", ".", "$", "relation", "->", "getForeignColumn", "(", ")", ".", "\" = c.id \"", ";", "$", "query", ".=", "\"where nc.\"", ".", "$", "relation", "->", "getLocalColumn", "(", ")", ".", "\" = :id\"", ";", "}", "if", "(", "$", "relation", "->", "getCardinality", "(", ")", "==", "Relation", "::", "$", "oneToMany", ")", "{", "$", "query", "=", "\"select \"", ".", "$", "fields", ".", "\" from \"", ".", "$", "mapperRelation", "->", "getTable", "(", ")", ".", "\" c \"", ";", "$", "query", ".=", "\"where c.\"", ".", "$", "relation", "->", "getForeignColumn", "(", ")", ".", "\" = :id\"", ";", "}", "return", "$", "query", ";", "}" ]
Get the query for select the related entitys. @param type $entity @param type $relation Name of the relation.
[ "Get", "the", "query", "for", "select", "the", "related", "entitys", "." ]
ba264dc681a9d803885fd35d10b0e37776f66659
https://github.com/flowcode/ceibo/blob/ba264dc681a9d803885fd35d10b0e37776f66659/src/flowcode/ceibo/builder/QueryBuilder.php#L126-L145
1,741
infotech-ru/yii-document-generator
src/DocumentType/AbstractDocumentType.php
AbstractDocumentType.getData
public function getData($key, $fetcher = self::DEFAULT_FETCHER_NAME) { return $this->getDataFetcher($fetcher)->getData($key); }
php
public function getData($key, $fetcher = self::DEFAULT_FETCHER_NAME) { return $this->getDataFetcher($fetcher)->getData($key); }
[ "public", "function", "getData", "(", "$", "key", ",", "$", "fetcher", "=", "self", "::", "DEFAULT_FETCHER_NAME", ")", "{", "return", "$", "this", "->", "getDataFetcher", "(", "$", "fetcher", ")", "->", "getData", "(", "$", "key", ")", ";", "}" ]
Get real substitution data @param mixed $key Data identifier @return array
[ "Get", "real", "substitution", "data" ]
70e418a84c34930662f2f6a8e12687e2c8492849
https://github.com/infotech-ru/yii-document-generator/blob/70e418a84c34930662f2f6a8e12687e2c8492849/src/DocumentType/AbstractDocumentType.php#L50-L53
1,742
iMoneza/imoneza-php-api
src/iMoneza/Helper.php
Helper.getCurrentIP
public static function getCurrentIP() { $ip = ''; foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'] as $headerKey) { if ($item = getenv($headerKey)) { foreach (array_filter(explode(',', $item), 'trim') as $ipAddress) { if ($ip = filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { break 2; } } } } return (string) $ip; }
php
public static function getCurrentIP() { $ip = ''; foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'] as $headerKey) { if ($item = getenv($headerKey)) { foreach (array_filter(explode(',', $item), 'trim') as $ipAddress) { if ($ip = filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { break 2; } } } } return (string) $ip; }
[ "public", "static", "function", "getCurrentIP", "(", ")", "{", "$", "ip", "=", "''", ";", "foreach", "(", "[", "'HTTP_CLIENT_IP'", ",", "'HTTP_X_FORWARDED_FOR'", ",", "'HTTP_X_FORWARDED'", ",", "'HTTP_X_CLUSTER_CLIENT_IP'", ",", "'HTTP_FORWARDED_FOR'", ",", "'HTTP_FORWARDED'", ",", "'REMOTE_ADDR'", "]", "as", "$", "headerKey", ")", "{", "if", "(", "$", "item", "=", "getenv", "(", "$", "headerKey", ")", ")", "{", "foreach", "(", "array_filter", "(", "explode", "(", "','", ",", "$", "item", ")", ",", "'trim'", ")", "as", "$", "ipAddress", ")", "{", "if", "(", "$", "ip", "=", "filter_var", "(", "$", "ipAddress", ",", "FILTER_VALIDATE_IP", ",", "FILTER_FLAG_NO_PRIV_RANGE", "|", "FILTER_FLAG_NO_RES_RANGE", ")", ")", "{", "break", "2", ";", "}", "}", "}", "}", "return", "(", "string", ")", "$", "ip", ";", "}" ]
Gets the current IP address @return string
[ "Gets", "the", "current", "IP", "address" ]
8347702c88c3cf754d21631a304a2c2d3abac98e
https://github.com/iMoneza/imoneza-php-api/blob/8347702c88c3cf754d21631a304a2c2d3abac98e/src/iMoneza/Helper.php#L20-L35
1,743
helthe/Segmentio
Templating/Renderer.php
Renderer.renderMethod
public function renderMethod(MethodInterface $method) { if (!$method->supports(MethodInterface::BROWSER_PLATFORM)) { throw new \InvalidArgumentException('Renderer only accepts browser methods.'); } return 'window.analytics.' . $method->getName() . '(' . $this->renderArguments($method) . ');'; }
php
public function renderMethod(MethodInterface $method) { if (!$method->supports(MethodInterface::BROWSER_PLATFORM)) { throw new \InvalidArgumentException('Renderer only accepts browser methods.'); } return 'window.analytics.' . $method->getName() . '(' . $this->renderArguments($method) . ');'; }
[ "public", "function", "renderMethod", "(", "MethodInterface", "$", "method", ")", "{", "if", "(", "!", "$", "method", "->", "supports", "(", "MethodInterface", "::", "BROWSER_PLATFORM", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Renderer only accepts browser methods.'", ")", ";", "}", "return", "'window.analytics.'", ".", "$", "method", "->", "getName", "(", ")", ".", "'('", ".", "$", "this", "->", "renderArguments", "(", "$", "method", ")", ".", "');'", ";", "}" ]
Renders the library method. @param MethodInterface $method @return string
[ "Renders", "the", "library", "method", "." ]
40a97cf9780404bf0a48ad4621cc994ca66e9128
https://github.com/helthe/Segmentio/blob/40a97cf9780404bf0a48ad4621cc994ca66e9128/Templating/Renderer.php#L84-L91
1,744
helthe/Segmentio
Templating/Renderer.php
Renderer.renderPage
public function renderPage($name = null,$category = null, array $properties = array()) { return $this->renderMethod(new PageMethod($name, $category, $properties)); }
php
public function renderPage($name = null,$category = null, array $properties = array()) { return $this->renderMethod(new PageMethod($name, $category, $properties)); }
[ "public", "function", "renderPage", "(", "$", "name", "=", "null", ",", "$", "category", "=", "null", ",", "array", "$", "properties", "=", "array", "(", ")", ")", "{", "return", "$", "this", "->", "renderMethod", "(", "new", "PageMethod", "(", "$", "name", ",", "$", "category", ",", "$", "properties", ")", ")", ";", "}" ]
Renders a page method. @param string $name @param string $category @param array $properties @return string
[ "Renders", "a", "page", "method", "." ]
40a97cf9780404bf0a48ad4621cc994ca66e9128
https://github.com/helthe/Segmentio/blob/40a97cf9780404bf0a48ad4621cc994ca66e9128/Templating/Renderer.php#L102-L105
1,745
helthe/Segmentio
Templating/Renderer.php
Renderer.renderQueue
public function renderQueue(Queue $queue) { $render = ''; while ($method = $queue->dequeue(MethodInterface::BROWSER_PLATFORM)) { $render .= $this->renderMethod($method) . "\n"; } return trim($render); }
php
public function renderQueue(Queue $queue) { $render = ''; while ($method = $queue->dequeue(MethodInterface::BROWSER_PLATFORM)) { $render .= $this->renderMethod($method) . "\n"; } return trim($render); }
[ "public", "function", "renderQueue", "(", "Queue", "$", "queue", ")", "{", "$", "render", "=", "''", ";", "while", "(", "$", "method", "=", "$", "queue", "->", "dequeue", "(", "MethodInterface", "::", "BROWSER_PLATFORM", ")", ")", "{", "$", "render", ".=", "$", "this", "->", "renderMethod", "(", "$", "method", ")", ".", "\"\\n\"", ";", "}", "return", "trim", "(", "$", "render", ")", ";", "}" ]
Renders a queue of library methods. @return string
[ "Renders", "a", "queue", "of", "library", "methods", "." ]
40a97cf9780404bf0a48ad4621cc994ca66e9128
https://github.com/helthe/Segmentio/blob/40a97cf9780404bf0a48ad4621cc994ca66e9128/Templating/Renderer.php#L112-L121
1,746
helthe/Segmentio
Templating/Renderer.php
Renderer.renderArgument
private function renderArgument($argument) { if (is_array($argument)) { $argument = json_encode($argument); } elseif (null === $argument) { $argument = 'null'; } elseif (is_string($argument)) { $argument = '"' . $argument . '"'; } return $argument; }
php
private function renderArgument($argument) { if (is_array($argument)) { $argument = json_encode($argument); } elseif (null === $argument) { $argument = 'null'; } elseif (is_string($argument)) { $argument = '"' . $argument . '"'; } return $argument; }
[ "private", "function", "renderArgument", "(", "$", "argument", ")", "{", "if", "(", "is_array", "(", "$", "argument", ")", ")", "{", "$", "argument", "=", "json_encode", "(", "$", "argument", ")", ";", "}", "elseif", "(", "null", "===", "$", "argument", ")", "{", "$", "argument", "=", "'null'", ";", "}", "elseif", "(", "is_string", "(", "$", "argument", ")", ")", "{", "$", "argument", "=", "'\"'", ".", "$", "argument", ".", "'\"'", ";", "}", "return", "$", "argument", ";", "}" ]
Renders a method argument. @param mixed $argument @return string
[ "Renders", "a", "method", "argument", "." ]
40a97cf9780404bf0a48ad4621cc994ca66e9128
https://github.com/helthe/Segmentio/blob/40a97cf9780404bf0a48ad4621cc994ca66e9128/Templating/Renderer.php#L155-L166
1,747
jitesoft/php-math
src/MatrixMath.php
MatrixMath.identity
public static function identity($type = Matrix44::class) : Matrix { $matrix = new $type(); for ($i=0;$i<$type::ROWS;$i++) { for ($j=0;$j<$type::COLUMNS;$j++) { $matrix[$i][$j] = $i === $j ? 1 : 0; } } return $matrix; }
php
public static function identity($type = Matrix44::class) : Matrix { $matrix = new $type(); for ($i=0;$i<$type::ROWS;$i++) { for ($j=0;$j<$type::COLUMNS;$j++) { $matrix[$i][$j] = $i === $j ? 1 : 0; } } return $matrix; }
[ "public", "static", "function", "identity", "(", "$", "type", "=", "Matrix44", "::", "class", ")", ":", "Matrix", "{", "$", "matrix", "=", "new", "$", "type", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "type", "::", "ROWS", ";", "$", "i", "++", ")", "{", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "$", "type", "::", "COLUMNS", ";", "$", "j", "++", ")", "{", "$", "matrix", "[", "$", "i", "]", "[", "$", "j", "]", "=", "$", "i", "===", "$", "j", "?", "1", ":", "0", ";", "}", "}", "return", "$", "matrix", ";", "}" ]
Create an identity matrix of given matrix type. @param string $type defaults to Matrix44 @return Matrix
[ "Create", "an", "identity", "matrix", "of", "given", "matrix", "type", "." ]
1775055e5a14ef30c7df0deeb1fe1ff0775bb581
https://github.com/jitesoft/php-math/blob/1775055e5a14ef30c7df0deeb1fe1ff0775bb581/src/MatrixMath.php#L26-L35
1,748
jitesoft/php-math
src/MatrixMath.php
MatrixMath.mul
public static function mul(Matrix $matrix, $value) : Matrix { if ($value instanceof Matrix) { return self::mulMatrix($matrix, $value); } if (is_numeric($value)) { return self::mulScalar($matrix, $value); } $type = gettype($value); throw new InvalidArgumentException("Invalid type. Can not multiply a matrix with {$type}."); }
php
public static function mul(Matrix $matrix, $value) : Matrix { if ($value instanceof Matrix) { return self::mulMatrix($matrix, $value); } if (is_numeric($value)) { return self::mulScalar($matrix, $value); } $type = gettype($value); throw new InvalidArgumentException("Invalid type. Can not multiply a matrix with {$type}."); }
[ "public", "static", "function", "mul", "(", "Matrix", "$", "matrix", ",", "$", "value", ")", ":", "Matrix", "{", "if", "(", "$", "value", "instanceof", "Matrix", ")", "{", "return", "self", "::", "mulMatrix", "(", "$", "matrix", ",", "$", "value", ")", ";", "}", "if", "(", "is_numeric", "(", "$", "value", ")", ")", "{", "return", "self", "::", "mulScalar", "(", "$", "matrix", ",", "$", "value", ")", ";", "}", "$", "type", "=", "gettype", "(", "$", "value", ")", ";", "throw", "new", "InvalidArgumentException", "(", "\"Invalid type. Can not multiply a matrix with {$type}.\"", ")", ";", "}" ]
Matrix multiplication. Multiplies the Matrix with either a scalar or another matrix. Currently only supports matrix multiplication with same type of matrices. @param Matrix $matrix @param float|Matrix $value @return Matrix @throws Exception
[ "Matrix", "multiplication", "." ]
1775055e5a14ef30c7df0deeb1fe1ff0775bb581
https://github.com/jitesoft/php-math/blob/1775055e5a14ef30c7df0deeb1fe1ff0775bb581/src/MatrixMath.php#L120-L132
1,749
jitesoft/php-math
src/MatrixMath.php
MatrixMath.mulScalar
public static function mulScalar(Matrix $matrix, float $scalar) : Matrix { $type = get_class($matrix); $result = new $type(); for ($i=0;$i<$type::ROWS;$i++) { for ($j=0;$j<$type::COLUMNS;$j++) { $result[$i][$j] = $matrix[$i][$j] * $scalar; } } return $result; }
php
public static function mulScalar(Matrix $matrix, float $scalar) : Matrix { $type = get_class($matrix); $result = new $type(); for ($i=0;$i<$type::ROWS;$i++) { for ($j=0;$j<$type::COLUMNS;$j++) { $result[$i][$j] = $matrix[$i][$j] * $scalar; } } return $result; }
[ "public", "static", "function", "mulScalar", "(", "Matrix", "$", "matrix", ",", "float", "$", "scalar", ")", ":", "Matrix", "{", "$", "type", "=", "get_class", "(", "$", "matrix", ")", ";", "$", "result", "=", "new", "$", "type", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "type", "::", "ROWS", ";", "$", "i", "++", ")", "{", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "$", "type", "::", "COLUMNS", ";", "$", "j", "++", ")", "{", "$", "result", "[", "$", "i", "]", "[", "$", "j", "]", "=", "$", "matrix", "[", "$", "i", "]", "[", "$", "j", "]", "*", "$", "scalar", ";", "}", "}", "return", "$", "result", ";", "}" ]
Matrix scalar multiplication. @param Matrix $matrix @param float $scalar @return Matrix
[ "Matrix", "scalar", "multiplication", "." ]
1775055e5a14ef30c7df0deeb1fe1ff0775bb581
https://github.com/jitesoft/php-math/blob/1775055e5a14ef30c7df0deeb1fe1ff0775bb581/src/MatrixMath.php#L177-L188
1,750
jitesoft/php-math
src/MatrixMath.php
MatrixMath.add
public static function add(Matrix $matrix, Matrix $matrix2) : Matrix { $type = get_class($matrix); $type2 = get_class($matrix2); if ($type !== $type2) { throw new InvalidArgumentException("Can only add matrices of same size."); } $result = new $type(); for ($i=0;$i<$type::ROWS;$i++) { for ($j=0;$j<$type::COLUMNS;$j++) { $result[$i][$j] = $matrix[$i][$j] + $matrix2[$i][$j]; } } return $result; }
php
public static function add(Matrix $matrix, Matrix $matrix2) : Matrix { $type = get_class($matrix); $type2 = get_class($matrix2); if ($type !== $type2) { throw new InvalidArgumentException("Can only add matrices of same size."); } $result = new $type(); for ($i=0;$i<$type::ROWS;$i++) { for ($j=0;$j<$type::COLUMNS;$j++) { $result[$i][$j] = $matrix[$i][$j] + $matrix2[$i][$j]; } } return $result; }
[ "public", "static", "function", "add", "(", "Matrix", "$", "matrix", ",", "Matrix", "$", "matrix2", ")", ":", "Matrix", "{", "$", "type", "=", "get_class", "(", "$", "matrix", ")", ";", "$", "type2", "=", "get_class", "(", "$", "matrix2", ")", ";", "if", "(", "$", "type", "!==", "$", "type2", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Can only add matrices of same size.\"", ")", ";", "}", "$", "result", "=", "new", "$", "type", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "type", "::", "ROWS", ";", "$", "i", "++", ")", "{", "for", "(", "$", "j", "=", "0", ";", "$", "j", "<", "$", "type", "::", "COLUMNS", ";", "$", "j", "++", ")", "{", "$", "result", "[", "$", "i", "]", "[", "$", "j", "]", "=", "$", "matrix", "[", "$", "i", "]", "[", "$", "j", "]", "+", "$", "matrix2", "[", "$", "i", "]", "[", "$", "j", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Matrix Matrix addition. @param Matrix $matrix @param Matrix $matrix2 @return Matrix @throws Exception
[ "Matrix", "Matrix", "addition", "." ]
1775055e5a14ef30c7df0deeb1fe1ff0775bb581
https://github.com/jitesoft/php-math/blob/1775055e5a14ef30c7df0deeb1fe1ff0775bb581/src/MatrixMath.php#L199-L216
1,751
jitesoft/php-math
src/MatrixMath.php
MatrixMath.makeRotationX
public static function makeRotationX(float $angle, string $type = Math::DEGREES) : Matrix33 { if ($type === Math::DEGREES) { $angle = Math::degToRad($angle); } return new Matrix33( 1, 0, 0, 0, cos($angle), - sin($angle), 0, sin($angle), cos($angle) ); }
php
public static function makeRotationX(float $angle, string $type = Math::DEGREES) : Matrix33 { if ($type === Math::DEGREES) { $angle = Math::degToRad($angle); } return new Matrix33( 1, 0, 0, 0, cos($angle), - sin($angle), 0, sin($angle), cos($angle) ); }
[ "public", "static", "function", "makeRotationX", "(", "float", "$", "angle", ",", "string", "$", "type", "=", "Math", "::", "DEGREES", ")", ":", "Matrix33", "{", "if", "(", "$", "type", "===", "Math", "::", "DEGREES", ")", "{", "$", "angle", "=", "Math", "::", "degToRad", "(", "$", "angle", ")", ";", "}", "return", "new", "Matrix33", "(", "1", ",", "0", ",", "0", ",", "0", ",", "cos", "(", "$", "angle", ")", ",", "-", "sin", "(", "$", "angle", ")", ",", "0", ",", "sin", "(", "$", "angle", ")", ",", "cos", "(", "$", "angle", ")", ")", ";", "}" ]
Create a rotation matrix with given X angle rotation. @param float $angle @param string $type If degrees or radians, see Math constants. @return Matrix33
[ "Create", "a", "rotation", "matrix", "with", "given", "X", "angle", "rotation", "." ]
1775055e5a14ef30c7df0deeb1fe1ff0775bb581
https://github.com/jitesoft/php-math/blob/1775055e5a14ef30c7df0deeb1fe1ff0775bb581/src/MatrixMath.php#L253-L263
1,752
samurai-fw/samurai
src/Samurai/Component/Core/Namespacer.php
Namespacer.pickAppDir
public static function pickAppDir($path) { // when relational path. if ($path[0] !== '/') return $path; $root = null; foreach (self::$namespaces as $p => $ns) { if (strpos($path, $p) === 0) { if ($root === null || strlen($root) < strlen($p)) $root = $p; } } return $root ? $root : $path; }
php
public static function pickAppDir($path) { // when relational path. if ($path[0] !== '/') return $path; $root = null; foreach (self::$namespaces as $p => $ns) { if (strpos($path, $p) === 0) { if ($root === null || strlen($root) < strlen($p)) $root = $p; } } return $root ? $root : $path; }
[ "public", "static", "function", "pickAppDir", "(", "$", "path", ")", "{", "// when relational path.", "if", "(", "$", "path", "[", "0", "]", "!==", "'/'", ")", "return", "$", "path", ";", "$", "root", "=", "null", ";", "foreach", "(", "self", "::", "$", "namespaces", "as", "$", "p", "=>", "$", "ns", ")", "{", "if", "(", "strpos", "(", "$", "path", ",", "$", "p", ")", "===", "0", ")", "{", "if", "(", "$", "root", "===", "null", "||", "strlen", "(", "$", "root", ")", "<", "strlen", "(", "$", "p", ")", ")", "$", "root", "=", "$", "p", ";", "}", "}", "return", "$", "root", "?", "$", "root", ":", "$", "path", ";", "}" ]
pick the app dir from some path. @access public @param string $path @return string
[ "pick", "the", "app", "dir", "from", "some", "path", "." ]
7ca3847b13f86e2847a17ab5e8e4e20893021d5a
https://github.com/samurai-fw/samurai/blob/7ca3847b13f86e2847a17ab5e8e4e20893021d5a/src/Samurai/Component/Core/Namespacer.php#L85-L98
1,753
samurai-fw/samurai
src/Samurai/Component/Core/Namespacer.php
Namespacer.pickRootDir
public static function pickRootDir($path) { // when relational path. if ($path[0] !== '/') return $path; $f = function($names, $count) { for ($i = 0; $i < $count; $i++) { array_pop($names); } return $names; }; $root = null; foreach (self::$namespaces as $p => $ns) { $d = join(DS, $f(explode(DS, $p), count(explode('\\', $ns)))); if (strpos($path, $d) === 0) { if ($root === null || strlen($root) < strlen($d)) $root = $d; } } return $root ? $root : $path; }
php
public static function pickRootDir($path) { // when relational path. if ($path[0] !== '/') return $path; $f = function($names, $count) { for ($i = 0; $i < $count; $i++) { array_pop($names); } return $names; }; $root = null; foreach (self::$namespaces as $p => $ns) { $d = join(DS, $f(explode(DS, $p), count(explode('\\', $ns)))); if (strpos($path, $d) === 0) { if ($root === null || strlen($root) < strlen($d)) $root = $d; } } return $root ? $root : $path; }
[ "public", "static", "function", "pickRootDir", "(", "$", "path", ")", "{", "// when relational path.", "if", "(", "$", "path", "[", "0", "]", "!==", "'/'", ")", "return", "$", "path", ";", "$", "f", "=", "function", "(", "$", "names", ",", "$", "count", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "$", "i", "++", ")", "{", "array_pop", "(", "$", "names", ")", ";", "}", "return", "$", "names", ";", "}", ";", "$", "root", "=", "null", ";", "foreach", "(", "self", "::", "$", "namespaces", "as", "$", "p", "=>", "$", "ns", ")", "{", "$", "d", "=", "join", "(", "DS", ",", "$", "f", "(", "explode", "(", "DS", ",", "$", "p", ")", ",", "count", "(", "explode", "(", "'\\\\'", ",", "$", "ns", ")", ")", ")", ")", ";", "if", "(", "strpos", "(", "$", "path", ",", "$", "d", ")", "===", "0", ")", "{", "if", "(", "$", "root", "===", "null", "||", "strlen", "(", "$", "root", ")", "<", "strlen", "(", "$", "d", ")", ")", "$", "root", "=", "$", "d", ";", "}", "}", "return", "$", "root", "?", "$", "root", ":", "$", "path", ";", "}" ]
pick the root dir from some path. @access public @param string $path @return string
[ "pick", "the", "root", "dir", "from", "some", "path", "." ]
7ca3847b13f86e2847a17ab5e8e4e20893021d5a
https://github.com/samurai-fw/samurai/blob/7ca3847b13f86e2847a17ab5e8e4e20893021d5a/src/Samurai/Component/Core/Namespacer.php#L108-L129
1,754
samurai-fw/samurai
src/Samurai/Component/Core/Namespacer.php
Namespacer.getNamespaceByPath
public static function getNamespaceByPath($path, $is_dir = true) { // when relational path. if ($path[0] !== '/') return null; $root_ns = ''; $filepath = $path; foreach (self::$namespaces as $p => $ns) { if (strpos($path, $p) !== false) { $root_ns = $ns; $filepath = substr($path, strlen($p) + 1); break; } } $ns = $filepath ? explode(DS, $filepath) : []; if (! $is_dir) array_pop($ns); array_unshift($ns, $root_ns); return join('\\', $ns); }
php
public static function getNamespaceByPath($path, $is_dir = true) { // when relational path. if ($path[0] !== '/') return null; $root_ns = ''; $filepath = $path; foreach (self::$namespaces as $p => $ns) { if (strpos($path, $p) !== false) { $root_ns = $ns; $filepath = substr($path, strlen($p) + 1); break; } } $ns = $filepath ? explode(DS, $filepath) : []; if (! $is_dir) array_pop($ns); array_unshift($ns, $root_ns); return join('\\', $ns); }
[ "public", "static", "function", "getNamespaceByPath", "(", "$", "path", ",", "$", "is_dir", "=", "true", ")", "{", "// when relational path.", "if", "(", "$", "path", "[", "0", "]", "!==", "'/'", ")", "return", "null", ";", "$", "root_ns", "=", "''", ";", "$", "filepath", "=", "$", "path", ";", "foreach", "(", "self", "::", "$", "namespaces", "as", "$", "p", "=>", "$", "ns", ")", "{", "if", "(", "strpos", "(", "$", "path", ",", "$", "p", ")", "!==", "false", ")", "{", "$", "root_ns", "=", "$", "ns", ";", "$", "filepath", "=", "substr", "(", "$", "path", ",", "strlen", "(", "$", "p", ")", "+", "1", ")", ";", "break", ";", "}", "}", "$", "ns", "=", "$", "filepath", "?", "explode", "(", "DS", ",", "$", "filepath", ")", ":", "[", "]", ";", "if", "(", "!", "$", "is_dir", ")", "array_pop", "(", "$", "ns", ")", ";", "array_unshift", "(", "$", "ns", ",", "$", "root_ns", ")", ";", "return", "join", "(", "'\\\\'", ",", "$", "ns", ")", ";", "}" ]
get namespace by filepath @param string $path @return string
[ "get", "namespace", "by", "filepath" ]
7ca3847b13f86e2847a17ab5e8e4e20893021d5a
https://github.com/samurai-fw/samurai/blob/7ca3847b13f86e2847a17ab5e8e4e20893021d5a/src/Samurai/Component/Core/Namespacer.php#L138-L160
1,755
hametuha/sekisyo
app/Hametuha/Sekisyo/GateKeeper.php
GateKeeper.rest_api_init
public function rest_api_init( $server ) { register_rest_route( 'sekisyo/v1', 'license/(?P<guid>[^/]+)/?', [ [ 'methods' => 'POST', 'callback' => [ $this, 'handle_rest_post' ], 'args' => [ 'guid' => [ 'required' => true, ], 'license' => [ 'required' => true, ], ], 'permission_callback' => function ( $request ) { return current_user_can( 'activate_plugins' ); }, ], [ 'methods' => 'DELETE', 'callback' => [ $this, 'handle_rest_delete' ], 'args' => [ 'guid' => [ 'required' => true, ], 'license' => [ 'required' => true, ], ], 'permission_callback' => function ( $request ) { return current_user_can( 'activate_plugins' ); }, ], ] ); }
php
public function rest_api_init( $server ) { register_rest_route( 'sekisyo/v1', 'license/(?P<guid>[^/]+)/?', [ [ 'methods' => 'POST', 'callback' => [ $this, 'handle_rest_post' ], 'args' => [ 'guid' => [ 'required' => true, ], 'license' => [ 'required' => true, ], ], 'permission_callback' => function ( $request ) { return current_user_can( 'activate_plugins' ); }, ], [ 'methods' => 'DELETE', 'callback' => [ $this, 'handle_rest_delete' ], 'args' => [ 'guid' => [ 'required' => true, ], 'license' => [ 'required' => true, ], ], 'permission_callback' => function ( $request ) { return current_user_can( 'activate_plugins' ); }, ], ] ); }
[ "public", "function", "rest_api_init", "(", "$", "server", ")", "{", "register_rest_route", "(", "'sekisyo/v1'", ",", "'license/(?P<guid>[^/]+)/?'", ",", "[", "[", "'methods'", "=>", "'POST'", ",", "'callback'", "=>", "[", "$", "this", ",", "'handle_rest_post'", "]", ",", "'args'", "=>", "[", "'guid'", "=>", "[", "'required'", "=>", "true", ",", "]", ",", "'license'", "=>", "[", "'required'", "=>", "true", ",", "]", ",", "]", ",", "'permission_callback'", "=>", "function", "(", "$", "request", ")", "{", "return", "current_user_can", "(", "'activate_plugins'", ")", ";", "}", ",", "]", ",", "[", "'methods'", "=>", "'DELETE'", ",", "'callback'", "=>", "[", "$", "this", ",", "'handle_rest_delete'", "]", ",", "'args'", "=>", "[", "'guid'", "=>", "[", "'required'", "=>", "true", ",", "]", ",", "'license'", "=>", "[", "'required'", "=>", "true", ",", "]", ",", "]", ",", "'permission_callback'", "=>", "function", "(", "$", "request", ")", "{", "return", "current_user_can", "(", "'activate_plugins'", ")", ";", "}", ",", "]", ",", "]", ")", ";", "}" ]
Handle API request @param \WP_REST_Server $server
[ "Handle", "API", "request" ]
94db776153afffff50b876ef1181e665e699c9a7
https://github.com/hametuha/sekisyo/blob/94db776153afffff50b876ef1181e665e699c9a7/app/Hametuha/Sekisyo/GateKeeper.php#L108-L141
1,756
hametuha/sekisyo
app/Hametuha/Sekisyo/GateKeeper.php
GateKeeper.check_validity
public function check_validity() { foreach ( $this->plugins as $plugin ) { /** @var Plugin $plugin */ if ( $plugin->valid ) { // This is valid plugin, so we need check license health. $plugin->update_license( $plugin->license, true ); if ( ! $plugin->fail_limit ) { // If plugin has no fail limit, skip it. continue; } /** * sekisyo_update_error * * @package sekisyo * @since 1.0.0 * * @param string $guid * @param int $failed * @param Plugin $plugin */ do_action( 'sekisyo_update_error', $plugin->guid, $plugin->failed, $plugin ); if ( $plugin->failed > $plugin->fail_limit ) { $plugin->inactivate(); } } } }
php
public function check_validity() { foreach ( $this->plugins as $plugin ) { /** @var Plugin $plugin */ if ( $plugin->valid ) { // This is valid plugin, so we need check license health. $plugin->update_license( $plugin->license, true ); if ( ! $plugin->fail_limit ) { // If plugin has no fail limit, skip it. continue; } /** * sekisyo_update_error * * @package sekisyo * @since 1.0.0 * * @param string $guid * @param int $failed * @param Plugin $plugin */ do_action( 'sekisyo_update_error', $plugin->guid, $plugin->failed, $plugin ); if ( $plugin->failed > $plugin->fail_limit ) { $plugin->inactivate(); } } } }
[ "public", "function", "check_validity", "(", ")", "{", "foreach", "(", "$", "this", "->", "plugins", "as", "$", "plugin", ")", "{", "/** @var Plugin $plugin */", "if", "(", "$", "plugin", "->", "valid", ")", "{", "// This is valid plugin, so we need check license health.", "$", "plugin", "->", "update_license", "(", "$", "plugin", "->", "license", ",", "true", ")", ";", "if", "(", "!", "$", "plugin", "->", "fail_limit", ")", "{", "// If plugin has no fail limit, skip it.", "continue", ";", "}", "/**\n\t\t\t\t * sekisyo_update_error\n\t\t\t\t *\n\t\t\t\t * @package sekisyo\n\t\t\t\t * @since 1.0.0\n\t\t\t\t *\n\t\t\t\t * @param string $guid\n\t\t\t\t * @param int $failed\n\t\t\t\t * @param Plugin $plugin\n\t\t\t\t */", "do_action", "(", "'sekisyo_update_error'", ",", "$", "plugin", "->", "guid", ",", "$", "plugin", "->", "failed", ",", "$", "plugin", ")", ";", "if", "(", "$", "plugin", "->", "failed", ">", "$", "plugin", "->", "fail_limit", ")", "{", "$", "plugin", "->", "inactivate", "(", ")", ";", "}", "}", "}", "}" ]
Check validity with cron job
[ "Check", "validity", "with", "cron", "job" ]
94db776153afffff50b876ef1181e665e699c9a7
https://github.com/hametuha/sekisyo/blob/94db776153afffff50b876ef1181e665e699c9a7/app/Hametuha/Sekisyo/GateKeeper.php#L197-L223
1,757
hametuha/sekisyo
app/Hametuha/Sekisyo/GateKeeper.php
GateKeeper.get
public static function get( $guid ) { $instance = self::get_instance(); if ( isset( $instance->plugins[ $guid ] ) ) { return $instance->plugins[ $guid ]; } else { new \WP_Error( sprintf( __( 'Plugin %s is not registered.', 'sekisyo' ), $guid ), 404, [ 'status' => 404, ] ); } }
php
public static function get( $guid ) { $instance = self::get_instance(); if ( isset( $instance->plugins[ $guid ] ) ) { return $instance->plugins[ $guid ]; } else { new \WP_Error( sprintf( __( 'Plugin %s is not registered.', 'sekisyo' ), $guid ), 404, [ 'status' => 404, ] ); } }
[ "public", "static", "function", "get", "(", "$", "guid", ")", "{", "$", "instance", "=", "self", "::", "get_instance", "(", ")", ";", "if", "(", "isset", "(", "$", "instance", "->", "plugins", "[", "$", "guid", "]", ")", ")", "{", "return", "$", "instance", "->", "plugins", "[", "$", "guid", "]", ";", "}", "else", "{", "new", "\\", "WP_Error", "(", "sprintf", "(", "__", "(", "'Plugin %s is not registered.'", ",", "'sekisyo'", ")", ",", "$", "guid", ")", ",", "404", ",", "[", "'status'", "=>", "404", ",", "]", ")", ";", "}", "}" ]
Get plugin instance. @param string $guid @return Plugin|\WP_Error
[ "Get", "plugin", "instance", "." ]
94db776153afffff50b876ef1181e665e699c9a7
https://github.com/hametuha/sekisyo/blob/94db776153afffff50b876ef1181e665e699c9a7/app/Hametuha/Sekisyo/GateKeeper.php#L281-L290
1,758
hametuha/sekisyo
app/Hametuha/Sekisyo/GateKeeper.php
GateKeeper.is_valid
public static function is_valid( $guids = [] ) { $instance = self::get_instance(); foreach ( $guids as $guid ) { if ( isset( $instance->plugins[ $guid ] ) && $instance->plugins[ $guid ]->valid ) { return true; } } return false; }
php
public static function is_valid( $guids = [] ) { $instance = self::get_instance(); foreach ( $guids as $guid ) { if ( isset( $instance->plugins[ $guid ] ) && $instance->plugins[ $guid ]->valid ) { return true; } } return false; }
[ "public", "static", "function", "is_valid", "(", "$", "guids", "=", "[", "]", ")", "{", "$", "instance", "=", "self", "::", "get_instance", "(", ")", ";", "foreach", "(", "$", "guids", "as", "$", "guid", ")", "{", "if", "(", "isset", "(", "$", "instance", "->", "plugins", "[", "$", "guid", "]", ")", "&&", "$", "instance", "->", "plugins", "[", "$", "guid", "]", "->", "valid", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Detect if this plugin is valid @param array $guids @return bool
[ "Detect", "if", "this", "plugin", "is", "valid" ]
94db776153afffff50b876ef1181e665e699c9a7
https://github.com/hametuha/sekisyo/blob/94db776153afffff50b876ef1181e665e699c9a7/app/Hametuha/Sekisyo/GateKeeper.php#L299-L308
1,759
FlexPress/component-metabox
src/FlexPress/Components/MetaBox/Helper.php
Helper.addMetaBoxes
public function addMetaBoxes() { $this->metaBoxes->rewind(); while ($this->metaBoxes->valid()) { $metaBox = $this->metaBoxes->current(); foreach ($metaBox->getSupportedPostTypes() as $postType) { add_meta_box( $metaBox->getID(), $metaBox->getTitle(), array( $metaBox, 'getCallback' ), $postType, $metaBox->getContext(), $metaBox->getPriority(), $metaBox->getCallbackArgs() ); add_action('save_post', array($metaBox, 'savePostCallback')); } $this->metaBoxes->next(); } }
php
public function addMetaBoxes() { $this->metaBoxes->rewind(); while ($this->metaBoxes->valid()) { $metaBox = $this->metaBoxes->current(); foreach ($metaBox->getSupportedPostTypes() as $postType) { add_meta_box( $metaBox->getID(), $metaBox->getTitle(), array( $metaBox, 'getCallback' ), $postType, $metaBox->getContext(), $metaBox->getPriority(), $metaBox->getCallbackArgs() ); add_action('save_post', array($metaBox, 'savePostCallback')); } $this->metaBoxes->next(); } }
[ "public", "function", "addMetaBoxes", "(", ")", "{", "$", "this", "->", "metaBoxes", "->", "rewind", "(", ")", ";", "while", "(", "$", "this", "->", "metaBoxes", "->", "valid", "(", ")", ")", "{", "$", "metaBox", "=", "$", "this", "->", "metaBoxes", "->", "current", "(", ")", ";", "foreach", "(", "$", "metaBox", "->", "getSupportedPostTypes", "(", ")", "as", "$", "postType", ")", "{", "add_meta_box", "(", "$", "metaBox", "->", "getID", "(", ")", ",", "$", "metaBox", "->", "getTitle", "(", ")", ",", "array", "(", "$", "metaBox", ",", "'getCallback'", ")", ",", "$", "postType", ",", "$", "metaBox", "->", "getContext", "(", ")", ",", "$", "metaBox", "->", "getPriority", "(", ")", ",", "$", "metaBox", "->", "getCallbackArgs", "(", ")", ")", ";", "add_action", "(", "'save_post'", ",", "array", "(", "$", "metaBox", ",", "'savePostCallback'", ")", ")", ";", "}", "$", "this", "->", "metaBoxes", "->", "next", "(", ")", ";", "}", "}" ]
Registers all the meta boxes added @author Tim Perry
[ "Registers", "all", "the", "meta", "boxes", "added" ]
1d0b928aad001295ac17a539b24c3e97ab8d34c7
https://github.com/FlexPress/component-metabox/blob/1d0b928aad001295ac17a539b24c3e97ab8d34c7/src/FlexPress/Components/MetaBox/Helper.php#L78-L109
1,760
amercier/rectangular-mozaic
src/RandomFiller.php
RandomFiller.set
public static function set(Grid $grid, Tile $tile) { // Boundaries of the grid within which the tile would fit $rows = $grid->rows - $tile->height + 1; $columns = $grid->columns - $tile->width + 1; // Start at a random position $row = rand(0, $rows - 1); $column = rand(0, $columns - 1); // Record the initial position to prevent infinite loop $initialRow = $row; $initialColumn = $column; // Iterate over grid until an empty spot is found while (!$grid->isEmptyForTile($row, $column, $tile)) { $column = ($column + 1) % $columns; if ($column === 0) { $row = ($row + 1) % $rows; } if ($row === $initialRow && $column === $initialColumn) { throw new InvalidArgumentException("No empty slot for {$tile} tile in grid: {$grid}"); } } $grid->set($row, $column, $tile); return [$row, $column]; }
php
public static function set(Grid $grid, Tile $tile) { // Boundaries of the grid within which the tile would fit $rows = $grid->rows - $tile->height + 1; $columns = $grid->columns - $tile->width + 1; // Start at a random position $row = rand(0, $rows - 1); $column = rand(0, $columns - 1); // Record the initial position to prevent infinite loop $initialRow = $row; $initialColumn = $column; // Iterate over grid until an empty spot is found while (!$grid->isEmptyForTile($row, $column, $tile)) { $column = ($column + 1) % $columns; if ($column === 0) { $row = ($row + 1) % $rows; } if ($row === $initialRow && $column === $initialColumn) { throw new InvalidArgumentException("No empty slot for {$tile} tile in grid: {$grid}"); } } $grid->set($row, $column, $tile); return [$row, $column]; }
[ "public", "static", "function", "set", "(", "Grid", "$", "grid", ",", "Tile", "$", "tile", ")", "{", "// Boundaries of the grid within which the tile would fit", "$", "rows", "=", "$", "grid", "->", "rows", "-", "$", "tile", "->", "height", "+", "1", ";", "$", "columns", "=", "$", "grid", "->", "columns", "-", "$", "tile", "->", "width", "+", "1", ";", "// Start at a random position", "$", "row", "=", "rand", "(", "0", ",", "$", "rows", "-", "1", ")", ";", "$", "column", "=", "rand", "(", "0", ",", "$", "columns", "-", "1", ")", ";", "// Record the initial position to prevent infinite loop", "$", "initialRow", "=", "$", "row", ";", "$", "initialColumn", "=", "$", "column", ";", "// Iterate over grid until an empty spot is found", "while", "(", "!", "$", "grid", "->", "isEmptyForTile", "(", "$", "row", ",", "$", "column", ",", "$", "tile", ")", ")", "{", "$", "column", "=", "(", "$", "column", "+", "1", ")", "%", "$", "columns", ";", "if", "(", "$", "column", "===", "0", ")", "{", "$", "row", "=", "(", "$", "row", "+", "1", ")", "%", "$", "rows", ";", "}", "if", "(", "$", "row", "===", "$", "initialRow", "&&", "$", "column", "===", "$", "initialColumn", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"No empty slot for {$tile} tile in grid: {$grid}\"", ")", ";", "}", "}", "$", "grid", "->", "set", "(", "$", "row", ",", "$", "column", ",", "$", "tile", ")", ";", "return", "[", "$", "row", ",", "$", "column", "]", ";", "}" ]
Set a tile randomly within a grid. @param Grid $grid Grid to fill the tile in. @param Tile $tile Tile to set. @return int[] Row and column where the tile was set. @throws InvalidArgumentException If there is no spot available for the given tile in the grid.
[ "Set", "a", "tile", "randomly", "within", "a", "grid", "." ]
d026a82c1bc73979308235a7a440665e92ee8525
https://github.com/amercier/rectangular-mozaic/blob/d026a82c1bc73979308235a7a440665e92ee8525/src/RandomFiller.php#L21-L48
1,761
amercier/rectangular-mozaic
src/RandomFiller.php
RandomFiller.tryToFill
public static function tryToFill(Grid $grid, Distribution $distribution) { $smallTiles = $distribution->small; $tallTiles = $distribution->tall; $wideTiles = $distribution->wide; for ($i = 0; $i < $distribution->getTiles(); $i++) { // Fill small tiles at the end if ($wideTiles === 0 && $tallTiles === 0) { static::set($grid, Tile::SMALL()); $smallTiles -= 1; // Fill tall tiles if more or equal than wide ones } elseif ($tallTiles >= $wideTiles) { static::set($grid, Tile::TALL()); $tallTiles -= 1; // Fill wide tiles if more than tall ones } else { static::set($grid, Tile::WIDE()); $wideTiles -= 1; } } }
php
public static function tryToFill(Grid $grid, Distribution $distribution) { $smallTiles = $distribution->small; $tallTiles = $distribution->tall; $wideTiles = $distribution->wide; for ($i = 0; $i < $distribution->getTiles(); $i++) { // Fill small tiles at the end if ($wideTiles === 0 && $tallTiles === 0) { static::set($grid, Tile::SMALL()); $smallTiles -= 1; // Fill tall tiles if more or equal than wide ones } elseif ($tallTiles >= $wideTiles) { static::set($grid, Tile::TALL()); $tallTiles -= 1; // Fill wide tiles if more than tall ones } else { static::set($grid, Tile::WIDE()); $wideTiles -= 1; } } }
[ "public", "static", "function", "tryToFill", "(", "Grid", "$", "grid", ",", "Distribution", "$", "distribution", ")", "{", "$", "smallTiles", "=", "$", "distribution", "->", "small", ";", "$", "tallTiles", "=", "$", "distribution", "->", "tall", ";", "$", "wideTiles", "=", "$", "distribution", "->", "wide", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "distribution", "->", "getTiles", "(", ")", ";", "$", "i", "++", ")", "{", "// Fill small tiles at the end", "if", "(", "$", "wideTiles", "===", "0", "&&", "$", "tallTiles", "===", "0", ")", "{", "static", "::", "set", "(", "$", "grid", ",", "Tile", "::", "SMALL", "(", ")", ")", ";", "$", "smallTiles", "-=", "1", ";", "// Fill tall tiles if more or equal than wide ones", "}", "elseif", "(", "$", "tallTiles", ">=", "$", "wideTiles", ")", "{", "static", "::", "set", "(", "$", "grid", ",", "Tile", "::", "TALL", "(", ")", ")", ";", "$", "tallTiles", "-=", "1", ";", "// Fill wide tiles if more than tall ones", "}", "else", "{", "static", "::", "set", "(", "$", "grid", ",", "Tile", "::", "WIDE", "(", ")", ")", ";", "$", "wideTiles", "-=", "1", ";", "}", "}", "}" ]
Fill a tiles distribution randomly within a grid. @param Grid $grid Grid to fill. @param Distribution $distribution Distribution to set. @return void @throws InvalidArgumentException If there is no spot available for the given tile in the grid.
[ "Fill", "a", "tiles", "distribution", "randomly", "within", "a", "grid", "." ]
d026a82c1bc73979308235a7a440665e92ee8525
https://github.com/amercier/rectangular-mozaic/blob/d026a82c1bc73979308235a7a440665e92ee8525/src/RandomFiller.php#L58-L79
1,762
amercier/rectangular-mozaic
src/RandomFiller.php
RandomFiller.fill
public static function fill(Grid $grid, Distribution $distribution, int $maxRetries) { Assert::assertPositiveInteger($maxRetries, 'maxRetries'); if ($distribution->getCells() !== ($cells = $grid->rows * $grid->columns)) { throw new InvalidArgumentException( "Cannot fill distribution {$distribution} ({$distribution->getCells()} cells)" . " in a {$grid->rows}x{$grid->columns} grid ({$cells} cells)" ); } if ($grid->rows < 2 && $distribution->tall > 0) { throw new InvalidArgumentException( "Cannot fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid: not enough rows." ); } if ($grid->columns < 2 && $distribution->wide > 0) { throw new InvalidArgumentException( "Cannot fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid: not enough columns." ); } for ($remainingTries = $maxRetries; $remainingTries > 0; $remainingTries -= 1) { try { return static::tryToFill($grid, $distribution); } catch (InvalidArgumentException $e) { $grid->empty(); } } throw new RuntimeException( "Could not fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid" . " after {$maxRetries} tries." ); }
php
public static function fill(Grid $grid, Distribution $distribution, int $maxRetries) { Assert::assertPositiveInteger($maxRetries, 'maxRetries'); if ($distribution->getCells() !== ($cells = $grid->rows * $grid->columns)) { throw new InvalidArgumentException( "Cannot fill distribution {$distribution} ({$distribution->getCells()} cells)" . " in a {$grid->rows}x{$grid->columns} grid ({$cells} cells)" ); } if ($grid->rows < 2 && $distribution->tall > 0) { throw new InvalidArgumentException( "Cannot fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid: not enough rows." ); } if ($grid->columns < 2 && $distribution->wide > 0) { throw new InvalidArgumentException( "Cannot fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid: not enough columns." ); } for ($remainingTries = $maxRetries; $remainingTries > 0; $remainingTries -= 1) { try { return static::tryToFill($grid, $distribution); } catch (InvalidArgumentException $e) { $grid->empty(); } } throw new RuntimeException( "Could not fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid" . " after {$maxRetries} tries." ); }
[ "public", "static", "function", "fill", "(", "Grid", "$", "grid", ",", "Distribution", "$", "distribution", ",", "int", "$", "maxRetries", ")", "{", "Assert", "::", "assertPositiveInteger", "(", "$", "maxRetries", ",", "'maxRetries'", ")", ";", "if", "(", "$", "distribution", "->", "getCells", "(", ")", "!==", "(", "$", "cells", "=", "$", "grid", "->", "rows", "*", "$", "grid", "->", "columns", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Cannot fill distribution {$distribution} ({$distribution->getCells()} cells)\"", ".", "\" in a {$grid->rows}x{$grid->columns} grid ({$cells} cells)\"", ")", ";", "}", "if", "(", "$", "grid", "->", "rows", "<", "2", "&&", "$", "distribution", "->", "tall", ">", "0", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Cannot fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid: not enough rows.\"", ")", ";", "}", "if", "(", "$", "grid", "->", "columns", "<", "2", "&&", "$", "distribution", "->", "wide", ">", "0", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Cannot fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid: not enough columns.\"", ")", ";", "}", "for", "(", "$", "remainingTries", "=", "$", "maxRetries", ";", "$", "remainingTries", ">", "0", ";", "$", "remainingTries", "-=", "1", ")", "{", "try", "{", "return", "static", "::", "tryToFill", "(", "$", "grid", ",", "$", "distribution", ")", ";", "}", "catch", "(", "InvalidArgumentException", "$", "e", ")", "{", "$", "grid", "->", "empty", "(", ")", ";", "}", "}", "throw", "new", "RuntimeException", "(", "\"Could not fill distribution {$distribution} in a {$grid->rows}x{$grid->columns} grid\"", ".", "\" after {$maxRetries} tries.\"", ")", ";", "}" ]
Try to fill a tiles distribution randomly within a grid. @param Grid $grid Grid to fill. @param Distribution $distribution Distribution to set. @param int $maxRetries Maximum number of tries. @return void @throws Exception If the grid could not be filled after $maxRetries retries.
[ "Try", "to", "fill", "a", "tiles", "distribution", "randomly", "within", "a", "grid", "." ]
d026a82c1bc73979308235a7a440665e92ee8525
https://github.com/amercier/rectangular-mozaic/blob/d026a82c1bc73979308235a7a440665e92ee8525/src/RandomFiller.php#L90-L124
1,763
Label305/Auja-PHP
src/Label305/Auja/Menu/Menu.php
Menu.addMenuItem
public function addMenuItem(MenuItem $menuItem, $position = -1) { if (!is_int($position)) { throw new InvalidArgumentException('position should be of type int.'); } if ($position < 0) { $position = count($this->menuItems); } $menuItem->setOrder($position); Utils::array_insert($this->menuItems, $menuItem, $position); return $this; }
php
public function addMenuItem(MenuItem $menuItem, $position = -1) { if (!is_int($position)) { throw new InvalidArgumentException('position should be of type int.'); } if ($position < 0) { $position = count($this->menuItems); } $menuItem->setOrder($position); Utils::array_insert($this->menuItems, $menuItem, $position); return $this; }
[ "public", "function", "addMenuItem", "(", "MenuItem", "$", "menuItem", ",", "$", "position", "=", "-", "1", ")", "{", "if", "(", "!", "is_int", "(", "$", "position", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'position should be of type int.'", ")", ";", "}", "if", "(", "$", "position", "<", "0", ")", "{", "$", "position", "=", "count", "(", "$", "this", "->", "menuItems", ")", ";", "}", "$", "menuItem", "->", "setOrder", "(", "$", "position", ")", ";", "Utils", "::", "array_insert", "(", "$", "this", "->", "menuItems", ",", "$", "menuItem", ",", "$", "position", ")", ";", "return", "$", "this", ";", "}" ]
Adds a MenuItem to this Menu. @param MenuItem $menuItem The MenuItem to add. @param int $position The position in the menu the MenuItem should have. If not set, it is appended to the end. @return $this
[ "Adds", "a", "MenuItem", "to", "this", "Menu", "." ]
64712af949c4b80e6ca19ed1936e6b37f8965a4c
https://github.com/Label305/Auja-PHP/blob/64712af949c4b80e6ca19ed1936e6b37f8965a4c/src/Label305/Auja/Menu/Menu.php#L60-L74
1,764
neemzy/patchwork-core
src/Controller/FrontController.php
FrontController.connect
public function connect(Application $app) { $ctrl = $app['controllers_factory']; /** * Homepage */ $ctrl ->get( '/', function () use ($app) { $root = str_replace('index.php/', '', $app['url_generator']->generate('home')); if ($app['request']->getRequestURI() != $root) { return $app->redirect($root, Response::HTTP_MOVED_PERMANENTLY); } return $app['twig']->render('front/partials/home.twig'); } ) ->bind('home'); /** * Admin root */ $ctrl ->get( '/admin', function () use ($app) { return $app->redirect($app['url_generator']->generate($app['config']['admin']['root'])); } ); /** * robots.txt */ $ctrl ->get( '/robots.txt', function () use ($app) { $response = new Response( 'User-agent: *'.PHP_EOL.( $app['debug'] ? 'Disallow: /' : 'Sitemap: '.$app['url_generator']->generate('home').'sitemap.xml' ) ); $response->headers->set('Content-Type', 'text/plain'); return $response; } ); return $ctrl; }
php
public function connect(Application $app) { $ctrl = $app['controllers_factory']; /** * Homepage */ $ctrl ->get( '/', function () use ($app) { $root = str_replace('index.php/', '', $app['url_generator']->generate('home')); if ($app['request']->getRequestURI() != $root) { return $app->redirect($root, Response::HTTP_MOVED_PERMANENTLY); } return $app['twig']->render('front/partials/home.twig'); } ) ->bind('home'); /** * Admin root */ $ctrl ->get( '/admin', function () use ($app) { return $app->redirect($app['url_generator']->generate($app['config']['admin']['root'])); } ); /** * robots.txt */ $ctrl ->get( '/robots.txt', function () use ($app) { $response = new Response( 'User-agent: *'.PHP_EOL.( $app['debug'] ? 'Disallow: /' : 'Sitemap: '.$app['url_generator']->generate('home').'sitemap.xml' ) ); $response->headers->set('Content-Type', 'text/plain'); return $response; } ); return $ctrl; }
[ "public", "function", "connect", "(", "Application", "$", "app", ")", "{", "$", "ctrl", "=", "$", "app", "[", "'controllers_factory'", "]", ";", "/**\n * Homepage\n */", "$", "ctrl", "->", "get", "(", "'/'", ",", "function", "(", ")", "use", "(", "$", "app", ")", "{", "$", "root", "=", "str_replace", "(", "'index.php/'", ",", "''", ",", "$", "app", "[", "'url_generator'", "]", "->", "generate", "(", "'home'", ")", ")", ";", "if", "(", "$", "app", "[", "'request'", "]", "->", "getRequestURI", "(", ")", "!=", "$", "root", ")", "{", "return", "$", "app", "->", "redirect", "(", "$", "root", ",", "Response", "::", "HTTP_MOVED_PERMANENTLY", ")", ";", "}", "return", "$", "app", "[", "'twig'", "]", "->", "render", "(", "'front/partials/home.twig'", ")", ";", "}", ")", "->", "bind", "(", "'home'", ")", ";", "/**\n * Admin root\n */", "$", "ctrl", "->", "get", "(", "'/admin'", ",", "function", "(", ")", "use", "(", "$", "app", ")", "{", "return", "$", "app", "->", "redirect", "(", "$", "app", "[", "'url_generator'", "]", "->", "generate", "(", "$", "app", "[", "'config'", "]", "[", "'admin'", "]", "[", "'root'", "]", ")", ")", ";", "}", ")", ";", "/**\n * robots.txt\n */", "$", "ctrl", "->", "get", "(", "'/robots.txt'", ",", "function", "(", ")", "use", "(", "$", "app", ")", "{", "$", "response", "=", "new", "Response", "(", "'User-agent: *'", ".", "PHP_EOL", ".", "(", "$", "app", "[", "'debug'", "]", "?", "'Disallow: /'", ":", "'Sitemap: '", ".", "$", "app", "[", "'url_generator'", "]", "->", "generate", "(", "'home'", ")", ".", "'sitemap.xml'", ")", ")", ";", "$", "response", "->", "headers", "->", "set", "(", "'Content-Type'", ",", "'text/plain'", ")", ";", "return", "$", "response", ";", "}", ")", ";", "return", "$", "ctrl", ";", "}" ]
Silex method that exposes routes to the app @param Silex\Application $app Application instance @return Silex\ControllerCollection Object encapsulating crafted routes
[ "Silex", "method", "that", "exposes", "routes", "to", "the", "app" ]
81c31b5c0b3a82a04ed90eb17cefaf2faddee4ee
https://github.com/neemzy/patchwork-core/blob/81c31b5c0b3a82a04ed90eb17cefaf2faddee4ee/src/Controller/FrontController.php#L18-L79
1,765
Sowapps/orpheus-publisher
src/Publisher/Exception/InvalidFieldException.php
InvalidFieldException.getText
public function getText() { $args = $this->args; $msg = $this->getMessage(); // $msg = $this->field.'_'.$this->getMessage(); // if( !hasTranslation($msg, $this->domain) ) { // if( hasTranslation($this->getMessage().'_field', $this->domain) ) { // $msg = $this->getMessage().'_field'; // $args = array_merge(array('FIELD'=>t($this->getField(), $this->domain)), $args); // } else // if( hasTranslation($this->getMessage(), $this->domain) ) { // $msg = $this->getMessage(); // } // } return t($msg, $this->domain, $args); }
php
public function getText() { $args = $this->args; $msg = $this->getMessage(); // $msg = $this->field.'_'.$this->getMessage(); // if( !hasTranslation($msg, $this->domain) ) { // if( hasTranslation($this->getMessage().'_field', $this->domain) ) { // $msg = $this->getMessage().'_field'; // $args = array_merge(array('FIELD'=>t($this->getField(), $this->domain)), $args); // } else // if( hasTranslation($this->getMessage(), $this->domain) ) { // $msg = $this->getMessage(); // } // } return t($msg, $this->domain, $args); }
[ "public", "function", "getText", "(", ")", "{", "$", "args", "=", "$", "this", "->", "args", ";", "$", "msg", "=", "$", "this", "->", "getMessage", "(", ")", ";", "// \t\t$msg\t= $this->field.'_'.$this->getMessage();", "// \t\tif( !hasTranslation($msg, $this->domain) ) {", "// \t\t\tif( hasTranslation($this->getMessage().'_field', $this->domain) ) {", "// \t\t\t\t$msg\t= $this->getMessage().'_field';", "// \t\t\t\t$args\t= array_merge(array('FIELD'=>t($this->getField(), $this->domain)), $args);", "// \t\t\t} else", "// \t\t\tif( hasTranslation($this->getMessage(), $this->domain) ) {", "// \t\t\t\t$msg\t= $this->getMessage();", "// \t\t\t}", "// \t\t}", "return", "t", "(", "$", "msg", ",", "$", "this", "->", "domain", ",", "$", "args", ")", ";", "}" ]
Get the user's message @return string The translated message from this exception
[ "Get", "the", "user", "s", "message" ]
e33508538a0aa6f7491d724ca1cb09893203bfba
https://github.com/Sowapps/orpheus-publisher/blob/e33508538a0aa6f7491d724ca1cb09893203bfba/src/Publisher/Exception/InvalidFieldException.php#L119-L133
1,766
Sowapps/orpheus-publisher
src/Publisher/Exception/InvalidFieldException.php
InvalidFieldException.from
public static function from(UserException $e, $field, $value, $type=null, $args=array()) { return new static($e->getMessage(), $field, $value, $type, $e->getDomain(), $args); }
php
public static function from(UserException $e, $field, $value, $type=null, $args=array()) { return new static($e->getMessage(), $field, $value, $type, $e->getDomain(), $args); }
[ "public", "static", "function", "from", "(", "UserException", "$", "e", ",", "$", "field", ",", "$", "value", ",", "$", "type", "=", "null", ",", "$", "args", "=", "array", "(", ")", ")", "{", "return", "new", "static", "(", "$", "e", "->", "getMessage", "(", ")", ",", "$", "field", ",", "$", "value", ",", "$", "type", ",", "$", "e", "->", "getDomain", "(", ")", ",", "$", "args", ")", ";", "}" ]
Convert an UserException into an InvalidFieldException using other parameters @param UserException $e @param string $field @param string $value @param string $type @param array $args @return InvalidFieldException
[ "Convert", "an", "UserException", "into", "an", "InvalidFieldException", "using", "other", "parameters" ]
e33508538a0aa6f7491d724ca1cb09893203bfba
https://github.com/Sowapps/orpheus-publisher/blob/e33508538a0aa6f7491d724ca1cb09893203bfba/src/Publisher/Exception/InvalidFieldException.php#L163-L165
1,767
popy-dev/popy-calendar
src/Parser/DateLexer/PregCollection.php
PregCollection.register
public function register(PregDateLexerInterface $lexer) { $this->regexp .= $lexer->getExpression(); $this->lexers[] = $lexer; }
php
public function register(PregDateLexerInterface $lexer) { $this->regexp .= $lexer->getExpression(); $this->lexers[] = $lexer; }
[ "public", "function", "register", "(", "PregDateLexerInterface", "$", "lexer", ")", "{", "$", "this", "->", "regexp", ".=", "$", "lexer", "->", "getExpression", "(", ")", ";", "$", "this", "->", "lexers", "[", "]", "=", "$", "lexer", ";", "}" ]
Registers a pattern in the collection. @param PregDateLexerInterface $lexer
[ "Registers", "a", "pattern", "in", "the", "collection", "." ]
989048be18451c813cfce926229c6aaddd1b0639
https://github.com/popy-dev/popy-calendar/blob/989048be18451c813cfce926229c6aaddd1b0639/src/Parser/DateLexer/PregCollection.php#L54-L58
1,768
popy-dev/popy-calendar
src/Parser/DateLexer/PregCollection.php
PregCollection.compileExpressions
protected function compileExpressions() { if (count($this->expressions) === 0) { throw new BadMethodCallException('Can\'t compile an empty expression'); } if (count($this->expressions) === 1) { return reset($this->expressions); } $parts = []; foreach ($this->expressions as $expr) { $expr = '(?:' . $expr . ')'; $parts[] = $expr; } return '(?:' . implode('|', $parts) . ')'; }
php
protected function compileExpressions() { if (count($this->expressions) === 0) { throw new BadMethodCallException('Can\'t compile an empty expression'); } if (count($this->expressions) === 1) { return reset($this->expressions); } $parts = []; foreach ($this->expressions as $expr) { $expr = '(?:' . $expr . ')'; $parts[] = $expr; } return '(?:' . implode('|', $parts) . ')'; }
[ "protected", "function", "compileExpressions", "(", ")", "{", "if", "(", "count", "(", "$", "this", "->", "expressions", ")", "===", "0", ")", "{", "throw", "new", "BadMethodCallException", "(", "'Can\\'t compile an empty expression'", ")", ";", "}", "if", "(", "count", "(", "$", "this", "->", "expressions", ")", "===", "1", ")", "{", "return", "reset", "(", "$", "this", "->", "expressions", ")", ";", "}", "$", "parts", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "expressions", "as", "$", "expr", ")", "{", "$", "expr", "=", "'(?:'", ".", "$", "expr", ".", "')'", ";", "$", "parts", "[", "]", "=", "$", "expr", ";", "}", "return", "'(?:'", ".", "implode", "(", "'|'", ",", "$", "parts", ")", ".", "')'", ";", "}" ]
Compile expression list. @return string
[ "Compile", "expression", "list", "." ]
989048be18451c813cfce926229c6aaddd1b0639
https://github.com/popy-dev/popy-calendar/blob/989048be18451c813cfce926229c6aaddd1b0639/src/Parser/DateLexer/PregCollection.php#L117-L135
1,769
flowcode/ceibo
src/flowcode/ceibo/data/PDOMySqlDataSource.php
PDOMySqlDataSource.getConnection
function getConnection() { try { if (is_null($this->conn)) { $this->conn = new PDO($this->getDbDsn(), $this->getDbUser(), $this->getDbPass()); } return $this->conn; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } }
php
function getConnection() { try { if (is_null($this->conn)) { $this->conn = new PDO($this->getDbDsn(), $this->getDbUser(), $this->getDbPass()); } return $this->conn; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } }
[ "function", "getConnection", "(", ")", "{", "try", "{", "if", "(", "is_null", "(", "$", "this", "->", "conn", ")", ")", "{", "$", "this", "->", "conn", "=", "new", "PDO", "(", "$", "this", "->", "getDbDsn", "(", ")", ",", "$", "this", "->", "getDbUser", "(", ")", ",", "$", "this", "->", "getDbPass", "(", ")", ")", ";", "}", "return", "$", "this", "->", "conn", ";", "}", "catch", "(", "PDOException", "$", "e", ")", "{", "print", "\"Error!: \"", ".", "$", "e", "->", "getMessage", "(", ")", ".", "\"<br/>\"", ";", "die", "(", ")", ";", "}", "}" ]
Open a mysql connection. @return type @throws Exception
[ "Open", "a", "mysql", "connection", "." ]
ba264dc681a9d803885fd35d10b0e37776f66659
https://github.com/flowcode/ceibo/blob/ba264dc681a9d803885fd35d10b0e37776f66659/src/flowcode/ceibo/data/PDOMySqlDataSource.php#L26-L36
1,770
helthe/Mandrill
Mailer/TemplatingEngineMailer.php
TemplatingEngineMailer.sendMessage
public function sendMessage($recipients, $sender, $subject, $templateName, array $context = array()) { $this->client->sendMessage($this->createMessage( $recipients, $sender, $subject, $this->render($templateName, $context) )); }
php
public function sendMessage($recipients, $sender, $subject, $templateName, array $context = array()) { $this->client->sendMessage($this->createMessage( $recipients, $sender, $subject, $this->render($templateName, $context) )); }
[ "public", "function", "sendMessage", "(", "$", "recipients", ",", "$", "sender", ",", "$", "subject", ",", "$", "templateName", ",", "array", "$", "context", "=", "array", "(", ")", ")", "{", "$", "this", "->", "client", "->", "sendMessage", "(", "$", "this", "->", "createMessage", "(", "$", "recipients", ",", "$", "sender", ",", "$", "subject", ",", "$", "this", "->", "render", "(", "$", "templateName", ",", "$", "context", ")", ")", ")", ";", "}" ]
Send a transactional message using the given template. @param mixed $recipients @param mixed $sender @param string $subject @param string $templateName @param array $context
[ "Send", "a", "transactional", "message", "using", "the", "given", "template", "." ]
5d4ddd71079d9308e6d117311e96be1b9eb95637
https://github.com/helthe/Mandrill/blob/5d4ddd71079d9308e6d117311e96be1b9eb95637/Mailer/TemplatingEngineMailer.php#L53-L61
1,771
unyx/console
Descriptor.php
Descriptor.getInputOptionsSynopsis
public function getInputOptionsSynopsis(definitions\Options $definitions, array $options = null) { if ($definitions->isEmpty()) { return ''; } // The 'short_synopsis' option is primarily used by the Help command which lists all Input Options // separately from the synopsis for brevity. if ($options['short_synopsis'] ?? false) { return '[options]'; } $items = []; foreach ($definitions as $option) { $items[] = $this->getInputOptionSynopsis($option, $options); } return implode(' ', $items); }
php
public function getInputOptionsSynopsis(definitions\Options $definitions, array $options = null) { if ($definitions->isEmpty()) { return ''; } // The 'short_synopsis' option is primarily used by the Help command which lists all Input Options // separately from the synopsis for brevity. if ($options['short_synopsis'] ?? false) { return '[options]'; } $items = []; foreach ($definitions as $option) { $items[] = $this->getInputOptionSynopsis($option, $options); } return implode(' ', $items); }
[ "public", "function", "getInputOptionsSynopsis", "(", "definitions", "\\", "Options", "$", "definitions", ",", "array", "$", "options", "=", "null", ")", "{", "if", "(", "$", "definitions", "->", "isEmpty", "(", ")", ")", "{", "return", "''", ";", "}", "// The 'short_synopsis' option is primarily used by the Help command which lists all Input Options", "// separately from the synopsis for brevity.", "if", "(", "$", "options", "[", "'short_synopsis'", "]", "??", "false", ")", "{", "return", "'[options]'", ";", "}", "$", "items", "=", "[", "]", ";", "foreach", "(", "$", "definitions", "as", "$", "option", ")", "{", "$", "items", "[", "]", "=", "$", "this", "->", "getInputOptionSynopsis", "(", "$", "option", ",", "$", "options", ")", ";", "}", "return", "implode", "(", "' '", ",", "$", "items", ")", ";", "}" ]
Provides a synopsis for the given Input Option Definitions. @param definitions\Options $definitions The Input Option Definitions to provide a synopsis for. @param array $options Additional options to be considered by the Descriptor. @return mixed
[ "Provides", "a", "synopsis", "for", "the", "given", "Input", "Option", "Definitions", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/Descriptor.php#L146-L165
1,772
unyx/console
Descriptor.php
Descriptor.getInputOptionSynopsis
public function getInputOptionSynopsis(input\Option $definition, array $options = null) { $shortcut = $definition->getShortcut() ? sprintf('-%s|', $definition->getShortcut()) : ''; if ($value = $definition->getValue()) { $format = $value->is(input\Value::REQUIRED) ? '%s--%s="..."' : '%s--%s[="..."]'; } else { $format = '%s--%s'; } return sprintf('['.$format.']', $shortcut, $definition->getName()); }
php
public function getInputOptionSynopsis(input\Option $definition, array $options = null) { $shortcut = $definition->getShortcut() ? sprintf('-%s|', $definition->getShortcut()) : ''; if ($value = $definition->getValue()) { $format = $value->is(input\Value::REQUIRED) ? '%s--%s="..."' : '%s--%s[="..."]'; } else { $format = '%s--%s'; } return sprintf('['.$format.']', $shortcut, $definition->getName()); }
[ "public", "function", "getInputOptionSynopsis", "(", "input", "\\", "Option", "$", "definition", ",", "array", "$", "options", "=", "null", ")", "{", "$", "shortcut", "=", "$", "definition", "->", "getShortcut", "(", ")", "?", "sprintf", "(", "'-%s|'", ",", "$", "definition", "->", "getShortcut", "(", ")", ")", ":", "''", ";", "if", "(", "$", "value", "=", "$", "definition", "->", "getValue", "(", ")", ")", "{", "$", "format", "=", "$", "value", "->", "is", "(", "input", "\\", "Value", "::", "REQUIRED", ")", "?", "'%s--%s=\"...\"'", ":", "'%s--%s[=\"...\"]'", ";", "}", "else", "{", "$", "format", "=", "'%s--%s'", ";", "}", "return", "sprintf", "(", "'['", ".", "$", "format", ".", "']'", ",", "$", "shortcut", ",", "$", "definition", "->", "getName", "(", ")", ")", ";", "}" ]
Provides a synopsis for the given Input Option. @param input\Option $definition The Input Option to provide a synopsis for. @param array $options Additional options to be considered by the Descriptor. @return mixed
[ "Provides", "a", "synopsis", "for", "the", "given", "Input", "Option", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/Descriptor.php#L174-L185
1,773
unyx/console
Descriptor.php
Descriptor.getInputArgumentsSynopsis
public function getInputArgumentsSynopsis(definitions\Arguments $definitions, array $options = null) { if ($definitions->isEmpty()) { return ''; } $items = []; /** @var input\Argument $argument */ foreach ($definitions as $argument) { $items[] = $this->getInputArgumentSynopsis($argument, $options); } return implode(' ', $items); }
php
public function getInputArgumentsSynopsis(definitions\Arguments $definitions, array $options = null) { if ($definitions->isEmpty()) { return ''; } $items = []; /** @var input\Argument $argument */ foreach ($definitions as $argument) { $items[] = $this->getInputArgumentSynopsis($argument, $options); } return implode(' ', $items); }
[ "public", "function", "getInputArgumentsSynopsis", "(", "definitions", "\\", "Arguments", "$", "definitions", ",", "array", "$", "options", "=", "null", ")", "{", "if", "(", "$", "definitions", "->", "isEmpty", "(", ")", ")", "{", "return", "''", ";", "}", "$", "items", "=", "[", "]", ";", "/** @var input\\Argument $argument */", "foreach", "(", "$", "definitions", "as", "$", "argument", ")", "{", "$", "items", "[", "]", "=", "$", "this", "->", "getInputArgumentSynopsis", "(", "$", "argument", ",", "$", "options", ")", ";", "}", "return", "implode", "(", "' '", ",", "$", "items", ")", ";", "}" ]
Provides a synopsis for the given Input Argument Definitions. @param definitions\Arguments $definitions The Input Argument Definitions to provide a synopsis for. @param array $options Additional options to be considered by the Descriptor. @return mixed
[ "Provides", "a", "synopsis", "for", "the", "given", "Input", "Argument", "Definitions", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/Descriptor.php#L194-L208
1,774
unyx/console
Descriptor.php
Descriptor.getInputArgumentSynopsis
public function getInputArgumentSynopsis(input\Argument $definition, array $options = null) { $output = '\<'.$definition->getName().'>'; $value = $definition->getValue(); if (!$value->is(input\Value::REQUIRED)) { $output = '['.$output.']'; } elseif ($value instanceof input\values\Multiple) { $output = $output.' ('.$output.')'; } if ($value instanceof input\values\Multiple) { $output .= '...'; } return $output; }
php
public function getInputArgumentSynopsis(input\Argument $definition, array $options = null) { $output = '\<'.$definition->getName().'>'; $value = $definition->getValue(); if (!$value->is(input\Value::REQUIRED)) { $output = '['.$output.']'; } elseif ($value instanceof input\values\Multiple) { $output = $output.' ('.$output.')'; } if ($value instanceof input\values\Multiple) { $output .= '...'; } return $output; }
[ "public", "function", "getInputArgumentSynopsis", "(", "input", "\\", "Argument", "$", "definition", ",", "array", "$", "options", "=", "null", ")", "{", "$", "output", "=", "'\\<'", ".", "$", "definition", "->", "getName", "(", ")", ".", "'>'", ";", "$", "value", "=", "$", "definition", "->", "getValue", "(", ")", ";", "if", "(", "!", "$", "value", "->", "is", "(", "input", "\\", "Value", "::", "REQUIRED", ")", ")", "{", "$", "output", "=", "'['", ".", "$", "output", ".", "']'", ";", "}", "elseif", "(", "$", "value", "instanceof", "input", "\\", "values", "\\", "Multiple", ")", "{", "$", "output", "=", "$", "output", ".", "' ('", ".", "$", "output", ".", "')'", ";", "}", "if", "(", "$", "value", "instanceof", "input", "\\", "values", "\\", "Multiple", ")", "{", "$", "output", ".=", "'...'", ";", "}", "return", "$", "output", ";", "}" ]
Provides a synopsis for the given Input Argument. @param input\Argument $definition The Input Argument to provide a synopsis for. @param array $options Additional options to be considered by the Descriptor. @return mixed
[ "Provides", "a", "synopsis", "for", "the", "given", "Input", "Argument", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/Descriptor.php#L217-L233
1,775
fortifi/sdk
api/Foundation/Enums/DataNodeState.php
DataNodeState.getDisplayValue
public static function getDisplayValue($value) { switch($value) { case self::ACTIVE: return 'Active'; case self::ARCHIVED: return 'Archived'; case self::PENDING: return 'Pending'; case self::CORRUPT: return 'Corrupt'; default: return $value; } }
php
public static function getDisplayValue($value) { switch($value) { case self::ACTIVE: return 'Active'; case self::ARCHIVED: return 'Archived'; case self::PENDING: return 'Pending'; case self::CORRUPT: return 'Corrupt'; default: return $value; } }
[ "public", "static", "function", "getDisplayValue", "(", "$", "value", ")", "{", "switch", "(", "$", "value", ")", "{", "case", "self", "::", "ACTIVE", ":", "return", "'Active'", ";", "case", "self", "::", "ARCHIVED", ":", "return", "'Archived'", ";", "case", "self", "::", "PENDING", ":", "return", "'Pending'", ";", "case", "self", "::", "CORRUPT", ":", "return", "'Corrupt'", ";", "default", ":", "return", "$", "value", ";", "}", "}" ]
Data is known to be corrupt
[ "Data", "is", "known", "to", "be", "corrupt" ]
4d0471c72c7954271c692d32265fd42f698392e4
https://github.com/fortifi/sdk/blob/4d0471c72c7954271c692d32265fd42f698392e4/api/Foundation/Enums/DataNodeState.php#L11-L26
1,776
philiplb/CRUDlexUser
src/CRUDlex/UserSetup.php
UserSetup.getPWHashFunction
protected function getPWHashFunction(AbstractData $data, $passwordField, $saltField) { $that = $this; return function(Entity $entity) use ($data, $passwordField, $saltField, $that) { $password = $entity->get($passwordField); if (!$password) { return true; } $salt = $entity->get($saltField); $newSalt = $that->possibleGenSalt($salt, $entity, $saltField); $passwordHash = $this->encoder->encodePassword($password, $salt); $doGenerateHash = $that->doGenerateHash($data, $entity, $passwordField, $password, $newSalt); if ($doGenerateHash) { $entity->set($passwordField, $passwordHash); } return true; }; }
php
protected function getPWHashFunction(AbstractData $data, $passwordField, $saltField) { $that = $this; return function(Entity $entity) use ($data, $passwordField, $saltField, $that) { $password = $entity->get($passwordField); if (!$password) { return true; } $salt = $entity->get($saltField); $newSalt = $that->possibleGenSalt($salt, $entity, $saltField); $passwordHash = $this->encoder->encodePassword($password, $salt); $doGenerateHash = $that->doGenerateHash($data, $entity, $passwordField, $password, $newSalt); if ($doGenerateHash) { $entity->set($passwordField, $passwordHash); } return true; }; }
[ "protected", "function", "getPWHashFunction", "(", "AbstractData", "$", "data", ",", "$", "passwordField", ",", "$", "saltField", ")", "{", "$", "that", "=", "$", "this", ";", "return", "function", "(", "Entity", "$", "entity", ")", "use", "(", "$", "data", ",", "$", "passwordField", ",", "$", "saltField", ",", "$", "that", ")", "{", "$", "password", "=", "$", "entity", "->", "get", "(", "$", "passwordField", ")", ";", "if", "(", "!", "$", "password", ")", "{", "return", "true", ";", "}", "$", "salt", "=", "$", "entity", "->", "get", "(", "$", "saltField", ")", ";", "$", "newSalt", "=", "$", "that", "->", "possibleGenSalt", "(", "$", "salt", ",", "$", "entity", ",", "$", "saltField", ")", ";", "$", "passwordHash", "=", "$", "this", "->", "encoder", "->", "encodePassword", "(", "$", "password", ",", "$", "salt", ")", ";", "$", "doGenerateHash", "=", "$", "that", "->", "doGenerateHash", "(", "$", "data", ",", "$", "entity", ",", "$", "passwordField", ",", "$", "password", ",", "$", "newSalt", ")", ";", "if", "(", "$", "doGenerateHash", ")", "{", "$", "entity", "->", "set", "(", "$", "passwordField", ",", "$", "passwordHash", ")", ";", "}", "return", "true", ";", "}", ";", "}" ]
Gets a closure for possibly generating a password hash in the entity. @param AbstractData $data the AbstractData instance managing the users @param string $passwordField the Entity fieldname of the password hash @param string $saltField the Entity fieldname of the password hash salt
[ "Gets", "a", "closure", "for", "possibly", "generating", "a", "password", "hash", "in", "the", "entity", "." ]
011c70106786ded665200a1b6b61234800c2b802
https://github.com/philiplb/CRUDlexUser/blob/011c70106786ded665200a1b6b61234800c2b802/src/CRUDlex/UserSetup.php#L43-L65
1,777
philiplb/CRUDlexUser
src/CRUDlex/UserSetup.php
UserSetup.possibleGenSalt
public function possibleGenSalt(&$salt, Entity $entity, $saltField) { if (!$salt) { $salt = $this->getSalt(40); $entity->set($saltField, $salt); return true; } return false; }
php
public function possibleGenSalt(&$salt, Entity $entity, $saltField) { if (!$salt) { $salt = $this->getSalt(40); $entity->set($saltField, $salt); return true; } return false; }
[ "public", "function", "possibleGenSalt", "(", "&", "$", "salt", ",", "Entity", "$", "entity", ",", "$", "saltField", ")", "{", "if", "(", "!", "$", "salt", ")", "{", "$", "salt", "=", "$", "this", "->", "getSalt", "(", "40", ")", ";", "$", "entity", "->", "set", "(", "$", "saltField", ",", "$", "salt", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Generates a new salt if the given salt is null. @param string $salt the salt to override if null @param Entity the entity getting the new salt @param string $saltField the field holding the salt in the entity @return boolean true if a new salt was generated
[ "Generates", "a", "new", "salt", "if", "the", "given", "salt", "is", "null", "." ]
011c70106786ded665200a1b6b61234800c2b802
https://github.com/philiplb/CRUDlexUser/blob/011c70106786ded665200a1b6b61234800c2b802/src/CRUDlex/UserSetup.php#L94-L102
1,778
philiplb/CRUDlexUser
src/CRUDlex/UserSetup.php
UserSetup.doGenerateHash
public function doGenerateHash(AbstractData $data, Entity $entity, $passwordField, $password, $newSalt) { $doGenerateHash = true; $id = $entity->get('id'); if ($id !== null) { $oldEntity = $data->get($entity->get('id')); $doGenerateHash = $oldEntity->get($passwordField) !== $password || $newSalt; } return $doGenerateHash; }
php
public function doGenerateHash(AbstractData $data, Entity $entity, $passwordField, $password, $newSalt) { $doGenerateHash = true; $id = $entity->get('id'); if ($id !== null) { $oldEntity = $data->get($entity->get('id')); $doGenerateHash = $oldEntity->get($passwordField) !== $password || $newSalt; } return $doGenerateHash; }
[ "public", "function", "doGenerateHash", "(", "AbstractData", "$", "data", ",", "Entity", "$", "entity", ",", "$", "passwordField", ",", "$", "password", ",", "$", "newSalt", ")", "{", "$", "doGenerateHash", "=", "true", ";", "$", "id", "=", "$", "entity", "->", "get", "(", "'id'", ")", ";", "if", "(", "$", "id", "!==", "null", ")", "{", "$", "oldEntity", "=", "$", "data", "->", "get", "(", "$", "entity", "->", "get", "(", "'id'", ")", ")", ";", "$", "doGenerateHash", "=", "$", "oldEntity", "->", "get", "(", "$", "passwordField", ")", "!==", "$", "password", "||", "$", "newSalt", ";", "}", "return", "$", "doGenerateHash", ";", "}" ]
Determines whether the entity needs a new hash generated. @param AbstractData $data the CRUDlex data instance of the user entity @param Entity $entity the entity @param string $passwordField the field holding the password hash in the entity @param string $password the current password hash @param boolean $newSalt whether a new password hash salt was generated @return boolean true if the entity needs a new hash
[ "Determines", "whether", "the", "entity", "needs", "a", "new", "hash", "generated", "." ]
011c70106786ded665200a1b6b61234800c2b802
https://github.com/philiplb/CRUDlexUser/blob/011c70106786ded665200a1b6b61234800c2b802/src/CRUDlex/UserSetup.php#L121-L130
1,779
philiplb/CRUDlexUser
src/CRUDlex/UserSetup.php
UserSetup.getSalt
public function getSalt($len) { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-=_+'; $l = strlen($chars) - 1; $str = ''; for ($i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $l)]; } return $str; }
php
public function getSalt($len) { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-=_+'; $l = strlen($chars) - 1; $str = ''; for ($i = 0; $i < $len; ++$i) { $str .= $chars[mt_rand(0, $l)]; } return $str; }
[ "public", "function", "getSalt", "(", "$", "len", ")", "{", "$", "chars", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()-=_+'", ";", "$", "l", "=", "strlen", "(", "$", "chars", ")", "-", "1", ";", "$", "str", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "len", ";", "++", "$", "i", ")", "{", "$", "str", ".=", "$", "chars", "[", "mt_rand", "(", "0", ",", "$", "l", ")", "]", ";", "}", "return", "$", "str", ";", "}" ]
Generates a random salt of the given length. @param int $len the desired length @return string a random salt of the given length
[ "Generates", "a", "random", "salt", "of", "the", "given", "length", "." ]
011c70106786ded665200a1b6b61234800c2b802
https://github.com/philiplb/CRUDlexUser/blob/011c70106786ded665200a1b6b61234800c2b802/src/CRUDlex/UserSetup.php#L141-L150
1,780
philiplb/CRUDlexUser
src/CRUDlex/UserSetup.php
UserSetup.addEvents
public function addEvents(AbstractData $data, $passwordField = 'password', $saltField = 'salt') { $that = $this; $saltGenFunction = function(Entity $entity) use ($saltField, $that) { $salt = $that->getSalt(40); $entity->set($saltField, $salt); return true; }; $data->getEvents()->push('before', 'create', $saltGenFunction); $pwHashFunction = $this->getPWHashFunction($data, $passwordField, $saltField); $data->getEvents()->push('before', 'create', $pwHashFunction); $data->getEvents()->push('before', 'update', $pwHashFunction); }
php
public function addEvents(AbstractData $data, $passwordField = 'password', $saltField = 'salt') { $that = $this; $saltGenFunction = function(Entity $entity) use ($saltField, $that) { $salt = $that->getSalt(40); $entity->set($saltField, $salt); return true; }; $data->getEvents()->push('before', 'create', $saltGenFunction); $pwHashFunction = $this->getPWHashFunction($data, $passwordField, $saltField); $data->getEvents()->push('before', 'create', $pwHashFunction); $data->getEvents()->push('before', 'update', $pwHashFunction); }
[ "public", "function", "addEvents", "(", "AbstractData", "$", "data", ",", "$", "passwordField", "=", "'password'", ",", "$", "saltField", "=", "'salt'", ")", "{", "$", "that", "=", "$", "this", ";", "$", "saltGenFunction", "=", "function", "(", "Entity", "$", "entity", ")", "use", "(", "$", "saltField", ",", "$", "that", ")", "{", "$", "salt", "=", "$", "that", "->", "getSalt", "(", "40", ")", ";", "$", "entity", "->", "set", "(", "$", "saltField", ",", "$", "salt", ")", ";", "return", "true", ";", "}", ";", "$", "data", "->", "getEvents", "(", ")", "->", "push", "(", "'before'", ",", "'create'", ",", "$", "saltGenFunction", ")", ";", "$", "pwHashFunction", "=", "$", "this", "->", "getPWHashFunction", "(", "$", "data", ",", "$", "passwordField", ",", "$", "saltField", ")", ";", "$", "data", "->", "getEvents", "(", ")", "->", "push", "(", "'before'", ",", "'create'", ",", "$", "pwHashFunction", ")", ";", "$", "data", "->", "getEvents", "(", ")", "->", "push", "(", "'before'", ",", "'update'", ",", "$", "pwHashFunction", ")", ";", "}" ]
Setups CRUDlex with some events so the passwords get salted and hashed properly. @param AbstractData $data the AbstractData instance managing the users @param string $passwordField the Entity fieldname of the password hash @param string $saltField the Entity fieldname of the password hash salt
[ "Setups", "CRUDlex", "with", "some", "events", "so", "the", "passwords", "get", "salted", "and", "hashed", "properly", "." ]
011c70106786ded665200a1b6b61234800c2b802
https://github.com/philiplb/CRUDlexUser/blob/011c70106786ded665200a1b6b61234800c2b802/src/CRUDlex/UserSetup.php#L165-L182
1,781
sellerlabs/nucleus
src/SellerLabs/Nucleus/Data/ArrayList.php
ArrayList.append
public function append(SemigroupInterface $other) { if ($other instanceof static) { return new static(array_merge($this->value, $other->value)); } $this->throwMismatchedDataTypeException($other); }
php
public function append(SemigroupInterface $other) { if ($other instanceof static) { return new static(array_merge($this->value, $other->value)); } $this->throwMismatchedDataTypeException($other); }
[ "public", "function", "append", "(", "SemigroupInterface", "$", "other", ")", "{", "if", "(", "$", "other", "instanceof", "static", ")", "{", "return", "new", "static", "(", "array_merge", "(", "$", "this", "->", "value", ",", "$", "other", "->", "value", ")", ")", ";", "}", "$", "this", "->", "throwMismatchedDataTypeException", "(", "$", "other", ")", ";", "}" ]
Append another semigroup and return the result. @param SemigroupInterface $other @return static|SemigroupInterface @throws CoreException @throws MismatchedArgumentTypesException
[ "Append", "another", "semigroup", "and", "return", "the", "result", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Data/ArrayList.php#L157-L164
1,782
extendsframework/extends-application
src/AbstractApplication.php
AbstractApplication.triggerOnStartup
protected function triggerOnStartup(): AbstractApplication { foreach ($this->getModules() as $module) { if ($module instanceof StartupProviderInterface) { $module->onStartup( $this->getServiceLocator() ); } } return $this; }
php
protected function triggerOnStartup(): AbstractApplication { foreach ($this->getModules() as $module) { if ($module instanceof StartupProviderInterface) { $module->onStartup( $this->getServiceLocator() ); } } return $this; }
[ "protected", "function", "triggerOnStartup", "(", ")", ":", "AbstractApplication", "{", "foreach", "(", "$", "this", "->", "getModules", "(", ")", "as", "$", "module", ")", "{", "if", "(", "$", "module", "instanceof", "StartupProviderInterface", ")", "{", "$", "module", "->", "onStartup", "(", "$", "this", "->", "getServiceLocator", "(", ")", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Trigger startup providers. @return AbstractApplication
[ "Trigger", "startup", "providers", "." ]
89b74594310e60542d5714e2db33ae0feb0f9d34
https://github.com/extendsframework/extends-application/blob/89b74594310e60542d5714e2db33ae0feb0f9d34/src/AbstractApplication.php#L55-L66
1,783
extendsframework/extends-application
src/AbstractApplication.php
AbstractApplication.triggerOnShutdown
protected function triggerOnShutdown(): AbstractApplication { foreach ($this->getModules() as $module) { if ($module instanceof ShutdownProviderInterface) { $module->onShutdown( $this->getServiceLocator() ); } } return $this; }
php
protected function triggerOnShutdown(): AbstractApplication { foreach ($this->getModules() as $module) { if ($module instanceof ShutdownProviderInterface) { $module->onShutdown( $this->getServiceLocator() ); } } return $this; }
[ "protected", "function", "triggerOnShutdown", "(", ")", ":", "AbstractApplication", "{", "foreach", "(", "$", "this", "->", "getModules", "(", ")", "as", "$", "module", ")", "{", "if", "(", "$", "module", "instanceof", "ShutdownProviderInterface", ")", "{", "$", "module", "->", "onShutdown", "(", "$", "this", "->", "getServiceLocator", "(", ")", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Trigger shutdown providers. @return AbstractApplication
[ "Trigger", "shutdown", "providers", "." ]
89b74594310e60542d5714e2db33ae0feb0f9d34
https://github.com/extendsframework/extends-application/blob/89b74594310e60542d5714e2db33ae0feb0f9d34/src/AbstractApplication.php#L73-L84
1,784
phergie/phergie-irc-plugin-react-pong
src/Plugin.php
Plugin.pong
public function pong(EventInterface $event, EventQueueInterface $queue) { $params = $event->getParams(); $queue->ircPong($params['server1']); }
php
public function pong(EventInterface $event, EventQueueInterface $queue) { $params = $event->getParams(); $queue->ircPong($params['server1']); }
[ "public", "function", "pong", "(", "EventInterface", "$", "event", ",", "EventQueueInterface", "$", "queue", ")", "{", "$", "params", "=", "$", "event", "->", "getParams", "(", ")", ";", "$", "queue", "->", "ircPong", "(", "$", "params", "[", "'server1'", "]", ")", ";", "}" ]
Responds to server ping events. @param \Phergie\Irc\Event\EventInterface $event Ping event to respond to @param \Phergie\Irc\Bot\React\EventQueueInterface $queue
[ "Responds", "to", "server", "ping", "events", "." ]
b5e21859f6e1d59b06d5d02a06e9651873823f28
https://github.com/phergie/phergie-irc-plugin-react-pong/blob/b5e21859f6e1d59b06d5d02a06e9651873823f28/src/Plugin.php#L43-L47
1,785
unyx/utils
str/Character.php
Character.each
public static function each(string $str, callable $callable, string $encoding = null, ...$args) : string { if ($str === '') { return $str; } $result = ''; $encoding = $encoding ?: utils\Str::encoding($str); $length = mb_strlen($str, $encoding); for ($idx = 0; $idx < $length; $idx++) { $result .= (string) call_user_func($callable, mb_substr($str, $idx, 1, $encoding), $idx, ...$args); } return $result; }
php
public static function each(string $str, callable $callable, string $encoding = null, ...$args) : string { if ($str === '') { return $str; } $result = ''; $encoding = $encoding ?: utils\Str::encoding($str); $length = mb_strlen($str, $encoding); for ($idx = 0; $idx < $length; $idx++) { $result .= (string) call_user_func($callable, mb_substr($str, $idx, 1, $encoding), $idx, ...$args); } return $result; }
[ "public", "static", "function", "each", "(", "string", "$", "str", ",", "callable", "$", "callable", ",", "string", "$", "encoding", "=", "null", ",", "...", "$", "args", ")", ":", "string", "{", "if", "(", "$", "str", "===", "''", ")", "{", "return", "$", "str", ";", "}", "$", "result", "=", "''", ";", "$", "encoding", "=", "$", "encoding", "?", ":", "utils", "\\", "Str", "::", "encoding", "(", "$", "str", ")", ";", "$", "length", "=", "mb_strlen", "(", "$", "str", ",", "$", "encoding", ")", ";", "for", "(", "$", "idx", "=", "0", ";", "$", "idx", "<", "$", "length", ";", "$", "idx", "++", ")", "{", "$", "result", ".=", "(", "string", ")", "call_user_func", "(", "$", "callable", ",", "mb_substr", "(", "$", "str", ",", "$", "idx", ",", "1", ",", "$", "encoding", ")", ",", "$", "idx", ",", "...", "$", "args", ")", ";", "}", "return", "$", "result", ";", "}" ]
Runs the given callable over each character in the given string and returns the resulting string. The callable should accept two arguments (in this order): - the character (multibyte string) - the character's index (int). Additional arguments may also be added and will be appended to the callable in the order given. The callable must return either a string or a value castable to a string. @param string $str The string over which to run the callable. @param callable $callable The callable to apply. @param string|null $encoding The encoding to use. @param mixed ...$args Additional arguments to pass to the callable. @return string The string after applying the callable to each of its characters.
[ "Runs", "the", "given", "callable", "over", "each", "character", "in", "the", "given", "string", "and", "returns", "the", "resulting", "string", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/str/Character.php#L166-L181
1,786
unyx/utils
str/Character.php
Character.toBinaryString
public static function toBinaryString(string $character) : string { $result = null; $length = strlen($character); // Note: We want the raw length, not the mb length. for ($i = 0; $i < $length; ++$i) { $result .= sprintf('%08b', ord($character[$i])); } return $result; }
php
public static function toBinaryString(string $character) : string { $result = null; $length = strlen($character); // Note: We want the raw length, not the mb length. for ($i = 0; $i < $length; ++$i) { $result .= sprintf('%08b', ord($character[$i])); } return $result; }
[ "public", "static", "function", "toBinaryString", "(", "string", "$", "character", ")", ":", "string", "{", "$", "result", "=", "null", ";", "$", "length", "=", "strlen", "(", "$", "character", ")", ";", "// Note: We want the raw length, not the mb length.", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "++", "$", "i", ")", "{", "$", "result", ".=", "sprintf", "(", "'%08b'", ",", "ord", "(", "$", "character", "[", "$", "i", "]", ")", ")", ";", "}", "return", "$", "result", ";", "}" ]
Returns the binary string representation of the given character. Multi-byte safe. @param string $character The character to represent. @return string
[ "Returns", "the", "binary", "string", "representation", "of", "the", "given", "character", ".", "Multi", "-", "byte", "safe", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/str/Character.php#L189-L199
1,787
unyx/utils
str/Character.php
Character.toDecimalCode
public static function toDecimalCode(string $character) : int { $code = ord($character[0]); // Single byte / 0xxxxxxx if (!($code & 0x80)) { return $code; } $bytes = 1; // 2 bytes / 110xxxxx if (0xc0 === ($code & 0xe0)) { $code = $code & ~0xc0; $bytes = 2; // 3 bytes / 1110xxxx } elseif (0xe0 === ($code & 0xf0)) { $code = $code & ~0xe0; $bytes = 3; // 4 bytes / 11110xxx } elseif (0xf0 === ($code & 0xf8)) { $code = $code & ~0xf0; $bytes = 4; } for ($i = 2; $i <= $bytes; $i++) { $code = ($code << 6) + (ord($character[$i - 1]) & ~0x80); } return $code; }
php
public static function toDecimalCode(string $character) : int { $code = ord($character[0]); // Single byte / 0xxxxxxx if (!($code & 0x80)) { return $code; } $bytes = 1; // 2 bytes / 110xxxxx if (0xc0 === ($code & 0xe0)) { $code = $code & ~0xc0; $bytes = 2; // 3 bytes / 1110xxxx } elseif (0xe0 === ($code & 0xf0)) { $code = $code & ~0xe0; $bytes = 3; // 4 bytes / 11110xxx } elseif (0xf0 === ($code & 0xf8)) { $code = $code & ~0xf0; $bytes = 4; } for ($i = 2; $i <= $bytes; $i++) { $code = ($code << 6) + (ord($character[$i - 1]) & ~0x80); } return $code; }
[ "public", "static", "function", "toDecimalCode", "(", "string", "$", "character", ")", ":", "int", "{", "$", "code", "=", "ord", "(", "$", "character", "[", "0", "]", ")", ";", "// Single byte / 0xxxxxxx", "if", "(", "!", "(", "$", "code", "&", "0x80", ")", ")", "{", "return", "$", "code", ";", "}", "$", "bytes", "=", "1", ";", "// 2 bytes / 110xxxxx", "if", "(", "0xc0", "===", "(", "$", "code", "&", "0xe0", ")", ")", "{", "$", "code", "=", "$", "code", "&", "~", "0xc0", ";", "$", "bytes", "=", "2", ";", "// 3 bytes / 1110xxxx", "}", "elseif", "(", "0xe0", "===", "(", "$", "code", "&", "0xf0", ")", ")", "{", "$", "code", "=", "$", "code", "&", "~", "0xe0", ";", "$", "bytes", "=", "3", ";", "// 4 bytes / 11110xxx", "}", "elseif", "(", "0xf0", "===", "(", "$", "code", "&", "0xf8", ")", ")", "{", "$", "code", "=", "$", "code", "&", "~", "0xf0", ";", "$", "bytes", "=", "4", ";", "}", "for", "(", "$", "i", "=", "2", ";", "$", "i", "<=", "$", "bytes", ";", "$", "i", "++", ")", "{", "$", "code", "=", "(", "$", "code", "<<", "6", ")", "+", "(", "ord", "(", "$", "character", "[", "$", "i", "-", "1", "]", ")", "&", "~", "0x80", ")", ";", "}", "return", "$", "code", ";", "}" ]
Returns the decimal code representation of the given character. Multi-byte safe. @param string $character The character to represent. @return int
[ "Returns", "the", "decimal", "code", "representation", "of", "the", "given", "character", ".", "Multi", "-", "byte", "safe", "." ]
503a3dd46fd2216024ab771b6e830be16d36b358
https://github.com/unyx/utils/blob/503a3dd46fd2216024ab771b6e830be16d36b358/str/Character.php#L207-L237
1,788
fazland/elastica-odm
src/Internal/CommitOrderCalculator.php
CommitOrderCalculator.addClass
public function addClass(DocumentMetadata $metadata): void { $this->graph->addNode($metadata->name); $assocNames = $metadata->getAssociationNames(); foreach ($assocNames as $assocName) { $targetClass = $metadata->getAssociationTargetClass($assocName); $this->graph->addNode($targetClass); $this->graph->connect($metadata->name, $targetClass); } }
php
public function addClass(DocumentMetadata $metadata): void { $this->graph->addNode($metadata->name); $assocNames = $metadata->getAssociationNames(); foreach ($assocNames as $assocName) { $targetClass = $metadata->getAssociationTargetClass($assocName); $this->graph->addNode($targetClass); $this->graph->connect($metadata->name, $targetClass); } }
[ "public", "function", "addClass", "(", "DocumentMetadata", "$", "metadata", ")", ":", "void", "{", "$", "this", "->", "graph", "->", "addNode", "(", "$", "metadata", "->", "name", ")", ";", "$", "assocNames", "=", "$", "metadata", "->", "getAssociationNames", "(", ")", ";", "foreach", "(", "$", "assocNames", "as", "$", "assocName", ")", "{", "$", "targetClass", "=", "$", "metadata", "->", "getAssociationTargetClass", "(", "$", "assocName", ")", ";", "$", "this", "->", "graph", "->", "addNode", "(", "$", "targetClass", ")", ";", "$", "this", "->", "graph", "->", "connect", "(", "$", "metadata", "->", "name", ",", "$", "targetClass", ")", ";", "}", "}" ]
Adds a document class to the dependency graph and evaluates its associations. @param DocumentMetadata $metadata
[ "Adds", "a", "document", "class", "to", "the", "dependency", "graph", "and", "evaluates", "its", "associations", "." ]
9d7276ea9ea9103c670f13f889bf59568ff35274
https://github.com/fazland/elastica-odm/blob/9d7276ea9ea9103c670f13f889bf59568ff35274/src/Internal/CommitOrderCalculator.php#L25-L35
1,789
fazland/elastica-odm
src/Internal/CommitOrderCalculator.php
CommitOrderCalculator.getOrder
public function getOrder(array $classNames): array { $elements = array_filter(iterator_to_array($this->graph), function ($element) use ($classNames): bool { list($node) = $element; return in_array($node->getClassName(), $classNames); }); return array_reverse($elements, false); }
php
public function getOrder(array $classNames): array { $elements = array_filter(iterator_to_array($this->graph), function ($element) use ($classNames): bool { list($node) = $element; return in_array($node->getClassName(), $classNames); }); return array_reverse($elements, false); }
[ "public", "function", "getOrder", "(", "array", "$", "classNames", ")", ":", "array", "{", "$", "elements", "=", "array_filter", "(", "iterator_to_array", "(", "$", "this", "->", "graph", ")", ",", "function", "(", "$", "element", ")", "use", "(", "$", "classNames", ")", ":", "bool", "{", "list", "(", "$", "node", ")", "=", "$", "element", ";", "return", "in_array", "(", "$", "node", "->", "getClassName", "(", ")", ",", "$", "classNames", ")", ";", "}", ")", ";", "return", "array_reverse", "(", "$", "elements", ",", "false", ")", ";", "}" ]
Gets the commit order set. @param array $classNames @return array
[ "Gets", "the", "commit", "order", "set", "." ]
9d7276ea9ea9103c670f13f889bf59568ff35274
https://github.com/fazland/elastica-odm/blob/9d7276ea9ea9103c670f13f889bf59568ff35274/src/Internal/CommitOrderCalculator.php#L44-L53
1,790
synapsestudios/synapse-base
src/Synapse/Entity/EntityIterator.php
EntityIterator.setEntities
public function setEntities(array $entities) { foreach ($entities as $entity) { if (! $entity instanceof AbstractEntity) { $message = sprintf( 'Expected an array of entities. Array contains element of type %s.', gettype($entity) ); throw new InvalidArgumentException($message); } } $this->entities = $entities; }
php
public function setEntities(array $entities) { foreach ($entities as $entity) { if (! $entity instanceof AbstractEntity) { $message = sprintf( 'Expected an array of entities. Array contains element of type %s.', gettype($entity) ); throw new InvalidArgumentException($message); } } $this->entities = $entities; }
[ "public", "function", "setEntities", "(", "array", "$", "entities", ")", "{", "foreach", "(", "$", "entities", "as", "$", "entity", ")", "{", "if", "(", "!", "$", "entity", "instanceof", "AbstractEntity", ")", "{", "$", "message", "=", "sprintf", "(", "'Expected an array of entities. Array contains element of type %s.'", ",", "gettype", "(", "$", "entity", ")", ")", ";", "throw", "new", "InvalidArgumentException", "(", "$", "message", ")", ";", "}", "}", "$", "this", "->", "entities", "=", "$", "entities", ";", "}" ]
Set the entities wrapped by this class @param array $entities Array of AbstractEntity objects @throws InvalidArgumentException If all elements of $entities are not AbstractEntity objects
[ "Set", "the", "entities", "wrapped", "by", "this", "class" ]
60c830550491742a077ab063f924e2f0b63825da
https://github.com/synapsestudios/synapse-base/blob/60c830550491742a077ab063f924e2f0b63825da/src/Synapse/Entity/EntityIterator.php#L49-L63
1,791
synapsestudios/synapse-base
src/Synapse/Entity/EntityIterator.php
EntityIterator.getArrayCopy
public function getArrayCopy() { $results = array_map(function ($entity) { return $entity->getArrayCopy(); }, $this->entities); if (! $this->paginationData) { return $results; } else { $data = $this->paginationData->getArrayCopy(); $data['results'] = $results; return $data; } }
php
public function getArrayCopy() { $results = array_map(function ($entity) { return $entity->getArrayCopy(); }, $this->entities); if (! $this->paginationData) { return $results; } else { $data = $this->paginationData->getArrayCopy(); $data['results'] = $results; return $data; } }
[ "public", "function", "getArrayCopy", "(", ")", "{", "$", "results", "=", "array_map", "(", "function", "(", "$", "entity", ")", "{", "return", "$", "entity", "->", "getArrayCopy", "(", ")", ";", "}", ",", "$", "this", "->", "entities", ")", ";", "if", "(", "!", "$", "this", "->", "paginationData", ")", "{", "return", "$", "results", ";", "}", "else", "{", "$", "data", "=", "$", "this", "->", "paginationData", "->", "getArrayCopy", "(", ")", ";", "$", "data", "[", "'results'", "]", "=", "$", "results", ";", "return", "$", "data", ";", "}", "}" ]
Return an array representation of the object Useful for turning the array of entities into a nested array, which is then ready to be JSON encoded in a REST response. @return array
[ "Return", "an", "array", "representation", "of", "the", "object" ]
60c830550491742a077ab063f924e2f0b63825da
https://github.com/synapsestudios/synapse-base/blob/60c830550491742a077ab063f924e2f0b63825da/src/Synapse/Entity/EntityIterator.php#L115-L128
1,792
Koudela/eArc-router
src/Router.php
Router.setAccessControllers
private function setAccessControllers(): void { $this->absolutePathToAccessControllers = []; $route = $this->routingBasePath; foreach ($this->getRealArgs() as $arg) { $route .= $arg . '/'; $path = $route . 'access.php'; if (\is_file($path)) { array_unshift($this->absolutePathToAccessControllers, $path); break; } } }
php
private function setAccessControllers(): void { $this->absolutePathToAccessControllers = []; $route = $this->routingBasePath; foreach ($this->getRealArgs() as $arg) { $route .= $arg . '/'; $path = $route . 'access.php'; if (\is_file($path)) { array_unshift($this->absolutePathToAccessControllers, $path); break; } } }
[ "private", "function", "setAccessControllers", "(", ")", ":", "void", "{", "$", "this", "->", "absolutePathToAccessControllers", "=", "[", "]", ";", "$", "route", "=", "$", "this", "->", "routingBasePath", ";", "foreach", "(", "$", "this", "->", "getRealArgs", "(", ")", "as", "$", "arg", ")", "{", "$", "route", ".=", "$", "arg", ".", "'/'", ";", "$", "path", "=", "$", "route", ".", "'access.php'", ";", "if", "(", "\\", "is_file", "(", "$", "path", ")", ")", "{", "array_unshift", "(", "$", "this", "->", "absolutePathToAccessControllers", ",", "$", "path", ")", ";", "break", ";", "}", "}", "}" ]
Set the access controller closures. @return void
[ "Set", "the", "access", "controller", "closures", "." ]
dd8d48e3283b7aab5111266288d636f071ef9535
https://github.com/Koudela/eArc-router/blob/dd8d48e3283b7aab5111266288d636f071ef9535/src/Router.php#L84-L99
1,793
Koudela/eArc-router
src/Router.php
Router.createRoute
private function createRoute(): void { $this->virtualArgs = []; $this->realArgs = \explode('/', $this->url); do { if ($this->setMainController( $this->routingBasePath . implode('/', $this->realArgs) )) return; array_unshift($this->virtualArgs, array_pop($this->realArgs)); } while (count($this->realArgs) > 0); throw new NoControllerFoundException(); }
php
private function createRoute(): void { $this->virtualArgs = []; $this->realArgs = \explode('/', $this->url); do { if ($this->setMainController( $this->routingBasePath . implode('/', $this->realArgs) )) return; array_unshift($this->virtualArgs, array_pop($this->realArgs)); } while (count($this->realArgs) > 0); throw new NoControllerFoundException(); }
[ "private", "function", "createRoute", "(", ")", ":", "void", "{", "$", "this", "->", "virtualArgs", "=", "[", "]", ";", "$", "this", "->", "realArgs", "=", "\\", "explode", "(", "'/'", ",", "$", "this", "->", "url", ")", ";", "do", "{", "if", "(", "$", "this", "->", "setMainController", "(", "$", "this", "->", "routingBasePath", ".", "implode", "(", "'/'", ",", "$", "this", "->", "realArgs", ")", ")", ")", "return", ";", "array_unshift", "(", "$", "this", "->", "virtualArgs", ",", "array_pop", "(", "$", "this", "->", "realArgs", ")", ")", ";", "}", "while", "(", "count", "(", "$", "this", "->", "realArgs", ")", ">", "0", ")", ";", "throw", "new", "NoControllerFoundException", "(", ")", ";", "}" ]
Calculate the route and route parameters. @throws NoControllerFoundException if no route maps to a main controller @return void
[ "Calculate", "the", "route", "and", "route", "parameters", "." ]
dd8d48e3283b7aab5111266288d636f071ef9535
https://github.com/Koudela/eArc-router/blob/dd8d48e3283b7aab5111266288d636f071ef9535/src/Router.php#L107-L122
1,794
Koudela/eArc-router
src/Router.php
Router.setMainController
private function setMainController(string $route): bool { if (!\is_dir($route)) return false; foreach ($this->requestNames[$this->requestType] as $requestName) { $path = $route . '/' . $requestName; if (\is_file($path)) { $this->absolutePathToMainController = $path; return true; } } return false; }
php
private function setMainController(string $route): bool { if (!\is_dir($route)) return false; foreach ($this->requestNames[$this->requestType] as $requestName) { $path = $route . '/' . $requestName; if (\is_file($path)) { $this->absolutePathToMainController = $path; return true; } } return false; }
[ "private", "function", "setMainController", "(", "string", "$", "route", ")", ":", "bool", "{", "if", "(", "!", "\\", "is_dir", "(", "$", "route", ")", ")", "return", "false", ";", "foreach", "(", "$", "this", "->", "requestNames", "[", "$", "this", "->", "requestType", "]", "as", "$", "requestName", ")", "{", "$", "path", "=", "$", "route", ".", "'/'", ".", "$", "requestName", ";", "if", "(", "\\", "is_file", "(", "$", "path", ")", ")", "{", "$", "this", "->", "absolutePathToMainController", "=", "$", "path", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Set the main controller closure to the most fitting controller. @param string $route @return bool true if a controller was found, false otherwise
[ "Set", "the", "main", "controller", "closure", "to", "the", "most", "fitting", "controller", "." ]
dd8d48e3283b7aab5111266288d636f071ef9535
https://github.com/Koudela/eArc-router/blob/dd8d48e3283b7aab5111266288d636f071ef9535/src/Router.php#L131-L145
1,795
unyx/console
output/formatting/styles/Stack.php
Stack.pop
public function pop(interfaces\Style $searched = null) : interfaces\Style { if (empty($this->styles)) { return $this->default; } if (!isset($searched)) { return array_pop($this->styles); } // Given a specific Style to search for, we need to compare the Styles to find the index at which // the Style resides, so that we can pop off the part of the Stack starting at the index. /* @var interfaces\Style $stackedStyle */ foreach (array_reverse($this->styles, true) as $index => $stackedStyle) { // In order to support nested inline styles, we need to compare identity of the output, // not just of the instances. // @todo Strict equality of the instances may be sufficient depending on how the Formatter gets implemented. if ($searched->apply('') === $stackedStyle->apply('')) { $this->styles = array_slice($this->styles, 0, $index); return $stackedStyle; } } throw new \InvalidArgumentException('Encountered an incorrectly nested formatting style tag'); }
php
public function pop(interfaces\Style $searched = null) : interfaces\Style { if (empty($this->styles)) { return $this->default; } if (!isset($searched)) { return array_pop($this->styles); } // Given a specific Style to search for, we need to compare the Styles to find the index at which // the Style resides, so that we can pop off the part of the Stack starting at the index. /* @var interfaces\Style $stackedStyle */ foreach (array_reverse($this->styles, true) as $index => $stackedStyle) { // In order to support nested inline styles, we need to compare identity of the output, // not just of the instances. // @todo Strict equality of the instances may be sufficient depending on how the Formatter gets implemented. if ($searched->apply('') === $stackedStyle->apply('')) { $this->styles = array_slice($this->styles, 0, $index); return $stackedStyle; } } throw new \InvalidArgumentException('Encountered an incorrectly nested formatting style tag'); }
[ "public", "function", "pop", "(", "interfaces", "\\", "Style", "$", "searched", "=", "null", ")", ":", "interfaces", "\\", "Style", "{", "if", "(", "empty", "(", "$", "this", "->", "styles", ")", ")", "{", "return", "$", "this", "->", "default", ";", "}", "if", "(", "!", "isset", "(", "$", "searched", ")", ")", "{", "return", "array_pop", "(", "$", "this", "->", "styles", ")", ";", "}", "// Given a specific Style to search for, we need to compare the Styles to find the index at which", "// the Style resides, so that we can pop off the part of the Stack starting at the index.", "/* @var interfaces\\Style $stackedStyle */", "foreach", "(", "array_reverse", "(", "$", "this", "->", "styles", ",", "true", ")", "as", "$", "index", "=>", "$", "stackedStyle", ")", "{", "// In order to support nested inline styles, we need to compare identity of the output,", "// not just of the instances.", "// @todo Strict equality of the instances may be sufficient depending on how the Formatter gets implemented.", "if", "(", "$", "searched", "->", "apply", "(", "''", ")", "===", "$", "stackedStyle", "->", "apply", "(", "''", ")", ")", "{", "$", "this", "->", "styles", "=", "array_slice", "(", "$", "this", "->", "styles", ",", "0", ",", "$", "index", ")", ";", "return", "$", "stackedStyle", ";", "}", "}", "throw", "new", "\\", "InvalidArgumentException", "(", "'Encountered an incorrectly nested formatting style tag'", ")", ";", "}" ]
Pops a style from the Stack. @param interfaces\Style $searched An optional, specific Style to pop from the Stack. If it is not the current element in the Stack, the Stack will be sliced and all Styles present after this instance will also be popped off. @return interfaces\Style The popped Style. @throws \InvalidArgumentException When a Style was given but couldn't be found in the Stack.
[ "Pops", "a", "style", "from", "the", "Stack", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/output/formatting/styles/Stack.php#L59-L84
1,796
unyx/console
output/formatting/styles/Stack.php
Stack.current
public function current() : interfaces\Style { return !empty($this->styles) ? end($this->styles) : $this->default; }
php
public function current() : interfaces\Style { return !empty($this->styles) ? end($this->styles) : $this->default; }
[ "public", "function", "current", "(", ")", ":", "interfaces", "\\", "Style", "{", "return", "!", "empty", "(", "$", "this", "->", "styles", ")", "?", "end", "(", "$", "this", "->", "styles", ")", ":", "$", "this", "->", "default", ";", "}" ]
Returns the current, topmost Style in the stack, or the default Style if none is stacked. @return interfaces\Style
[ "Returns", "the", "current", "topmost", "Style", "in", "the", "stack", "or", "the", "default", "Style", "if", "none", "is", "stacked", "." ]
b4a76e08bbb5428b0349c0ec4259a914f81a2957
https://github.com/unyx/console/blob/b4a76e08bbb5428b0349c0ec4259a914f81a2957/output/formatting/styles/Stack.php#L91-L94
1,797
tzurbaev/api-client
src/Commands/GetResourceCommand.php
GetResourceCommand.requestUrl
public function requestUrl(ApiResourceInterface $resource) { $resourcePath = $this->resourcePath().'/'.$this->getResourceId(); return $resource->apiUrl($resourcePath); }
php
public function requestUrl(ApiResourceInterface $resource) { $resourcePath = $this->resourcePath().'/'.$this->getResourceId(); return $resource->apiUrl($resourcePath); }
[ "public", "function", "requestUrl", "(", "ApiResourceInterface", "$", "resource", ")", "{", "$", "resourcePath", "=", "$", "this", "->", "resourcePath", "(", ")", ".", "'/'", ".", "$", "this", "->", "getResourceId", "(", ")", ";", "return", "$", "resource", "->", "apiUrl", "(", "$", "resourcePath", ")", ";", "}" ]
HTTP request URL. @param ApiResourceInterface $resource @return string
[ "HTTP", "request", "URL", "." ]
78cec644c2be7d732f1d826900e22f427de44f3c
https://github.com/tzurbaev/api-client/blob/78cec644c2be7d732f1d826900e22f427de44f3c/src/Commands/GetResourceCommand.php#L81-L86
1,798
aryelgois/utils
src/PublicVendor.php
PublicVendor.postInstall
public static function postInstall(Event $event) { $vendor_dir = $event->getComposer()->getConfig()->get('vendor-dir'); $base_dir = dirname($vendor_dir); $config_file = $base_dir . '/config/public_vendor.json'; $gitignore_file = $base_dir . '/.gitignore'; if (file_exists($config_file)) { $config = json_decode(file_get_contents($config_file), true); if ($config === null) { throw new \RuntimeException('Error loading configuration file'); } /* * Create symbolic links */ foreach ($config['map'] as $map) { if (array_key_exists($map['vendor'], $config['vendors'])) { $destiny = $base_dir . '/' . $config['vendors'][$map['vendor']] . '/' . trim($map['destiny'], '/'); $source = $vendor_dir . '/' . trim($map['source'], '/'); if (!file_exists(dirname($destiny))) { mkdir(dirname($destiny), 0755, true); } if (!file_exists($destiny)) { symlink($source, $destiny); } } else { throw new \RuntimeException('Undefined vendor'); } } /* * Update gitignore */ $gitignore = (file_exists($gitignore_file)) ? file($gitignore_file, FILE_IGNORE_NEW_LINES) : ['/vendor/']; foreach ($config['vendors'] as $vendor_path) { $ignore_path = '/' . trim($vendor_path, '/') . '/'; if (!in_array($ignore_path, $gitignore)) { $gitignore[] = $ignore_path; } } $gitignore_handle = fopen($gitignore_file, 'w'); fwrite($gitignore_handle, implode("\n", $gitignore) . "\n"); fclose($gitignore_handle); } else { throw new \RuntimeException('Configuration file not found'); } }
php
public static function postInstall(Event $event) { $vendor_dir = $event->getComposer()->getConfig()->get('vendor-dir'); $base_dir = dirname($vendor_dir); $config_file = $base_dir . '/config/public_vendor.json'; $gitignore_file = $base_dir . '/.gitignore'; if (file_exists($config_file)) { $config = json_decode(file_get_contents($config_file), true); if ($config === null) { throw new \RuntimeException('Error loading configuration file'); } /* * Create symbolic links */ foreach ($config['map'] as $map) { if (array_key_exists($map['vendor'], $config['vendors'])) { $destiny = $base_dir . '/' . $config['vendors'][$map['vendor']] . '/' . trim($map['destiny'], '/'); $source = $vendor_dir . '/' . trim($map['source'], '/'); if (!file_exists(dirname($destiny))) { mkdir(dirname($destiny), 0755, true); } if (!file_exists($destiny)) { symlink($source, $destiny); } } else { throw new \RuntimeException('Undefined vendor'); } } /* * Update gitignore */ $gitignore = (file_exists($gitignore_file)) ? file($gitignore_file, FILE_IGNORE_NEW_LINES) : ['/vendor/']; foreach ($config['vendors'] as $vendor_path) { $ignore_path = '/' . trim($vendor_path, '/') . '/'; if (!in_array($ignore_path, $gitignore)) { $gitignore[] = $ignore_path; } } $gitignore_handle = fopen($gitignore_file, 'w'); fwrite($gitignore_handle, implode("\n", $gitignore) . "\n"); fclose($gitignore_handle); } else { throw new \RuntimeException('Configuration file not found'); } }
[ "public", "static", "function", "postInstall", "(", "Event", "$", "event", ")", "{", "$", "vendor_dir", "=", "$", "event", "->", "getComposer", "(", ")", "->", "getConfig", "(", ")", "->", "get", "(", "'vendor-dir'", ")", ";", "$", "base_dir", "=", "dirname", "(", "$", "vendor_dir", ")", ";", "$", "config_file", "=", "$", "base_dir", ".", "'/config/public_vendor.json'", ";", "$", "gitignore_file", "=", "$", "base_dir", ".", "'/.gitignore'", ";", "if", "(", "file_exists", "(", "$", "config_file", ")", ")", "{", "$", "config", "=", "json_decode", "(", "file_get_contents", "(", "$", "config_file", ")", ",", "true", ")", ";", "if", "(", "$", "config", "===", "null", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Error loading configuration file'", ")", ";", "}", "/*\n * Create symbolic links\n */", "foreach", "(", "$", "config", "[", "'map'", "]", "as", "$", "map", ")", "{", "if", "(", "array_key_exists", "(", "$", "map", "[", "'vendor'", "]", ",", "$", "config", "[", "'vendors'", "]", ")", ")", "{", "$", "destiny", "=", "$", "base_dir", ".", "'/'", ".", "$", "config", "[", "'vendors'", "]", "[", "$", "map", "[", "'vendor'", "]", "]", ".", "'/'", ".", "trim", "(", "$", "map", "[", "'destiny'", "]", ",", "'/'", ")", ";", "$", "source", "=", "$", "vendor_dir", ".", "'/'", ".", "trim", "(", "$", "map", "[", "'source'", "]", ",", "'/'", ")", ";", "if", "(", "!", "file_exists", "(", "dirname", "(", "$", "destiny", ")", ")", ")", "{", "mkdir", "(", "dirname", "(", "$", "destiny", ")", ",", "0755", ",", "true", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "destiny", ")", ")", "{", "symlink", "(", "$", "source", ",", "$", "destiny", ")", ";", "}", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "'Undefined vendor'", ")", ";", "}", "}", "/*\n * Update gitignore\n */", "$", "gitignore", "=", "(", "file_exists", "(", "$", "gitignore_file", ")", ")", "?", "file", "(", "$", "gitignore_file", ",", "FILE_IGNORE_NEW_LINES", ")", ":", "[", "'/vendor/'", "]", ";", "foreach", "(", "$", "config", "[", "'vendors'", "]", "as", "$", "vendor_path", ")", "{", "$", "ignore_path", "=", "'/'", ".", "trim", "(", "$", "vendor_path", ",", "'/'", ")", ".", "'/'", ";", "if", "(", "!", "in_array", "(", "$", "ignore_path", ",", "$", "gitignore", ")", ")", "{", "$", "gitignore", "[", "]", "=", "$", "ignore_path", ";", "}", "}", "$", "gitignore_handle", "=", "fopen", "(", "$", "gitignore_file", ",", "'w'", ")", ";", "fwrite", "(", "$", "gitignore_handle", ",", "implode", "(", "\"\\n\"", ",", "$", "gitignore", ")", ".", "\"\\n\"", ")", ";", "fclose", "(", "$", "gitignore_handle", ")", ";", "}", "else", "{", "throw", "new", "\\", "RuntimeException", "(", "'Configuration file not found'", ")", ";", "}", "}" ]
Callback for Composer's post-install-cmd It reads a configuration file at base_dir/config/public_vendor.json with the following structure: { "vendors": { vendor_alias: path to vendor directory under base_dir ... }, "map": [ { "source": path to directory under base_dir/vendor "vendor": vendor_alias to be used "destiny": path to symbolic link under vendor } ... ] } Then, it creates symbolic links from source to destiny Additionally, it writes a .gitignore with all vendors listed @param Event $event Composer Script Event @throws \RuntimeException If configuration file is not found @throws \RuntimeException If configuration file could not be loaded @throws \RuntimeException If a map uses an undefined vendor
[ "Callback", "for", "Composer", "s", "post", "-", "install", "-", "cmd" ]
683a4685de166592aadd0fe7ebec828b99f0cbdc
https://github.com/aryelgois/utils/blob/683a4685de166592aadd0fe7ebec828b99f0cbdc/src/PublicVendor.php#L54-L105
1,799
agalbourdin/agl-core
src/Data/File.php
File.getSubPath
public static function getSubPath($pFileName, $pDepth = 3) { if (empty($pFileName)) { return DS; } $levels = array(); for ($i = 0; $i < $pDepth; $i++) { $levels[] = substr($pFileName, $i, 1); } return implode(DS, $levels) . DS; }
php
public static function getSubPath($pFileName, $pDepth = 3) { if (empty($pFileName)) { return DS; } $levels = array(); for ($i = 0; $i < $pDepth; $i++) { $levels[] = substr($pFileName, $i, 1); } return implode(DS, $levels) . DS; }
[ "public", "static", "function", "getSubPath", "(", "$", "pFileName", ",", "$", "pDepth", "=", "3", ")", "{", "if", "(", "empty", "(", "$", "pFileName", ")", ")", "{", "return", "DS", ";", "}", "$", "levels", "=", "array", "(", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "pDepth", ";", "$", "i", "++", ")", "{", "$", "levels", "[", "]", "=", "substr", "(", "$", "pFileName", ",", "$", "i", ",", "1", ")", ";", "}", "return", "implode", "(", "DS", ",", "$", "levels", ")", ".", "DS", ";", "}" ]
Create a path to store files in multiple subdirectories, based on first letters of filename. @param string $pFIleName @param int $pDepth Number of subdirectories @return string
[ "Create", "a", "path", "to", "store", "files", "in", "multiple", "subdirectories", "based", "on", "first", "letters", "of", "filename", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Data/File.php#L22-L35