repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
flowcode/AmulenMediaBundle
src/Flowcode/MediaBundle/Controller/AdminMediaTypeController.php
AdminMediaTypeController.createEditForm
private function createEditForm(MediaType $entity) { $form = $this->createForm(new MediaTypeType(), $entity, array( 'action' => $this->generateUrl('mediatype_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; }
php
private function createEditForm(MediaType $entity) { $form = $this->createForm(new MediaTypeType(), $entity, array( 'action' => $this->generateUrl('mediatype_update', array('id' => $entity->getId())), 'method' => 'PUT', )); $form->add('submit', 'submit', array('label' => 'Update')); return $form; }
[ "private", "function", "createEditForm", "(", "MediaType", "$", "entity", ")", "{", "$", "form", "=", "$", "this", "->", "createForm", "(", "new", "MediaTypeType", "(", ")", ",", "$", "entity", ",", "array", "(", "'action'", "=>", "$", "this", "->", "g...
Creates a form to edit a MediaType entity. @param MediaType $entity The entity @return \Symfony\Component\Form\Form The form
[ "Creates", "a", "form", "to", "edit", "a", "MediaType", "entity", "." ]
3be28720ff108cca1480de609872d29283776643
https://github.com/flowcode/AmulenMediaBundle/blob/3be28720ff108cca1480de609872d29283776643/src/Flowcode/MediaBundle/Controller/AdminMediaTypeController.php#L161-L171
train
bkdotcom/Toolbox
src/FetchUrl.php
FetchUrl.extractHeaders
private function extractHeaders($str) { $this->debug->log(__METHOD__); $this->debug->groupUncollapse(); $headerStart = 0; #$this->debug->log(('top', \substr($return, 0, $this->curlInfo['header_size'])); $headerLenStack = array(); $i = 0; while (true) { $headerEnd = \strpos($str, "\r\n\r\n", $headerStart); $headerLength = $headerEnd - $headerStart; $headers = \substr($str, $headerStart, $headerLength); $headerStart = $headerEnd+4; $headerLenStack[] = \strlen($headers)+4; #$this->debug->log('headers', \str_replace(array("\r","\n"), array('|','|'), $headers)); if (\count($headerLenStack) > $this->curlInfo['redirect_count']) { #$this->debug->log('header_len_stack','['.\implode(',',$header_len_stack).']'); $sum = 0; for ($j=$i; $j>=0; $j--) { $sum += $headerLenStack[$j]; if ($sum == $this->curlInfo['header_size']) { #$this->debug->info('found headers'); break 2; } } } if ($headerEnd === false || $i > 20) { $this->debug->warn('error parsing headers'); break; } $i++; } // $this->debug->log('headers', $headers); return $headers; }
php
private function extractHeaders($str) { $this->debug->log(__METHOD__); $this->debug->groupUncollapse(); $headerStart = 0; #$this->debug->log(('top', \substr($return, 0, $this->curlInfo['header_size'])); $headerLenStack = array(); $i = 0; while (true) { $headerEnd = \strpos($str, "\r\n\r\n", $headerStart); $headerLength = $headerEnd - $headerStart; $headers = \substr($str, $headerStart, $headerLength); $headerStart = $headerEnd+4; $headerLenStack[] = \strlen($headers)+4; #$this->debug->log('headers', \str_replace(array("\r","\n"), array('|','|'), $headers)); if (\count($headerLenStack) > $this->curlInfo['redirect_count']) { #$this->debug->log('header_len_stack','['.\implode(',',$header_len_stack).']'); $sum = 0; for ($j=$i; $j>=0; $j--) { $sum += $headerLenStack[$j]; if ($sum == $this->curlInfo['header_size']) { #$this->debug->info('found headers'); break 2; } } } if ($headerEnd === false || $i > 20) { $this->debug->warn('error parsing headers'); break; } $i++; } // $this->debug->log('headers', $headers); return $headers; }
[ "private", "function", "extractHeaders", "(", "$", "str", ")", "{", "$", "this", "->", "debug", "->", "log", "(", "__METHOD__", ")", ";", "$", "this", "->", "debug", "->", "groupUncollapse", "(", ")", ";", "$", "headerStart", "=", "0", ";", "#$this->de...
for a string containing both headers and content, return the header portion @param string $str headers + content @return string
[ "for", "a", "string", "containing", "both", "headers", "and", "content", "return", "the", "header", "portion" ]
2f9d34fd57bd8382baee4c29aac13a6710e3a994
https://github.com/bkdotcom/Toolbox/blob/2f9d34fd57bd8382baee4c29aac13a6710e3a994/src/FetchUrl.php#L189-L223
train
bkdotcom/Toolbox
src/FetchUrl.php
FetchUrl.curlGetOptions
protected function curlGetOptions($url, $options = array()) { $this->debug->groupCollapsed(__METHOD__); $urlParts = Html::parseUrl($url); $optionsDefault = $this->curlOptionsDefault($url); $options = $this->curlOptionsNormalize($options); // $this->debug->log('optionsDefault', $optionsDefault); $options = ArrayUtil::mergeDeep($optionsDefault, $options); $options['CURLOPT_URL'] = \str_replace(' ', '%20', $options['CURLOPT_URL']); $options['CURLOPT_FOLLOWLOCATION'] = false; // we will follow manually if ($options['verbose']) { $options['CURLOPT_VERBOSE'] = true; /* $options['tempfile'] = tempnam(\sys_get_temp_dir(), 'curl_'); if (\is_writable($options['tempfile'])) { $fh = \fopen($options['tempfile'], 'w+'); $options['CURLOPT_STDERR'] = $fh; } */ $options['CURLINFO_HEADER_OUT'] = false; // https://bugs.php.net/bug.php?id=65348 $options['CURLOPT_STDERR'] = \fopen('php://temp', 'rw'); } if (!empty($options['CURLOPT_PROXY']) && \in_array($urlParts['host'], array('127.0.0.1','localhost'))) { $this->debug->log('not using proxy for localhost'); $options['CURLOPT_PROXY'] = false; // formerly set to null... which no longer works } if (empty($options['CURLOPT_PROXY']) && \getenv('http_proxy')) { $this->debug->log('http_proxy env variable is set.... setting NO_PROXY env variable'); \putenv('NO_PROXY='.$urlParts['host']); } $this->debug->groupEnd(); return $options; }
php
protected function curlGetOptions($url, $options = array()) { $this->debug->groupCollapsed(__METHOD__); $urlParts = Html::parseUrl($url); $optionsDefault = $this->curlOptionsDefault($url); $options = $this->curlOptionsNormalize($options); // $this->debug->log('optionsDefault', $optionsDefault); $options = ArrayUtil::mergeDeep($optionsDefault, $options); $options['CURLOPT_URL'] = \str_replace(' ', '%20', $options['CURLOPT_URL']); $options['CURLOPT_FOLLOWLOCATION'] = false; // we will follow manually if ($options['verbose']) { $options['CURLOPT_VERBOSE'] = true; /* $options['tempfile'] = tempnam(\sys_get_temp_dir(), 'curl_'); if (\is_writable($options['tempfile'])) { $fh = \fopen($options['tempfile'], 'w+'); $options['CURLOPT_STDERR'] = $fh; } */ $options['CURLINFO_HEADER_OUT'] = false; // https://bugs.php.net/bug.php?id=65348 $options['CURLOPT_STDERR'] = \fopen('php://temp', 'rw'); } if (!empty($options['CURLOPT_PROXY']) && \in_array($urlParts['host'], array('127.0.0.1','localhost'))) { $this->debug->log('not using proxy for localhost'); $options['CURLOPT_PROXY'] = false; // formerly set to null... which no longer works } if (empty($options['CURLOPT_PROXY']) && \getenv('http_proxy')) { $this->debug->log('http_proxy env variable is set.... setting NO_PROXY env variable'); \putenv('NO_PROXY='.$urlParts['host']); } $this->debug->groupEnd(); return $options; }
[ "protected", "function", "curlGetOptions", "(", "$", "url", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "this", "->", "debug", "->", "groupCollapsed", "(", "__METHOD__", ")", ";", "$", "urlParts", "=", "Html", "::", "parseUrl", "(", "$"...
Get complete options @param string $url url to fetch @param array $options array o options @return array
[ "Get", "complete", "options" ]
2f9d34fd57bd8382baee4c29aac13a6710e3a994
https://github.com/bkdotcom/Toolbox/blob/2f9d34fd57bd8382baee4c29aac13a6710e3a994/src/FetchUrl.php#L406-L438
train
bkdotcom/Toolbox
src/FetchUrl.php
FetchUrl.curlOptionsDefault
protected function curlOptionsDefault($url) { $this->debug->groupCollapsed(__METHOD__); $opts = array( // 'CURLOPT_VERBOSE' => 1, // 'CURLOPT_STDERR' => fopen(dirname($_SERVER['SCRIPT_FILENAME']).'/stderr.txt','a'), // 'CURLOPT_COOKIEJAR' => 'c:/shazbot.txt', // broken was only grabbing 2 of 3 cookies // 'CURLOPT_COOKIEFILE' => 'c:/shazbot.txt', // 'CURLOPT_CAINFO' => '/usr/local/apache/htdocs/ca-bundle.cert', 'curl_getinfo' => false, // whether to display 'verbose' => false, 'CURLINFO_HEADER_OUT' => true, 'CURLOPT_FOLLOWLOCATION'=> false, // will follow manualy because of the cookie problem 'CURLOPT_HEADER' => true, // return header (to grab cookies n whatnot) 'CURLOPT_IPRESOLVE' => CURL_IPRESOLVE_V4, 'CURLOPT_URL' => $url, 'CURLOPT_HTTPHEADER' => array(), 'CURLOPT_REFERER' => Html::getSelfUrl(array(), array('fullUrl'=>true,'chars'=>false)), 'CURLOPT_RETURNTRANSFER'=> true, // return string rather than echo 'CURLOPT_SSL_VERIFYPEER'=> false, 'CURLOPT_USERAGENT' => !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)', ); $opts = \array_merge($opts, $this->cfg['curl_opts']); $proxy = \getenv('http_proxy'); if ($proxy) { $this->debug->log('http_proxy env var set...setting default PROXY, CURLOPT_PROXYUSERPWD, and PROXYAUTH'); $pup = \parse_url($proxy); $opts['CURLOPT_PROXY'] = $pup['host']; if (!empty($pup['port'])) { $opts['CURLOPT_PROXY'] .= ':'.$pup['port']; } if (!empty($pup['user'])) { $opts['CURLOPT_PROXYUSERPWD'] = $pup['user']; if (!empty($pup['pass'])) { $opts['CURLOPT_PROXYUSERPWD'] .= ':'.$pup['pass']; } } $opts['CURLOPT_PROXYAUTH'] = CURLAUTH_BASIC; // | CURLAUTH_NTLM; } // $this->debug->log('opts', $opts); $this->debug->groupEnd(); return $opts; }
php
protected function curlOptionsDefault($url) { $this->debug->groupCollapsed(__METHOD__); $opts = array( // 'CURLOPT_VERBOSE' => 1, // 'CURLOPT_STDERR' => fopen(dirname($_SERVER['SCRIPT_FILENAME']).'/stderr.txt','a'), // 'CURLOPT_COOKIEJAR' => 'c:/shazbot.txt', // broken was only grabbing 2 of 3 cookies // 'CURLOPT_COOKIEFILE' => 'c:/shazbot.txt', // 'CURLOPT_CAINFO' => '/usr/local/apache/htdocs/ca-bundle.cert', 'curl_getinfo' => false, // whether to display 'verbose' => false, 'CURLINFO_HEADER_OUT' => true, 'CURLOPT_FOLLOWLOCATION'=> false, // will follow manualy because of the cookie problem 'CURLOPT_HEADER' => true, // return header (to grab cookies n whatnot) 'CURLOPT_IPRESOLVE' => CURL_IPRESOLVE_V4, 'CURLOPT_URL' => $url, 'CURLOPT_HTTPHEADER' => array(), 'CURLOPT_REFERER' => Html::getSelfUrl(array(), array('fullUrl'=>true,'chars'=>false)), 'CURLOPT_RETURNTRANSFER'=> true, // return string rather than echo 'CURLOPT_SSL_VERIFYPEER'=> false, 'CURLOPT_USERAGENT' => !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)', ); $opts = \array_merge($opts, $this->cfg['curl_opts']); $proxy = \getenv('http_proxy'); if ($proxy) { $this->debug->log('http_proxy env var set...setting default PROXY, CURLOPT_PROXYUSERPWD, and PROXYAUTH'); $pup = \parse_url($proxy); $opts['CURLOPT_PROXY'] = $pup['host']; if (!empty($pup['port'])) { $opts['CURLOPT_PROXY'] .= ':'.$pup['port']; } if (!empty($pup['user'])) { $opts['CURLOPT_PROXYUSERPWD'] = $pup['user']; if (!empty($pup['pass'])) { $opts['CURLOPT_PROXYUSERPWD'] .= ':'.$pup['pass']; } } $opts['CURLOPT_PROXYAUTH'] = CURLAUTH_BASIC; // | CURLAUTH_NTLM; } // $this->debug->log('opts', $opts); $this->debug->groupEnd(); return $opts; }
[ "protected", "function", "curlOptionsDefault", "(", "$", "url", ")", "{", "$", "this", "->", "debug", "->", "groupCollapsed", "(", "__METHOD__", ")", ";", "$", "opts", "=", "array", "(", "// 'CURLOPT_VERBOSE' => 1,", "// 'CURLOPT_STDERR' => fopen(dirname($_SERV...
Get defautl cURL options @param string $url url @return array
[ "Get", "defautl", "cURL", "options" ]
2f9d34fd57bd8382baee4c29aac13a6710e3a994
https://github.com/bkdotcom/Toolbox/blob/2f9d34fd57bd8382baee4c29aac13a6710e3a994/src/FetchUrl.php#L447-L491
train
bkdotcom/Toolbox
src/FetchUrl.php
FetchUrl.curlGetReturn
protected function curlGetReturn() { $follow = !isset($this->optionsPassed['CURLOPT_FOLLOWLOCATION']) || $this->optionsPassed['CURLOPT_FOLLOWLOCATION']; $headers = $this->fetchResponse['headers']; if ($follow && isset($headers['Location'])) { // follow location $location = Html::getAbsUrl($this->options['CURLOPT_URL'], $headers['Location']); $this->debug->info('redirect', $location); if (\count(\array_keys($this->redirectHistory, $location)) > 1) { // a -> b -> a is OK $this->debug->warn('redirect loop', $this->redirectHistory); $return = false; } else { if (\in_array($headers['Return-Code'], array(302,303))) { $this->optionsPassed['CURLOPT_POSTFIELDS'] = null; $this->optionsPassed['post'] = null; } $this->optionsPassed['cookies'] = $this->fetchResponse['cookies']; unset($this->optionsPassed['url']); // url used by scrape() unset($this->optionsPassed['CURLOPT_URL']); $return = $this->fetchCurl($location, $this->optionsPassed); } } else { $this->redirectHistory = array(); if ($headers && $headers['Return-Code'] != 200 && $follow) { #$this->debug->log('fetchResponse', $this->fetchResponse); $return = false; } else { if (!empty($headers['Content-Encoding']) && $headers['Content-Encoding'] == 'gzip') { $this->debug->info('decompressing gzip content'); $this->fetchResponse['body'] = Gzip::decompressString($this->fetchResponse['body']); } $return = $this->fetchResponse; } } return $return; }
php
protected function curlGetReturn() { $follow = !isset($this->optionsPassed['CURLOPT_FOLLOWLOCATION']) || $this->optionsPassed['CURLOPT_FOLLOWLOCATION']; $headers = $this->fetchResponse['headers']; if ($follow && isset($headers['Location'])) { // follow location $location = Html::getAbsUrl($this->options['CURLOPT_URL'], $headers['Location']); $this->debug->info('redirect', $location); if (\count(\array_keys($this->redirectHistory, $location)) > 1) { // a -> b -> a is OK $this->debug->warn('redirect loop', $this->redirectHistory); $return = false; } else { if (\in_array($headers['Return-Code'], array(302,303))) { $this->optionsPassed['CURLOPT_POSTFIELDS'] = null; $this->optionsPassed['post'] = null; } $this->optionsPassed['cookies'] = $this->fetchResponse['cookies']; unset($this->optionsPassed['url']); // url used by scrape() unset($this->optionsPassed['CURLOPT_URL']); $return = $this->fetchCurl($location, $this->optionsPassed); } } else { $this->redirectHistory = array(); if ($headers && $headers['Return-Code'] != 200 && $follow) { #$this->debug->log('fetchResponse', $this->fetchResponse); $return = false; } else { if (!empty($headers['Content-Encoding']) && $headers['Content-Encoding'] == 'gzip') { $this->debug->info('decompressing gzip content'); $this->fetchResponse['body'] = Gzip::decompressString($this->fetchResponse['body']); } $return = $this->fetchResponse; } } return $return; }
[ "protected", "function", "curlGetReturn", "(", ")", "{", "$", "follow", "=", "!", "isset", "(", "$", "this", "->", "optionsPassed", "[", "'CURLOPT_FOLLOWLOCATION'", "]", ")", "||", "$", "this", "->", "optionsPassed", "[", "'CURLOPT_FOLLOWLOCATION'", "]", ";", ...
Build return value from fetchResponse @return array|false
[ "Build", "return", "value", "from", "fetchResponse" ]
2f9d34fd57bd8382baee4c29aac13a6710e3a994
https://github.com/bkdotcom/Toolbox/blob/2f9d34fd57bd8382baee4c29aac13a6710e3a994/src/FetchUrl.php#L629-L665
train
fabsgc/framework
Core/Asset/Asset.php
Asset._setFile
protected function _setFile($path) { $this->_name .= $path; $this->_data['' . $path . ''] = file_get_contents($path); if ($this->_type == 'css') { $this->_currentPath = dirname($path) . '/'; $this->_data['' . $path . ''] = preg_replace_callback('`url\((.*)\)`isU', ['Gcs\Framework\Core\Asset\Asset', '_parseRelativePathCssUrl'], $this->_data['' . $path . '']); $this->_data['' . $path . ''] = preg_replace_callback('`src=\'(.*)\'`isU', ['Gcs\Framework\Core\Asset\Asset', '_parseRelativePathCssSrc'], $this->_data['' . $path . '']); } }
php
protected function _setFile($path) { $this->_name .= $path; $this->_data['' . $path . ''] = file_get_contents($path); if ($this->_type == 'css') { $this->_currentPath = dirname($path) . '/'; $this->_data['' . $path . ''] = preg_replace_callback('`url\((.*)\)`isU', ['Gcs\Framework\Core\Asset\Asset', '_parseRelativePathCssUrl'], $this->_data['' . $path . '']); $this->_data['' . $path . ''] = preg_replace_callback('`src=\'(.*)\'`isU', ['Gcs\Framework\Core\Asset\Asset', '_parseRelativePathCssSrc'], $this->_data['' . $path . '']); } }
[ "protected", "function", "_setFile", "(", "$", "path", ")", "{", "$", "this", "->", "_name", ".=", "$", "path", ";", "$", "this", "->", "_data", "[", "''", ".", "$", "path", ".", "''", "]", "=", "file_get_contents", "(", "$", "path", ")", ";", "i...
configure one file @access public @param $path string @return void @since 3.0 @package Gcs\Framework\Core\Asset
[ "configure", "one", "file" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Asset/Asset.php#L172-L181
train
fabsgc/framework
Core/Asset/Asset.php
Asset._setDir
protected function _setDir($path) { if ($handle = opendir($path)) { while (false !== ($entry = readdir($handle))) { $extension = explode('.', basename($entry)); $ext = $extension[count($extension) - 1]; if ($ext == $this->_type) { $this->_setFile($path . $entry); } } closedir($handle); } }
php
protected function _setDir($path) { if ($handle = opendir($path)) { while (false !== ($entry = readdir($handle))) { $extension = explode('.', basename($entry)); $ext = $extension[count($extension) - 1]; if ($ext == $this->_type) { $this->_setFile($path . $entry); } } closedir($handle); } }
[ "protected", "function", "_setDir", "(", "$", "path", ")", "{", "if", "(", "$", "handle", "=", "opendir", "(", "$", "path", ")", ")", "{", "while", "(", "false", "!==", "(", "$", "entry", "=", "readdir", "(", "$", "handle", ")", ")", ")", "{", ...
configure a directory @access public @param $path string @return void @since 3.0 @package Gcs\Framework\Core\Asset
[ "configure", "a", "directory" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Asset/Asset.php#L192-L205
train
fabsgc/framework
Core/Asset/Asset.php
Asset._parseRelativePathCss
protected function _parseRelativePathCss($m) { /** * We take the page. Each time we have a '../' in a path file in the css, we drop a folder of the parent file. Zxample : * css file : css/dossier/truc/test.css * image file in css : ../../test.png * we have two ../ so we delete two folder : css/test/test.png */ $pathReplace = ''; if (!preg_match('~(?:f|ht)tps?://~i', $m[1]) && !preg_match('~(data)~i', $m[1])) { //we clear the '/' at the beginning $m[1] = preg_replace("#^/#isU", '', $m[1]); $m[1] = str_replace('"', '', $m[1]); $m[1] = str_replace("'", '', $m[1]); $this->_currentPath = preg_replace("#^/#isU", '', $this->_currentPath); //on count the number of '../' $numberParentDir = substr_count($m[1], '../'); if ($numberParentDir > 0) { for ($i = 0; $i < $numberParentDir; $i++) { $pathReplace .= '(.[^\/]+)\/'; } $pathReplace .= '$'; $newCurrentPath = preg_replace('#' . $pathReplace . '#isU', '/', $this->_currentPath); $m[1] = preg_replace('#\.\./#isU', '', $m[1]); if ($newCurrentPath != $this->_currentPath) { $m[1] = $newCurrentPath . $m[1]; } else if (!preg_match('#^' . preg_quote($newCurrentPath) . '#isU', $m[1])) { if (!preg_match('#^/asset#isU', $m[1]) && !preg_match('#^asset#isU', $m[1])) { $m[1] = $newCurrentPath . $m[1]; } } } if (!preg_match('#^/#isU', $m[1])) { $m[1] = '/' . $m[1]; } if (Config::config()['user']['output']['https']) { return 'https://' . str_replace('//', '/', $_SERVER['HTTP_HOST'] . '/' . Config::config()['user']['framework']['folder'] . $m[1]); } else { return 'http://' . str_replace('//', '/', $_SERVER['HTTP_HOST'] . '/' . Config::config()['user']['framework']['folder'] . $m[1]); } } else { return $m[1]; } }
php
protected function _parseRelativePathCss($m) { /** * We take the page. Each time we have a '../' in a path file in the css, we drop a folder of the parent file. Zxample : * css file : css/dossier/truc/test.css * image file in css : ../../test.png * we have two ../ so we delete two folder : css/test/test.png */ $pathReplace = ''; if (!preg_match('~(?:f|ht)tps?://~i', $m[1]) && !preg_match('~(data)~i', $m[1])) { //we clear the '/' at the beginning $m[1] = preg_replace("#^/#isU", '', $m[1]); $m[1] = str_replace('"', '', $m[1]); $m[1] = str_replace("'", '', $m[1]); $this->_currentPath = preg_replace("#^/#isU", '', $this->_currentPath); //on count the number of '../' $numberParentDir = substr_count($m[1], '../'); if ($numberParentDir > 0) { for ($i = 0; $i < $numberParentDir; $i++) { $pathReplace .= '(.[^\/]+)\/'; } $pathReplace .= '$'; $newCurrentPath = preg_replace('#' . $pathReplace . '#isU', '/', $this->_currentPath); $m[1] = preg_replace('#\.\./#isU', '', $m[1]); if ($newCurrentPath != $this->_currentPath) { $m[1] = $newCurrentPath . $m[1]; } else if (!preg_match('#^' . preg_quote($newCurrentPath) . '#isU', $m[1])) { if (!preg_match('#^/asset#isU', $m[1]) && !preg_match('#^asset#isU', $m[1])) { $m[1] = $newCurrentPath . $m[1]; } } } if (!preg_match('#^/#isU', $m[1])) { $m[1] = '/' . $m[1]; } if (Config::config()['user']['output']['https']) { return 'https://' . str_replace('//', '/', $_SERVER['HTTP_HOST'] . '/' . Config::config()['user']['framework']['folder'] . $m[1]); } else { return 'http://' . str_replace('//', '/', $_SERVER['HTTP_HOST'] . '/' . Config::config()['user']['framework']['folder'] . $m[1]); } } else { return $m[1]; } }
[ "protected", "function", "_parseRelativePathCss", "(", "$", "m", ")", "{", "/**\n * We take the page. Each time we have a '../' in a path file in the css, we drop a folder of the parent file. Zxample :\n * css file : css/dossier/truc/test.css\n * image file in css : ../.....
correct wrong links @access public @param $m array @return string @since 3.0 @package Gcs\Framework\Core\Asset
[ "correct", "wrong", "links" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Asset/Asset.php#L242-L295
train
fabsgc/framework
Core/Asset/Asset.php
Asset._compress
protected function _compress() { //$before = '(?<=[:(, ])'; //$after = '(?=[ ,);}])'; //$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)'; foreach ($this->_data as $value) { $this->_concatContent .= $value; } if ($this->_type == 'css') { $this->_concatContent = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $this->_concatContent); $this->_concatContent = str_replace(': ', ':', $this->_concatContent); $this->_concatContent = str_replace(["\r\n", "\r", "\n", "\t", ' ', ' ', ' '], '', $this->_concatContent); } }
php
protected function _compress() { //$before = '(?<=[:(, ])'; //$after = '(?=[ ,);}])'; //$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)'; foreach ($this->_data as $value) { $this->_concatContent .= $value; } if ($this->_type == 'css') { $this->_concatContent = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $this->_concatContent); $this->_concatContent = str_replace(': ', ':', $this->_concatContent); $this->_concatContent = str_replace(["\r\n", "\r", "\n", "\t", ' ', ' ', ' '], '', $this->_concatContent); } }
[ "protected", "function", "_compress", "(", ")", "{", "//$before = '(?<=[:(, ])';", "//$after = '(?=[ ,);}])';", "//$units = '(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|vm)';", "foreach", "(", "$", "this", "->", "_data", "as", "$", "value", ")", "{", "$", "this", "-...
concatenate parser content @access public @return void @since 3.0 @package Gcs\Framework\Core\Asset
[ "concatenate", "parser", "content" ]
45e58182aba6a3c6381970a1fd3c17662cff2168
https://github.com/fabsgc/framework/blob/45e58182aba6a3c6381970a1fd3c17662cff2168/Core/Asset/Asset.php#L305-L319
train
Ingewikkeld/oauth-server-bundle
src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php
Client.getResource
public function getResource($identifier) { /** @var ClientEntity $client */ $client = $this->getRepository()->findOneBy(array('id' => $identifier)); if (!$client) { throw new NotFoundHttpException( $this->translator->trans('error.client_not_found', array('%id%' => $identifier)) ); } return $this->createResourceFromClient($client); }
php
public function getResource($identifier) { /** @var ClientEntity $client */ $client = $this->getRepository()->findOneBy(array('id' => $identifier)); if (!$client) { throw new NotFoundHttpException( $this->translator->trans('error.client_not_found', array('%id%' => $identifier)) ); } return $this->createResourceFromClient($client); }
[ "public", "function", "getResource", "(", "$", "identifier", ")", "{", "/** @var ClientEntity $client */", "$", "client", "=", "$", "this", "->", "getRepository", "(", ")", "->", "findOneBy", "(", "array", "(", "'id'", "=>", "$", "identifier", ")", ")", ";",...
Returns the oAuth2 Client with the given identifier. @param string|integer $identifier @throws NotFoundHttpException if the client could not be found. @return Resource
[ "Returns", "the", "oAuth2", "Client", "with", "the", "given", "identifier", "." ]
b5957414e57aeb2223d3b403aff4b108c10fd5cc
https://github.com/Ingewikkeld/oauth-server-bundle/blob/b5957414e57aeb2223d3b403aff4b108c10fd5cc/src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php#L60-L71
train
Ingewikkeld/oauth-server-bundle
src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php
Client.getCollection
public function getCollection(array $options = array()) { /** @var ClientEntity[] $collection */ $collection = $this->getRepository()->findAll(); $resource = new Resource($this->generateBrowseUrl(), array('count' => count($collection))); foreach ($collection as $element) { $resource->setEmbedded('client', $this->createResourceFromClient($element)); } return $resource; }
php
public function getCollection(array $options = array()) { /** @var ClientEntity[] $collection */ $collection = $this->getRepository()->findAll(); $resource = new Resource($this->generateBrowseUrl(), array('count' => count($collection))); foreach ($collection as $element) { $resource->setEmbedded('client', $this->createResourceFromClient($element)); } return $resource; }
[ "public", "function", "getCollection", "(", "array", "$", "options", "=", "array", "(", ")", ")", "{", "/** @var ClientEntity[] $collection */", "$", "collection", "=", "$", "this", "->", "getRepository", "(", ")", "->", "findAll", "(", ")", ";", "$", "resou...
Returns all clients in a single collection resource. @param string[] $options @return Resource
[ "Returns", "all", "clients", "in", "a", "single", "collection", "resource", "." ]
b5957414e57aeb2223d3b403aff4b108c10fd5cc
https://github.com/Ingewikkeld/oauth-server-bundle/blob/b5957414e57aeb2223d3b403aff4b108c10fd5cc/src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php#L80-L91
train
Ingewikkeld/oauth-server-bundle
src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php
Client.delete
public function delete(Resource $resource) { $data = $resource->toArray(); $client = $this->getRepository()->findOneBy(array('id' => $data['id'])); if (!$client) { $errorMessage = $this->translator->trans('error.client_not_found', array('%id%' => $data['id'])); throw new NotFoundHttpException($errorMessage); } $this->entityManager->remove($client); }
php
public function delete(Resource $resource) { $data = $resource->toArray(); $client = $this->getRepository()->findOneBy(array('id' => $data['id'])); if (!$client) { $errorMessage = $this->translator->trans('error.client_not_found', array('%id%' => $data['id'])); throw new NotFoundHttpException($errorMessage); } $this->entityManager->remove($client); }
[ "public", "function", "delete", "(", "Resource", "$", "resource", ")", "{", "$", "data", "=", "$", "resource", "->", "toArray", "(", ")", ";", "$", "client", "=", "$", "this", "->", "getRepository", "(", ")", "->", "findOneBy", "(", "array", "(", "'i...
Removes the Client from the database. @param \Hal\Resource $resource @throws NotFoundHttpException if no client with the given id could be found. @return void
[ "Removes", "the", "Client", "from", "the", "database", "." ]
b5957414e57aeb2223d3b403aff4b108c10fd5cc
https://github.com/Ingewikkeld/oauth-server-bundle/blob/b5957414e57aeb2223d3b403aff4b108c10fd5cc/src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php#L151-L162
train
Ingewikkeld/oauth-server-bundle
src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php
Client.createResourceFromClient
protected function createResourceFromClient(ClientEntity $client) { $resource = new Resource( $this->generateReadUrl($client->getId()), array( 'id' => $client->getId(), 'publicId' => $client->getPublicId(), 'secret' => $client->getSecret(), 'redirectUris' => $client->getRedirectUris(), 'grants' => $client->getAllowedGrantTypes(), ) ); return $resource; }
php
protected function createResourceFromClient(ClientEntity $client) { $resource = new Resource( $this->generateReadUrl($client->getId()), array( 'id' => $client->getId(), 'publicId' => $client->getPublicId(), 'secret' => $client->getSecret(), 'redirectUris' => $client->getRedirectUris(), 'grants' => $client->getAllowedGrantTypes(), ) ); return $resource; }
[ "protected", "function", "createResourceFromClient", "(", "ClientEntity", "$", "client", ")", "{", "$", "resource", "=", "new", "Resource", "(", "$", "this", "->", "generateReadUrl", "(", "$", "client", "->", "getId", "(", ")", ")", ",", "array", "(", "'id...
Creates a new resource from the given Client entity. @param ClientEntity $client @return Resource
[ "Creates", "a", "new", "resource", "from", "the", "given", "Client", "entity", "." ]
b5957414e57aeb2223d3b403aff4b108c10fd5cc
https://github.com/Ingewikkeld/oauth-server-bundle/blob/b5957414e57aeb2223d3b403aff4b108c10fd5cc/src/Ingewikkeld/Rest/OAuthServerBundle/ResourceMapper/Client.php#L230-L244
train
vgrdominik/VGRElasticsearchHttpFoundationBundle
Security/Http/Firewall/ElasticsearchContextListener.php
ElasticsearchContextListener.handle
public function handle(GetResponseEvent $event) { if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) { $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse')); $this->registered = true; } $request = $event->getRequest(); $session = $request->getSession(); /*$sessionId = $session->getId(); if(empty($sessionId)) { $session = null; }*/ if (null === $session || null === $token = $session->get('_security_'.$this->contextKey)) { $this->context->setToken(null); return; } $token = unserialize($token); if (null !== $this->logger) { $this->logger->debug('Read SecurityContext from the session'); } if ($token instanceof TokenInterface) { $token = $this->refreshUser($token); } elseif (null !== $token) { if (null !== $this->logger) { $this->logger->warning(sprintf('Session includes a "%s" where a security token is expected', is_object($token) ? get_class($token) : gettype($token))); } $token = null; } $this->context->setToken($token); }
php
public function handle(GetResponseEvent $event) { if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) { $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse')); $this->registered = true; } $request = $event->getRequest(); $session = $request->getSession(); /*$sessionId = $session->getId(); if(empty($sessionId)) { $session = null; }*/ if (null === $session || null === $token = $session->get('_security_'.$this->contextKey)) { $this->context->setToken(null); return; } $token = unserialize($token); if (null !== $this->logger) { $this->logger->debug('Read SecurityContext from the session'); } if ($token instanceof TokenInterface) { $token = $this->refreshUser($token); } elseif (null !== $token) { if (null !== $this->logger) { $this->logger->warning(sprintf('Session includes a "%s" where a security token is expected', is_object($token) ? get_class($token) : gettype($token))); } $token = null; } $this->context->setToken($token); }
[ "public", "function", "handle", "(", "GetResponseEvent", "$", "event", ")", "{", "if", "(", "!", "$", "this", "->", "registered", "&&", "null", "!==", "$", "this", "->", "dispatcher", "&&", "$", "event", "->", "isMasterRequest", "(", ")", ")", "{", "$"...
Reads the SecurityContext from the session. @param GetResponseEvent $event A GetResponseEvent instance
[ "Reads", "the", "SecurityContext", "from", "the", "session", "." ]
06fad4b3619bfaf481b3141800d0b9eb5ae45b07
https://github.com/vgrdominik/VGRElasticsearchHttpFoundationBundle/blob/06fad4b3619bfaf481b3141800d0b9eb5ae45b07/Security/Http/Firewall/ElasticsearchContextListener.php#L91-L129
train
vgrdominik/VGRElasticsearchHttpFoundationBundle
Security/Http/Firewall/ElasticsearchContextListener.php
ElasticsearchContextListener.onKernelResponse
public function onKernelResponse(FilterResponseEvent $event) { if (!$event->isMasterRequest()) { return; } if (!$event->getRequest()->hasSession()) { return; } if (null !== $this->logger) { $this->logger->debug('Write SecurityContext in the session'); } $request = $event->getRequest(); $session = $request->getSession(); if (null === $session) { return; } if ((null === $token = $this->context->getToken()) || ($token instanceof AnonymousToken)) { if ($request->hasPreviousSession()) { $session->remove('_security_'.$this->contextKey); } } else { $session->set('_security_'.$this->contextKey, serialize($token)); } }
php
public function onKernelResponse(FilterResponseEvent $event) { if (!$event->isMasterRequest()) { return; } if (!$event->getRequest()->hasSession()) { return; } if (null !== $this->logger) { $this->logger->debug('Write SecurityContext in the session'); } $request = $event->getRequest(); $session = $request->getSession(); if (null === $session) { return; } if ((null === $token = $this->context->getToken()) || ($token instanceof AnonymousToken)) { if ($request->hasPreviousSession()) { $session->remove('_security_'.$this->contextKey); } } else { $session->set('_security_'.$this->contextKey, serialize($token)); } }
[ "public", "function", "onKernelResponse", "(", "FilterResponseEvent", "$", "event", ")", "{", "if", "(", "!", "$", "event", "->", "isMasterRequest", "(", ")", ")", "{", "return", ";", "}", "if", "(", "!", "$", "event", "->", "getRequest", "(", ")", "->...
Writes the SecurityContext to the session. @param FilterResponseEvent $event A FilterResponseEvent instance
[ "Writes", "the", "SecurityContext", "to", "the", "session", "." ]
06fad4b3619bfaf481b3141800d0b9eb5ae45b07
https://github.com/vgrdominik/VGRElasticsearchHttpFoundationBundle/blob/06fad4b3619bfaf481b3141800d0b9eb5ae45b07/Security/Http/Firewall/ElasticsearchContextListener.php#L136-L164
train
vgrdominik/VGRElasticsearchHttpFoundationBundle
Security/Http/Firewall/ElasticsearchContextListener.php
ElasticsearchContextListener.refreshUser
private function refreshUser(TokenInterface $token) { $user = $token->getUser(); if (!$user instanceof UserInterface) { return $token; } if (null !== $this->logger) { $this->logger->debug(sprintf('Reloading user from user provider.')); } foreach ($this->userProviders as $provider) { try { $refreshedUser = $provider->refreshUser($user); $token->setUser($refreshedUser); if (null !== $this->logger) { $this->logger->debug(sprintf('Username "%s" was reloaded from user provider.', $refreshedUser->getUsername())); } return $token; } catch (UnsupportedUserException $unsupported) { // let's try the next user provider } catch (UsernameNotFoundException $notFound) { if (null !== $this->logger) { $this->logger->warning(sprintf('Username "%s" could not be found.', $notFound->getUsername())); } return; } } throw new \RuntimeException(sprintf('There is no user provider for user "%s".', get_class($user))); }
php
private function refreshUser(TokenInterface $token) { $user = $token->getUser(); if (!$user instanceof UserInterface) { return $token; } if (null !== $this->logger) { $this->logger->debug(sprintf('Reloading user from user provider.')); } foreach ($this->userProviders as $provider) { try { $refreshedUser = $provider->refreshUser($user); $token->setUser($refreshedUser); if (null !== $this->logger) { $this->logger->debug(sprintf('Username "%s" was reloaded from user provider.', $refreshedUser->getUsername())); } return $token; } catch (UnsupportedUserException $unsupported) { // let's try the next user provider } catch (UsernameNotFoundException $notFound) { if (null !== $this->logger) { $this->logger->warning(sprintf('Username "%s" could not be found.', $notFound->getUsername())); } return; } } throw new \RuntimeException(sprintf('There is no user provider for user "%s".', get_class($user))); }
[ "private", "function", "refreshUser", "(", "TokenInterface", "$", "token", ")", "{", "$", "user", "=", "$", "token", "->", "getUser", "(", ")", ";", "if", "(", "!", "$", "user", "instanceof", "UserInterface", ")", "{", "return", "$", "token", ";", "}",...
Refreshes the user by reloading it from the user provider @param TokenInterface $token @return TokenInterface|null @throws \RuntimeException
[ "Refreshes", "the", "user", "by", "reloading", "it", "from", "the", "user", "provider" ]
06fad4b3619bfaf481b3141800d0b9eb5ae45b07
https://github.com/vgrdominik/VGRElasticsearchHttpFoundationBundle/blob/06fad4b3619bfaf481b3141800d0b9eb5ae45b07/Security/Http/Firewall/ElasticsearchContextListener.php#L175-L208
train
bishopb/vanilla
applications/vanilla/controllers/class.discussionscontroller.php
DiscussionsController.Table
public function Table($Page = '0') { if ($this->SyndicationMethod == SYNDICATION_NONE) $this->View = 'table'; $this->Index($Page); }
php
public function Table($Page = '0') { if ($this->SyndicationMethod == SYNDICATION_NONE) $this->View = 'table'; $this->Index($Page); }
[ "public", "function", "Table", "(", "$", "Page", "=", "'0'", ")", "{", "if", "(", "$", "this", "->", "SyndicationMethod", "==", "SYNDICATION_NONE", ")", "$", "this", "->", "View", "=", "'table'", ";", "$", "this", "->", "Index", "(", "$", "Page", ")"...
"Table" layout for discussions. Mimics more traditional forum discussion layout. @param int $Page Multiplied by PerPage option to determine offset.
[ "Table", "layout", "for", "discussions", ".", "Mimics", "more", "traditional", "forum", "discussion", "layout", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/vanilla/controllers/class.discussionscontroller.php#L58-L62
train
bishopb/vanilla
applications/vanilla/controllers/class.discussionscontroller.php
DiscussionsController.Bookmarked
public function Bookmarked($Page = '0') { $this->Permission('Garden.SignIn.Allow'); Gdn_Theme::Section('DiscussionList'); // Figure out which discussions layout to choose (Defined on "Homepage" settings page). $Layout = C('Vanilla.Discussions.Layout'); switch($Layout) { case 'table': if ($this->SyndicationMethod == SYNDICATION_NONE) $this->View = 'table'; break; default: $this->View = 'index'; break; } // Determine offset from $Page list($Page, $Limit) = OffsetLimit($Page, C('Vanilla.Discussions.PerPage', 30)); $this->CanonicalUrl(Url(ConcatSep('/', 'discussions', 'bookmarked', PageNumber($Page, $Limit, TRUE, FALSE)), TRUE)); // Validate $Page if (!is_numeric($Page) || $Page < 0) $Page = 0; $DiscussionModel = new DiscussionModel(); $Wheres = array( 'w.Bookmarked' => '1', 'w.UserID' => Gdn::Session()->UserID ); $this->DiscussionData = $DiscussionModel->Get($Page, $Limit, $Wheres); $this->SetData('Discussions', $this->DiscussionData); $CountDiscussions = $DiscussionModel->GetCount($Wheres); $this->SetData('CountDiscussions', $CountDiscussions); $this->Category = FALSE; $this->SetJson('Loading', $Page . ' to ' . $Limit); // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->EventArguments['PagerType'] = 'Pager'; $this->FireEvent('BeforeBuildBookmarkedPager'); $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this); $this->Pager->ClientID = 'Pager'; $this->Pager->Configure( $Page, $Limit, $CountDiscussions, 'discussions/bookmarked/%1$s' ); if (!$this->Data('_PagerUrl')) $this->SetData('_PagerUrl', 'discussions/bookmarked/{Page}'); $this->SetData('_Page', $Page); $this->SetData('_Limit', $Limit); $this->FireEvent('AfterBuildBookmarkedPager'); // Deliver JSON data if necessary if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->SetJson('LessRow', $this->Pager->ToString('less')); $this->SetJson('MoreRow', $this->Pager->ToString('more')); $this->View = 'discussions'; } // Add modules $this->AddModule('DiscussionFilterModule'); $this->AddModule('NewDiscussionModule'); $this->AddModule('CategoriesModule'); // Render default view (discussions/bookmarked.php) $this->SetData('Title', T('My Bookmarks')); $this->SetData('Breadcrumbs', array(array('Name' => T('My Bookmarks'), 'Url' => '/discussions/bookmarked'))); $this->Render(); }
php
public function Bookmarked($Page = '0') { $this->Permission('Garden.SignIn.Allow'); Gdn_Theme::Section('DiscussionList'); // Figure out which discussions layout to choose (Defined on "Homepage" settings page). $Layout = C('Vanilla.Discussions.Layout'); switch($Layout) { case 'table': if ($this->SyndicationMethod == SYNDICATION_NONE) $this->View = 'table'; break; default: $this->View = 'index'; break; } // Determine offset from $Page list($Page, $Limit) = OffsetLimit($Page, C('Vanilla.Discussions.PerPage', 30)); $this->CanonicalUrl(Url(ConcatSep('/', 'discussions', 'bookmarked', PageNumber($Page, $Limit, TRUE, FALSE)), TRUE)); // Validate $Page if (!is_numeric($Page) || $Page < 0) $Page = 0; $DiscussionModel = new DiscussionModel(); $Wheres = array( 'w.Bookmarked' => '1', 'w.UserID' => Gdn::Session()->UserID ); $this->DiscussionData = $DiscussionModel->Get($Page, $Limit, $Wheres); $this->SetData('Discussions', $this->DiscussionData); $CountDiscussions = $DiscussionModel->GetCount($Wheres); $this->SetData('CountDiscussions', $CountDiscussions); $this->Category = FALSE; $this->SetJson('Loading', $Page . ' to ' . $Limit); // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->EventArguments['PagerType'] = 'Pager'; $this->FireEvent('BeforeBuildBookmarkedPager'); $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this); $this->Pager->ClientID = 'Pager'; $this->Pager->Configure( $Page, $Limit, $CountDiscussions, 'discussions/bookmarked/%1$s' ); if (!$this->Data('_PagerUrl')) $this->SetData('_PagerUrl', 'discussions/bookmarked/{Page}'); $this->SetData('_Page', $Page); $this->SetData('_Limit', $Limit); $this->FireEvent('AfterBuildBookmarkedPager'); // Deliver JSON data if necessary if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->SetJson('LessRow', $this->Pager->ToString('less')); $this->SetJson('MoreRow', $this->Pager->ToString('more')); $this->View = 'discussions'; } // Add modules $this->AddModule('DiscussionFilterModule'); $this->AddModule('NewDiscussionModule'); $this->AddModule('CategoriesModule'); // Render default view (discussions/bookmarked.php) $this->SetData('Title', T('My Bookmarks')); $this->SetData('Breadcrumbs', array(array('Name' => T('My Bookmarks'), 'Url' => '/discussions/bookmarked'))); $this->Render(); }
[ "public", "function", "Bookmarked", "(", "$", "Page", "=", "'0'", ")", "{", "$", "this", "->", "Permission", "(", "'Garden.SignIn.Allow'", ")", ";", "Gdn_Theme", "::", "Section", "(", "'DiscussionList'", ")", ";", "// Figure out which discussions layout to choose (D...
Display discussions the user has bookmarked. @since 2.0.0 @access public @param int $Offset Number of discussions to skip.
[ "Display", "discussions", "the", "user", "has", "bookmarked", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/vanilla/controllers/class.discussionscontroller.php#L298-L371
train
bishopb/vanilla
applications/vanilla/controllers/class.discussionscontroller.php
DiscussionsController.Mine
public function Mine($Page = 'p1') { $this->Permission('Garden.SignIn.Allow'); Gdn_Theme::Section('DiscussionList'); // Set criteria & get discussions data list($Offset, $Limit) = OffsetLimit($Page, C('Vanilla.Discussions.PerPage', 30)); $Session = Gdn::Session(); $Wheres = array('d.InsertUserID' => $Session->UserID); $DiscussionModel = new DiscussionModel(); $this->DiscussionData = $DiscussionModel->Get($Offset, $Limit, $Wheres); $this->SetData('Discussions', $this->DiscussionData); $CountDiscussions = $this->SetData('CountDiscussions', $DiscussionModel->GetCount($Wheres)); // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->EventArguments['PagerType'] = 'MorePager'; $this->FireEvent('BeforeBuildMinePager'); $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this); $this->Pager->MoreCode = 'More Discussions'; $this->Pager->LessCode = 'Newer Discussions'; $this->Pager->ClientID = 'Pager'; $this->Pager->Configure( $Offset, $Limit, $CountDiscussions, 'discussions/mine/%1$s' ); $this->SetData('_PagerUrl', 'discussions/mine/{Page}'); $this->SetData('_Page', $Page); $this->SetData('_Limit', $Limit); $this->FireEvent('AfterBuildMinePager'); // Deliver JSON data if necessary if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->SetJson('LessRow', $this->Pager->ToString('less')); $this->SetJson('MoreRow', $this->Pager->ToString('more')); $this->View = 'discussions'; } // Add modules $this->AddModule('DiscussionFilterModule'); $this->AddModule('NewDiscussionModule'); $this->AddModule('CategoriesModule'); $this->AddModule('BookmarkedModule'); // Render default view (discussions/mine.php) $this->SetData('Title', T('My Discussions')); $this->SetData('Breadcrumbs', array(array('Name' => T('My Discussions'), 'Url' => '/discussions/mine'))); $this->Render('Index'); }
php
public function Mine($Page = 'p1') { $this->Permission('Garden.SignIn.Allow'); Gdn_Theme::Section('DiscussionList'); // Set criteria & get discussions data list($Offset, $Limit) = OffsetLimit($Page, C('Vanilla.Discussions.PerPage', 30)); $Session = Gdn::Session(); $Wheres = array('d.InsertUserID' => $Session->UserID); $DiscussionModel = new DiscussionModel(); $this->DiscussionData = $DiscussionModel->Get($Offset, $Limit, $Wheres); $this->SetData('Discussions', $this->DiscussionData); $CountDiscussions = $this->SetData('CountDiscussions', $DiscussionModel->GetCount($Wheres)); // Build a pager $PagerFactory = new Gdn_PagerFactory(); $this->EventArguments['PagerType'] = 'MorePager'; $this->FireEvent('BeforeBuildMinePager'); $this->Pager = $PagerFactory->GetPager($this->EventArguments['PagerType'], $this); $this->Pager->MoreCode = 'More Discussions'; $this->Pager->LessCode = 'Newer Discussions'; $this->Pager->ClientID = 'Pager'; $this->Pager->Configure( $Offset, $Limit, $CountDiscussions, 'discussions/mine/%1$s' ); $this->SetData('_PagerUrl', 'discussions/mine/{Page}'); $this->SetData('_Page', $Page); $this->SetData('_Limit', $Limit); $this->FireEvent('AfterBuildMinePager'); // Deliver JSON data if necessary if ($this->_DeliveryType != DELIVERY_TYPE_ALL) { $this->SetJson('LessRow', $this->Pager->ToString('less')); $this->SetJson('MoreRow', $this->Pager->ToString('more')); $this->View = 'discussions'; } // Add modules $this->AddModule('DiscussionFilterModule'); $this->AddModule('NewDiscussionModule'); $this->AddModule('CategoriesModule'); $this->AddModule('BookmarkedModule'); // Render default view (discussions/mine.php) $this->SetData('Title', T('My Discussions')); $this->SetData('Breadcrumbs', array(array('Name' => T('My Discussions'), 'Url' => '/discussions/mine'))); $this->Render('Index'); }
[ "public", "function", "Mine", "(", "$", "Page", "=", "'p1'", ")", "{", "$", "this", "->", "Permission", "(", "'Garden.SignIn.Allow'", ")", ";", "Gdn_Theme", "::", "Section", "(", "'DiscussionList'", ")", ";", "// Set criteria & get discussions data", "list", "("...
Display discussions started by the user. @since 2.0.0 @access public @param int $Offset Number of discussions to skip.
[ "Display", "discussions", "started", "by", "the", "user", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/vanilla/controllers/class.discussionscontroller.php#L396-L447
train
bishopb/vanilla
applications/vanilla/controllers/class.discussionscontroller.php
DiscussionsController.GetCommentCounts
public function GetCommentCounts() { $this->AllowJSONP(TRUE); $vanilla_identifier = GetValue('vanilla_identifier', $_GET); if (!is_array($vanilla_identifier)) $vanilla_identifier = array($vanilla_identifier); $vanilla_identifier = array_unique($vanilla_identifier); $FinalData = array_fill_keys($vanilla_identifier, 0); $Misses = array(); $CacheKey = 'embed.comments.count.%s'; $OriginalIDs = array(); foreach ($vanilla_identifier as $ForeignID) { $HashedForeignID = ForeignIDHash($ForeignID); // Keep record of non-hashed identifiers for the reply $OriginalIDs[$HashedForeignID] = $ForeignID; $RealCacheKey = sprintf($CacheKey, $HashedForeignID); $Comments = Gdn::Cache()->Get($RealCacheKey); if ($Comments !== Gdn_Cache::CACHEOP_FAILURE) $FinalData[$ForeignID] = $Comments; else $Misses[] = $HashedForeignID; } if (sizeof($Misses)) { $CountData = Gdn::SQL() ->Select('ForeignID, CountComments') ->From('Discussion') ->Where('Type', 'page') ->WhereIn('ForeignID', $Misses) ->Get()->ResultArray(); foreach ($CountData as $Row) { // Get original identifier to send back $ForeignID = $OriginalIDs[$Row['ForeignID']]; $FinalData[$ForeignID] = $Row['CountComments']; // Cache using the hashed identifier $RealCacheKey = sprintf($CacheKey, $Row['ForeignID']); Gdn::Cache()->Store($RealCacheKey, $Row['CountComments'], array( Gdn_Cache::FEATURE_EXPIRY => 60 )); } } $this->SetData('CountData', $FinalData); $this->DeliveryMethod = DELIVERY_METHOD_JSON; $this->DeliveryType = DELIVERY_TYPE_DATA; $this->Render(); }
php
public function GetCommentCounts() { $this->AllowJSONP(TRUE); $vanilla_identifier = GetValue('vanilla_identifier', $_GET); if (!is_array($vanilla_identifier)) $vanilla_identifier = array($vanilla_identifier); $vanilla_identifier = array_unique($vanilla_identifier); $FinalData = array_fill_keys($vanilla_identifier, 0); $Misses = array(); $CacheKey = 'embed.comments.count.%s'; $OriginalIDs = array(); foreach ($vanilla_identifier as $ForeignID) { $HashedForeignID = ForeignIDHash($ForeignID); // Keep record of non-hashed identifiers for the reply $OriginalIDs[$HashedForeignID] = $ForeignID; $RealCacheKey = sprintf($CacheKey, $HashedForeignID); $Comments = Gdn::Cache()->Get($RealCacheKey); if ($Comments !== Gdn_Cache::CACHEOP_FAILURE) $FinalData[$ForeignID] = $Comments; else $Misses[] = $HashedForeignID; } if (sizeof($Misses)) { $CountData = Gdn::SQL() ->Select('ForeignID, CountComments') ->From('Discussion') ->Where('Type', 'page') ->WhereIn('ForeignID', $Misses) ->Get()->ResultArray(); foreach ($CountData as $Row) { // Get original identifier to send back $ForeignID = $OriginalIDs[$Row['ForeignID']]; $FinalData[$ForeignID] = $Row['CountComments']; // Cache using the hashed identifier $RealCacheKey = sprintf($CacheKey, $Row['ForeignID']); Gdn::Cache()->Store($RealCacheKey, $Row['CountComments'], array( Gdn_Cache::FEATURE_EXPIRY => 60 )); } } $this->SetData('CountData', $FinalData); $this->DeliveryMethod = DELIVERY_METHOD_JSON; $this->DeliveryType = DELIVERY_TYPE_DATA; $this->Render(); }
[ "public", "function", "GetCommentCounts", "(", ")", "{", "$", "this", "->", "AllowJSONP", "(", "TRUE", ")", ";", "$", "vanilla_identifier", "=", "GetValue", "(", "'vanilla_identifier'", ",", "$", "_GET", ")", ";", "if", "(", "!", "is_array", "(", "$", "v...
Takes a set of discussion identifiers and returns their comment counts in the same order.
[ "Takes", "a", "set", "of", "discussion", "identifiers", "and", "returns", "their", "comment", "counts", "in", "the", "same", "order", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/vanilla/controllers/class.discussionscontroller.php#L484-L536
train
bishopb/vanilla
applications/vanilla/controllers/class.discussionscontroller.php
DiscussionsController.Sort
public function Sort($Target = '') { if (!Gdn::Session()->IsValid()) throw PermissionException(); if (!$this->Request->IsAuthenticatedPostBack()) throw ForbiddenException('GET'); // Get param $SortField = Gdn::Request()->Post('DiscussionSort'); $SortField = 'd.'.StringBeginsWith($SortField, 'd.', TRUE, TRUE); // Use whitelist here too to keep database clean if (!in_array($SortField, DiscussionModel::AllowedSortFields())) { throw new Gdn_UserException("Unknown sort $SortField."); } // Set user pref Gdn::UserModel()->SavePreference(Gdn::Session()->UserID, 'Discussions.SortField', $SortField); if ($Target) Redirect($Target); // Send sorted discussions. $this->DeliveryMethod(DELIVERY_METHOD_JSON); $this->Render(); }
php
public function Sort($Target = '') { if (!Gdn::Session()->IsValid()) throw PermissionException(); if (!$this->Request->IsAuthenticatedPostBack()) throw ForbiddenException('GET'); // Get param $SortField = Gdn::Request()->Post('DiscussionSort'); $SortField = 'd.'.StringBeginsWith($SortField, 'd.', TRUE, TRUE); // Use whitelist here too to keep database clean if (!in_array($SortField, DiscussionModel::AllowedSortFields())) { throw new Gdn_UserException("Unknown sort $SortField."); } // Set user pref Gdn::UserModel()->SavePreference(Gdn::Session()->UserID, 'Discussions.SortField', $SortField); if ($Target) Redirect($Target); // Send sorted discussions. $this->DeliveryMethod(DELIVERY_METHOD_JSON); $this->Render(); }
[ "public", "function", "Sort", "(", "$", "Target", "=", "''", ")", "{", "if", "(", "!", "Gdn", "::", "Session", "(", ")", "->", "IsValid", "(", ")", ")", "throw", "PermissionException", "(", ")", ";", "if", "(", "!", "$", "this", "->", "Request", ...
Set user preference for sorting discussions.
[ "Set", "user", "preference", "for", "sorting", "discussions", "." ]
8494eb4a4ad61603479015a8054d23ff488364e8
https://github.com/bishopb/vanilla/blob/8494eb4a4ad61603479015a8054d23ff488364e8/applications/vanilla/controllers/class.discussionscontroller.php#L541-L566
train
CampusUnion/Sked
src/SkeFormInput.php
SkeFormInput.defineType
protected function defineType(string $strType) { switch ($strType) { case 'select': case 'textarea': $this->strElementType = $strType; break; case 'checkbox': case 'hidden': case 'radio': case 'text': default: $this->strElementType = 'input'; $this->aAttribs['type'] = $strType; break; } }
php
protected function defineType(string $strType) { switch ($strType) { case 'select': case 'textarea': $this->strElementType = $strType; break; case 'checkbox': case 'hidden': case 'radio': case 'text': default: $this->strElementType = 'input'; $this->aAttribs['type'] = $strType; break; } }
[ "protected", "function", "defineType", "(", "string", "$", "strType", ")", "{", "switch", "(", "$", "strType", ")", "{", "case", "'select'", ":", "case", "'textarea'", ":", "$", "this", "->", "strElementType", "=", "$", "strType", ";", "break", ";", "cas...
Init the HTML element type. @param string $strType Type of HTML element.
[ "Init", "the", "HTML", "element", "type", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/SkeFormInput.php#L95-L111
train
CampusUnion/Sked
src/SkeFormInput.php
SkeFormInput.renderInput
public function renderInput(array $aAttribs = []) { $this->aAttribs += $aAttribs; $strElement = $this->isMulti() ? $this->renderMulti() : $this->renderSingle(); $strSuffix = $this->strSuffix ? ' ' . $this->strSuffix : ''; return $strElement . $strSuffix; }
php
public function renderInput(array $aAttribs = []) { $this->aAttribs += $aAttribs; $strElement = $this->isMulti() ? $this->renderMulti() : $this->renderSingle(); $strSuffix = $this->strSuffix ? ' ' . $this->strSuffix : ''; return $strElement . $strSuffix; }
[ "public", "function", "renderInput", "(", "array", "$", "aAttribs", "=", "[", "]", ")", "{", "$", "this", "->", "aAttribs", "+=", "$", "aAttribs", ";", "$", "strElement", "=", "$", "this", "->", "isMulti", "(", ")", "?", "$", "this", "->", "renderMul...
Render the input element. @param array $aAttribs Array of element attributes. @return string HTML
[ "Render", "the", "input", "element", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/SkeFormInput.php#L207-L213
train
CampusUnion/Sked
src/SkeFormInput.php
SkeFormInput.renderSingle
protected function renderSingle() { $strHtml = ''; // Apply label? if (in_array($this->getType(), ['checkbox', 'radio'])) $strHtml .= '<label class="sked-input-multi">'; // Build opening tag $strHtml .= '<' . $this->strElementType . ' ' . $this->renderAttribs() . '>'; // Optional - Build inner HTML if (!empty($this->aOptions)) { // An indexed array means use the label as the value also. $bLabelIsValue = isset($this->aOptions[0]); foreach ($this->aOptions as $mValue => $strLabel) { if ($bLabelIsValue) $mValue = $strLabel; $strSelected = isset($this->mValue) && (string)$this->mValue === (string)$mValue ? ' selected' : ''; $strHtml .= '<option value="' . $mValue . '"' . $strSelected . '>' . $strLabel . '</option>'; } } elseif ('textarea' === $this->strElementType) { $strHtml .= $this->mValue; } // Optional - Build closing tag if ('input' !== $this->strElementType) $strHtml .= '</' . $this->strElementType . '>'; // Close label? if (in_array($this->getType(), ['checkbox', 'radio'])) $strHtml .= '</label>'; return $strHtml; }
php
protected function renderSingle() { $strHtml = ''; // Apply label? if (in_array($this->getType(), ['checkbox', 'radio'])) $strHtml .= '<label class="sked-input-multi">'; // Build opening tag $strHtml .= '<' . $this->strElementType . ' ' . $this->renderAttribs() . '>'; // Optional - Build inner HTML if (!empty($this->aOptions)) { // An indexed array means use the label as the value also. $bLabelIsValue = isset($this->aOptions[0]); foreach ($this->aOptions as $mValue => $strLabel) { if ($bLabelIsValue) $mValue = $strLabel; $strSelected = isset($this->mValue) && (string)$this->mValue === (string)$mValue ? ' selected' : ''; $strHtml .= '<option value="' . $mValue . '"' . $strSelected . '>' . $strLabel . '</option>'; } } elseif ('textarea' === $this->strElementType) { $strHtml .= $this->mValue; } // Optional - Build closing tag if ('input' !== $this->strElementType) $strHtml .= '</' . $this->strElementType . '>'; // Close label? if (in_array($this->getType(), ['checkbox', 'radio'])) $strHtml .= '</label>'; return $strHtml; }
[ "protected", "function", "renderSingle", "(", ")", "{", "$", "strHtml", "=", "''", ";", "// Apply label?", "if", "(", "in_array", "(", "$", "this", "->", "getType", "(", ")", ",", "[", "'checkbox'", ",", "'radio'", "]", ")", ")", "$", "strHtml", ".=", ...
Render a single element. @return string HTML
[ "Render", "a", "single", "element", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/SkeFormInput.php#L220-L256
train
CampusUnion/Sked
src/SkeFormInput.php
SkeFormInput.renderMulti
protected function renderMulti() { $strHtml = ''; // An indexed array means use the label as the value also. $bLabelIsValue = isset($this->aOptions[0]); foreach ($this->aOptions as $mValue => $strLabel) { if ($bLabelIsValue) $mValue = $strLabel; $strSelected = isset($this->mValue) && in_array($strLabel, (array)$this->mValue) ? ' checked' : ''; $strHtml .= '<label class="sked-input-multi">' . '<input value="' . $mValue . '" ' . $this->renderAttribs() . $strSelected . '> ' . $strLabel . '</label>'; } return $strHtml; }
php
protected function renderMulti() { $strHtml = ''; // An indexed array means use the label as the value also. $bLabelIsValue = isset($this->aOptions[0]); foreach ($this->aOptions as $mValue => $strLabel) { if ($bLabelIsValue) $mValue = $strLabel; $strSelected = isset($this->mValue) && in_array($strLabel, (array)$this->mValue) ? ' checked' : ''; $strHtml .= '<label class="sked-input-multi">' . '<input value="' . $mValue . '" ' . $this->renderAttribs() . $strSelected . '> ' . $strLabel . '</label>'; } return $strHtml; }
[ "protected", "function", "renderMulti", "(", ")", "{", "$", "strHtml", "=", "''", ";", "// An indexed array means use the label as the value also.", "$", "bLabelIsValue", "=", "isset", "(", "$", "this", "->", "aOptions", "[", "0", "]", ")", ";", "foreach", "(", ...
Render multiple related elements. @return string HTML
[ "Render", "multiple", "related", "elements", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/SkeFormInput.php#L263-L280
train
cobonto/module
src/Classes/Actions/Event.php
Event.add
public function add() { if($moduleEvents = $this->module->events()) { $systemEvents = $this->load(); if(isset($moduleEvents['listen'])) // for listen event we must check if exists merge if not add it foreach ($moduleEvents['listen'] as $event => $listens) { if(isset($systemEvents['listen'][$event])) $systemEvents['listen'][$event] = array_merge($systemEvents['listen'][$event],$listens); else $systemEvents['listen'][$event] = $listens; } // for subscribe if(isset($moduleEvents['subscribe'])) $systemEvents['subscribe'][] = $moduleEvents['subscribe']; return $this->set($systemEvents); } return true; }
php
public function add() { if($moduleEvents = $this->module->events()) { $systemEvents = $this->load(); if(isset($moduleEvents['listen'])) // for listen event we must check if exists merge if not add it foreach ($moduleEvents['listen'] as $event => $listens) { if(isset($systemEvents['listen'][$event])) $systemEvents['listen'][$event] = array_merge($systemEvents['listen'][$event],$listens); else $systemEvents['listen'][$event] = $listens; } // for subscribe if(isset($moduleEvents['subscribe'])) $systemEvents['subscribe'][] = $moduleEvents['subscribe']; return $this->set($systemEvents); } return true; }
[ "public", "function", "add", "(", ")", "{", "if", "(", "$", "moduleEvents", "=", "$", "this", "->", "module", "->", "events", "(", ")", ")", "{", "$", "systemEvents", "=", "$", "this", "->", "load", "(", ")", ";", "if", "(", "isset", "(", "$", ...
add events to events.php in cache
[ "add", "events", "to", "events", ".", "php", "in", "cache" ]
0978b5305c3d6f13ef7e0e5297855bd09eee6b76
https://github.com/cobonto/module/blob/0978b5305c3d6f13ef7e0e5297855bd09eee6b76/src/Classes/Actions/Event.php#L11-L31
train
cobonto/module
src/Classes/Actions/Event.php
Event.remove
public function remove() { if($moduleEvents = $this->module->events()) { $systemEvents = $this->load(); if (isset($moduleEvents['listen'])) // for listen event we must check if exists merge if not add it foreach ($moduleEvents['listen'] as $event => $listens) { if (isset($systemEvents['listen'][$event])) { foreach ($listens as $listen) { $key = array_search($listen, $systemEvents['listen'][$event]); if ($key !== false) unset($listen, $systemEvents['listen'][$event][$key]); } } } // for subscribe if (isset($moduleEvents['subscribe'])) { $key = array_search($moduleEvents['subscribe'], $systemEvents['subscribe'][$event]); if($key !==false) unset($systemEvents['subscribe'][$key]); } return $this->set($systemEvents); } return true; }
php
public function remove() { if($moduleEvents = $this->module->events()) { $systemEvents = $this->load(); if (isset($moduleEvents['listen'])) // for listen event we must check if exists merge if not add it foreach ($moduleEvents['listen'] as $event => $listens) { if (isset($systemEvents['listen'][$event])) { foreach ($listens as $listen) { $key = array_search($listen, $systemEvents['listen'][$event]); if ($key !== false) unset($listen, $systemEvents['listen'][$event][$key]); } } } // for subscribe if (isset($moduleEvents['subscribe'])) { $key = array_search($moduleEvents['subscribe'], $systemEvents['subscribe'][$event]); if($key !==false) unset($systemEvents['subscribe'][$key]); } return $this->set($systemEvents); } return true; }
[ "public", "function", "remove", "(", ")", "{", "if", "(", "$", "moduleEvents", "=", "$", "this", "->", "module", "->", "events", "(", ")", ")", "{", "$", "systemEvents", "=", "$", "this", "->", "load", "(", ")", ";", "if", "(", "isset", "(", "$",...
remove events from system
[ "remove", "events", "from", "system" ]
0978b5305c3d6f13ef7e0e5297855bd09eee6b76
https://github.com/cobonto/module/blob/0978b5305c3d6f13ef7e0e5297855bd09eee6b76/src/Classes/Actions/Event.php#L33-L62
train
zepi/turbo-base
Zepi/Web/AccessControl/src/EventHandler/GenerateNewPassword.php
GenerateNewPassword.execute
public function execute(Framework $framework, WebRequest $request, Response $response) { // Set the title for the page $this->setTitle($this->translate('Generate a new password', '\\Zepi\\Web\\AccessControl')); // Generate a new password $result = $this->generateNewPassword($framework, $request, $response); // Display the successful saved message $response->setOutput($this->render('\\Zepi\\Web\\AccessControl\\Templates\\GenerateNewPasswordFinished', array( 'title' => $this->getTitle(), 'result' => $result['result'], 'message' => $result['message'] ))); }
php
public function execute(Framework $framework, WebRequest $request, Response $response) { // Set the title for the page $this->setTitle($this->translate('Generate a new password', '\\Zepi\\Web\\AccessControl')); // Generate a new password $result = $this->generateNewPassword($framework, $request, $response); // Display the successful saved message $response->setOutput($this->render('\\Zepi\\Web\\AccessControl\\Templates\\GenerateNewPasswordFinished', array( 'title' => $this->getTitle(), 'result' => $result['result'], 'message' => $result['message'] ))); }
[ "public", "function", "execute", "(", "Framework", "$", "framework", ",", "WebRequest", "$", "request", ",", "Response", "$", "response", ")", "{", "// Set the title for the page", "$", "this", "->", "setTitle", "(", "$", "this", "->", "translate", "(", "'Gene...
Handles the whole registration process @access public @param \Zepi\Turbo\Framework $framework @param \Zepi\Turbo\Request\WebRequest $request @param \Zepi\Turbo\Response\Response $response
[ "Handles", "the", "whole", "registration", "process" ]
9a36d8c7649317f55f91b2adf386bd1f04ec02a3
https://github.com/zepi/turbo-base/blob/9a36d8c7649317f55f91b2adf386bd1f04ec02a3/Zepi/Web/AccessControl/src/EventHandler/GenerateNewPassword.php#L66-L80
train
zepi/turbo-base
Zepi/Web/AccessControl/src/EventHandler/GenerateNewPassword.php
GenerateNewPassword.generateRandomPassword
protected function generateRandomPassword() { $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+*=-_/()!?[]{}'; $password = array(); $alphabetLength = strlen($alphabet) - 1; for ($i = 0; $i < 10; $i++) { $charIndex = mt_rand(0, $alphabetLength); $password[] = $alphabet[$charIndex]; } $password = implode('', $password); if (!preg_match('/\d/', $password)) { $password = mt_rand(0, 9) . $password . mt_rand(0, 9); } return $password; }
php
protected function generateRandomPassword() { $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+*=-_/()!?[]{}'; $password = array(); $alphabetLength = strlen($alphabet) - 1; for ($i = 0; $i < 10; $i++) { $charIndex = mt_rand(0, $alphabetLength); $password[] = $alphabet[$charIndex]; } $password = implode('', $password); if (!preg_match('/\d/', $password)) { $password = mt_rand(0, 9) . $password . mt_rand(0, 9); } return $password; }
[ "protected", "function", "generateRandomPassword", "(", ")", "{", "$", "alphabet", "=", "'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+*=-_/()!?[]{}'", ";", "$", "password", "=", "array", "(", ")", ";", "$", "alphabetLength", "=", "strlen", "(", "$", ...
Generates a new random password @access protected @return string
[ "Generates", "a", "new", "random", "password" ]
9a36d8c7649317f55f91b2adf386bd1f04ec02a3
https://github.com/zepi/turbo-base/blob/9a36d8c7649317f55f91b2adf386bd1f04ec02a3/Zepi/Web/AccessControl/src/EventHandler/GenerateNewPassword.php#L155-L173
train
ilya-dev/block
src/Block/Block.php
Block.setObject
public function setObject($object) { if ( ! is_object($object)) { throw new InvalidArgumentException( 'Expected an object, but got '.gettype($object) ); } $this->object = new ReflectionClass($object); }
php
public function setObject($object) { if ( ! is_object($object)) { throw new InvalidArgumentException( 'Expected an object, but got '.gettype($object) ); } $this->object = new ReflectionClass($object); }
[ "public", "function", "setObject", "(", "$", "object", ")", "{", "if", "(", "!", "is_object", "(", "$", "object", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "'Expected an object, but got '", ".", "gettype", "(", "$", "object", ")", ")", ...
Set the object you want to work with. @throws InvalidArgumentException @param mixed $object @return void
[ "Set", "the", "object", "you", "want", "to", "work", "with", "." ]
46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8
https://github.com/ilya-dev/block/blob/46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8/src/Block/Block.php#L46-L56
train
ilya-dev/block
src/Block/Block.php
Block.property
public function property($name) { if ( ! $this->object->hasProperty($name)) { throw new UnexpectedValueException( "Property {$name} does not exist" ); } return $this->extractComment($this->object->getProperty($name)); }
php
public function property($name) { if ( ! $this->object->hasProperty($name)) { throw new UnexpectedValueException( "Property {$name} does not exist" ); } return $this->extractComment($this->object->getProperty($name)); }
[ "public", "function", "property", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "object", "->", "hasProperty", "(", "$", "name", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"Property {$name} does not exist\"", ")", ";",...
Fetch a property comment. @throws UnexpectedValueException @param string $name @return Comment
[ "Fetch", "a", "property", "comment", "." ]
46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8
https://github.com/ilya-dev/block/blob/46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8/src/Block/Block.php#L75-L85
train
ilya-dev/block
src/Block/Block.php
Block.properties
public function properties($filter = null) { if (is_null($filter)) { $properties = $this->object->getProperties(); } else { $properties = $this->object->getProperties($filter); } return array_map([$this, 'extractComment'], $properties); }
php
public function properties($filter = null) { if (is_null($filter)) { $properties = $this->object->getProperties(); } else { $properties = $this->object->getProperties($filter); } return array_map([$this, 'extractComment'], $properties); }
[ "public", "function", "properties", "(", "$", "filter", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "filter", ")", ")", "{", "$", "properties", "=", "$", "this", "->", "object", "->", "getProperties", "(", ")", ";", "}", "else", "{", "$"...
Get the comments for all properties. @param integer|null $filter @return array
[ "Get", "the", "comments", "for", "all", "properties", "." ]
46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8
https://github.com/ilya-dev/block/blob/46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8/src/Block/Block.php#L93-L105
train
ilya-dev/block
src/Block/Block.php
Block.method
public function method($name) { if ( ! $this->object->hasMethod($name)) { throw new UnexpectedValueException( "Method {$name} does not exist" ); } return $this->extractComment($this->object->getMethod($name)); }
php
public function method($name) { if ( ! $this->object->hasMethod($name)) { throw new UnexpectedValueException( "Method {$name} does not exist" ); } return $this->extractComment($this->object->getMethod($name)); }
[ "public", "function", "method", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "object", "->", "hasMethod", "(", "$", "name", ")", ")", "{", "throw", "new", "UnexpectedValueException", "(", "\"Method {$name} does not exist\"", ")", ";", "}"...
Get the method comment. @throws UnexpectedValueException @param string $name @return Comment
[ "Get", "the", "method", "comment", "." ]
46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8
https://github.com/ilya-dev/block/blob/46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8/src/Block/Block.php#L114-L124
train
ilya-dev/block
src/Block/Block.php
Block.methods
public function methods($filter = null) { if (is_null($filter)) { $methods = $this->object->getMethods(); } else { $methods = $this->object->getMethods($filter); } return array_map([$this, 'extractComment'], $methods); }
php
public function methods($filter = null) { if (is_null($filter)) { $methods = $this->object->getMethods(); } else { $methods = $this->object->getMethods($filter); } return array_map([$this, 'extractComment'], $methods); }
[ "public", "function", "methods", "(", "$", "filter", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "filter", ")", ")", "{", "$", "methods", "=", "$", "this", "->", "object", "->", "getMethods", "(", ")", ";", "}", "else", "{", "$", "meth...
Get the comments for all methods. @param integer|null $filter @return array
[ "Get", "the", "comments", "for", "all", "methods", "." ]
46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8
https://github.com/ilya-dev/block/blob/46aeff9abd1e61a4247e1cf3aed3f8c7561e2bd8/src/Block/Block.php#L132-L144
train
flowcode/AmulenNewsBundle
src/Flowcode/NewsBundle/Controller/AdminCategoryController.php
AdminCategoryController.indexAction
public function indexAction() { $em = $this->getDoctrine()->getManager(); $rootName = $this->container->getParameter('flowcode_news.root_category'); $root = $em->getRepository('AmulenClassificationBundle:Category')->findOneBy(array("name" => $rootName)); $entities = $em->getRepository('AmulenClassificationBundle:Category')->getChildren($root); return array( 'entities' => $entities, 'rootcategory' => $root, ); }
php
public function indexAction() { $em = $this->getDoctrine()->getManager(); $rootName = $this->container->getParameter('flowcode_news.root_category'); $root = $em->getRepository('AmulenClassificationBundle:Category')->findOneBy(array("name" => $rootName)); $entities = $em->getRepository('AmulenClassificationBundle:Category')->getChildren($root); return array( 'entities' => $entities, 'rootcategory' => $root, ); }
[ "public", "function", "indexAction", "(", ")", "{", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "$", "rootName", "=", "$", "this", "->", "container", "->", "getParameter", "(", "'flowcode_news.root_categor...
Lists all Category entities. @Route("/", name="admin_news_category") @Method("GET") @Template()
[ "Lists", "all", "Category", "entities", "." ]
e870d2f09b629affeddf9a53ed43205300b66933
https://github.com/flowcode/AmulenNewsBundle/blob/e870d2f09b629affeddf9a53ed43205300b66933/src/Flowcode/NewsBundle/Controller/AdminCategoryController.php#L27-L37
train
flowcode/AmulenNewsBundle
src/Flowcode/NewsBundle/Controller/AdminCategoryController.php
AdminCategoryController.childrensAction
public function childrensAction($id) { $em = $this->getDoctrine()->getManager(); $parent = $em->getRepository('AmulenClassificationBundle:Category')->findOneBy(array("id" => $id)); $childrens = $em->getRepository('AmulenClassificationBundle:Category')->getChildren($parent, true); return array( 'entities' => $childrens, 'parent' => $parent, ); }
php
public function childrensAction($id) { $em = $this->getDoctrine()->getManager(); $parent = $em->getRepository('AmulenClassificationBundle:Category')->findOneBy(array("id" => $id)); $childrens = $em->getRepository('AmulenClassificationBundle:Category')->getChildren($parent, true); return array( 'entities' => $childrens, 'parent' => $parent, ); }
[ "public", "function", "childrensAction", "(", "$", "id", ")", "{", "$", "em", "=", "$", "this", "->", "getDoctrine", "(", ")", "->", "getManager", "(", ")", ";", "$", "parent", "=", "$", "em", "->", "getRepository", "(", "'AmulenClassificationBundle:Catego...
Select parent. @Route("/childrens/{id}", name="admin_news_category_children") @Method("GET") @Template()
[ "Select", "parent", "." ]
e870d2f09b629affeddf9a53ed43205300b66933
https://github.com/flowcode/AmulenNewsBundle/blob/e870d2f09b629affeddf9a53ed43205300b66933/src/Flowcode/NewsBundle/Controller/AdminCategoryController.php#L113-L123
train
flowcode/AmulenNewsBundle
src/Flowcode/NewsBundle/Controller/AdminCategoryController.php
AdminCategoryController.createDeleteForm
private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_news_category_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete', 'attr' => array( 'onclick' => 'return confirm("Estás seguro?")' ))) ->getForm() ; }
php
private function createDeleteForm($id) { return $this->createFormBuilder() ->setAction($this->generateUrl('admin_news_category_delete', array('id' => $id))) ->setMethod('DELETE') ->add('submit', 'submit', array('label' => 'Delete', 'attr' => array( 'onclick' => 'return confirm("Estás seguro?")' ))) ->getForm() ; }
[ "private", "function", "createDeleteForm", "(", "$", "id", ")", "{", "return", "$", "this", "->", "createFormBuilder", "(", ")", "->", "setAction", "(", "$", "this", "->", "generateUrl", "(", "'admin_news_category_delete'", ",", "array", "(", "'id'", "=>", "...
Creates a form to delete a Category entity by id. @param mixed $id The entity id @return Form The form
[ "Creates", "a", "form", "to", "delete", "a", "Category", "entity", "by", "id", "." ]
e870d2f09b629affeddf9a53ed43205300b66933
https://github.com/flowcode/AmulenNewsBundle/blob/e870d2f09b629affeddf9a53ed43205300b66933/src/Flowcode/NewsBundle/Controller/AdminCategoryController.php#L258-L268
train
bereczkybalazs/brick-core
src/RouteDispatcher.php
RouteDispatcher.parseFilters
protected function parseFilters($filters) { $beforeFilter = array(); $afterFilter = array(); if (isset($filters[Route::BEFORE])) { $beforeFilter = array_intersect_key($this->filters, array_flip((array)$filters[Route::BEFORE])); } if (isset($filters[Route::AFTER])) { $afterFilter = array_intersect_key($this->filters, array_flip((array)$filters[Route::AFTER])); } return array($beforeFilter, $afterFilter); }
php
protected function parseFilters($filters) { $beforeFilter = array(); $afterFilter = array(); if (isset($filters[Route::BEFORE])) { $beforeFilter = array_intersect_key($this->filters, array_flip((array)$filters[Route::BEFORE])); } if (isset($filters[Route::AFTER])) { $afterFilter = array_intersect_key($this->filters, array_flip((array)$filters[Route::AFTER])); } return array($beforeFilter, $afterFilter); }
[ "protected", "function", "parseFilters", "(", "$", "filters", ")", "{", "$", "beforeFilter", "=", "array", "(", ")", ";", "$", "afterFilter", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "filters", "[", "Route", "::", "BEFORE", "]", ")"...
Normalise the array filters attached to the route and merge with any global filters. @param $filters @return array
[ "Normalise", "the", "array", "filters", "attached", "to", "the", "route", "and", "merge", "with", "any", "global", "filters", "." ]
6528c127d6aa2e506813891c6147fb341ed80e7c
https://github.com/bereczkybalazs/brick-core/blob/6528c127d6aa2e506813891c6147fb341ed80e7c/src/RouteDispatcher.php#L148-L162
train
bereczkybalazs/brick-core
src/RouteDispatcher.php
RouteDispatcher.dispatchRoute
protected function dispatchRoute($httpMethod, $uri) { if (isset($this->staticRouteMap[$uri])) { return $this->dispatchStaticRoute($httpMethod, $uri); } return $this->dispatchVariableRoute($httpMethod, $uri); }
php
protected function dispatchRoute($httpMethod, $uri) { if (isset($this->staticRouteMap[$uri])) { return $this->dispatchStaticRoute($httpMethod, $uri); } return $this->dispatchVariableRoute($httpMethod, $uri); }
[ "protected", "function", "dispatchRoute", "(", "$", "httpMethod", ",", "$", "uri", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "staticRouteMap", "[", "$", "uri", "]", ")", ")", "{", "return", "$", "this", "->", "dispatchStaticRoute", "(", "$"...
Perform the route dispatching. Check static routes first followed by variable routes. @param $httpMethod @param $uri @throws HttpRouteNotFoundException
[ "Perform", "the", "route", "dispatching", ".", "Check", "static", "routes", "first", "followed", "by", "variable", "routes", "." ]
6528c127d6aa2e506813891c6147fb341ed80e7c
https://github.com/bereczkybalazs/brick-core/blob/6528c127d6aa2e506813891c6147fb341ed80e7c/src/RouteDispatcher.php#L171-L178
train
bereczkybalazs/brick-core
src/RouteDispatcher.php
RouteDispatcher.dispatchStaticRoute
protected function dispatchStaticRoute($httpMethod, $uri) { $routes = $this->staticRouteMap[$uri]; if (!isset($routes[$httpMethod])) { $httpMethod = $this->checkFallbacks($routes, $httpMethod); } return $routes[$httpMethod]; }
php
protected function dispatchStaticRoute($httpMethod, $uri) { $routes = $this->staticRouteMap[$uri]; if (!isset($routes[$httpMethod])) { $httpMethod = $this->checkFallbacks($routes, $httpMethod); } return $routes[$httpMethod]; }
[ "protected", "function", "dispatchStaticRoute", "(", "$", "httpMethod", ",", "$", "uri", ")", "{", "$", "routes", "=", "$", "this", "->", "staticRouteMap", "[", "$", "uri", "]", ";", "if", "(", "!", "isset", "(", "$", "routes", "[", "$", "httpMethod", ...
Handle the dispatching of static routes. @param $httpMethod @param $uri @return mixed @throws HttpMethodNotAllowedException
[ "Handle", "the", "dispatching", "of", "static", "routes", "." ]
6528c127d6aa2e506813891c6147fb341ed80e7c
https://github.com/bereczkybalazs/brick-core/blob/6528c127d6aa2e506813891c6147fb341ed80e7c/src/RouteDispatcher.php#L188-L197
train
bereczkybalazs/brick-core
src/RouteDispatcher.php
RouteDispatcher.dispatchVariableRoute
protected function dispatchVariableRoute($httpMethod, $uri) { foreach ($this->variableRouteData as $data) { if (!preg_match($data['regex'], $uri, $matches)) { continue; } $count = count($matches); while (!isset($data['routeMap'][$count++])) { ; } $routes = $data['routeMap'][$count - 1]; if (!isset($routes[$httpMethod])) { $httpMethod = $this->checkFallbacks($routes, $httpMethod); } foreach (array_values($routes[$httpMethod][2]) as $i => $varName) { if (!isset($matches[$i + 1]) || $matches[$i + 1] === '') { unset($routes[$httpMethod][2][$varName]); } else { $routes[$httpMethod][2][$varName] = $matches[$i + 1]; } } return $routes[$httpMethod]; } throw new HttpRouteNotFoundException('Route ' . $uri . ' does not exist'); }
php
protected function dispatchVariableRoute($httpMethod, $uri) { foreach ($this->variableRouteData as $data) { if (!preg_match($data['regex'], $uri, $matches)) { continue; } $count = count($matches); while (!isset($data['routeMap'][$count++])) { ; } $routes = $data['routeMap'][$count - 1]; if (!isset($routes[$httpMethod])) { $httpMethod = $this->checkFallbacks($routes, $httpMethod); } foreach (array_values($routes[$httpMethod][2]) as $i => $varName) { if (!isset($matches[$i + 1]) || $matches[$i + 1] === '') { unset($routes[$httpMethod][2][$varName]); } else { $routes[$httpMethod][2][$varName] = $matches[$i + 1]; } } return $routes[$httpMethod]; } throw new HttpRouteNotFoundException('Route ' . $uri . ' does not exist'); }
[ "protected", "function", "dispatchVariableRoute", "(", "$", "httpMethod", ",", "$", "uri", ")", "{", "foreach", "(", "$", "this", "->", "variableRouteData", "as", "$", "data", ")", "{", "if", "(", "!", "preg_match", "(", "$", "data", "[", "'regex'", "]",...
Handle the dispatching of variable routes. @param $httpMethod @param $uri @throws HttpMethodNotAllowedException @throws HttpRouteNotFoundException
[ "Handle", "the", "dispatching", "of", "variable", "routes", "." ]
6528c127d6aa2e506813891c6147fb341ed80e7c
https://github.com/bereczkybalazs/brick-core/blob/6528c127d6aa2e506813891c6147fb341ed80e7c/src/RouteDispatcher.php#L233-L264
train
CampusUnion/Sked
src/Database/SkeModelPDO.php
SkeModelPDO.find
public function find(int $iId) { $oSelect = $this->oConnector->prepare('SELECT * FROM sked_events WHERE id = :id'); if (!$oSelect->execute([':id' => $iId])) throw new \Exception(__METHOD__ . ' - ' . $oSelect->errorInfo()[2]); return $oSelect->fetch(\PDO::FETCH_ASSOC); }
php
public function find(int $iId) { $oSelect = $this->oConnector->prepare('SELECT * FROM sked_events WHERE id = :id'); if (!$oSelect->execute([':id' => $iId])) throw new \Exception(__METHOD__ . ' - ' . $oSelect->errorInfo()[2]); return $oSelect->fetch(\PDO::FETCH_ASSOC); }
[ "public", "function", "find", "(", "int", "$", "iId", ")", "{", "$", "oSelect", "=", "$", "this", "->", "oConnector", "->", "prepare", "(", "'SELECT * FROM sked_events WHERE id = :id'", ")", ";", "if", "(", "!", "$", "oSelect", "->", "execute", "(", "[", ...
Retrieve an event from the database. @param int $iId @return array
[ "Retrieve", "an", "event", "from", "the", "database", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModelPDO.php#L46-L52
train
CampusUnion/Sked
src/Database/SkeModelPDO.php
SkeModelPDO.queryDay
protected function queryDay(string $strDateStart, string $strDateEnd) { $strQuery = $this->querySelectFrom($strDateStart) . $this->queryJoin() . $this->queryWhereNotExpired(); // Happening today $strQuery .= ' AND ('; // Original date matches $strQuery .= ' sked_events.starts_at BETWEEN :date_start AND :date_end'; // Or it's already started and... $strQuery .= ' OR (sked_events.starts_at <= :date_start AND ('; // Daily $strQuery .= ' ( sked_events.interval = "1" AND ( DATEDIFF( :date_start_NOTIME, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d") )/sked_events.frequency ) % 1 =0 )'; // Day of week matches for weekly events $strQuery .= ' OR ( sked_events.interval = "7" AND sked_events.' . date('D', strtotime($strDateStart)) . ' = 1 AND ( DATEDIFF( :date_start_NOTIME, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d") )/7 ) % sked_events.frequency = 0 )'; // Monthly by day of week // Calculate how many months since first session, see if it's an exact match for today $strQuery .= ' OR ( sked_events.interval = "Monthly" AND sked_events.' . date('D', strtotime($strDateStart)) . ' = 1 AND TIMESTAMPADD( MONTH, ROUND(DATEDIFF(:date_start, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d"))/30), sked_events.starts_at ) BETWEEN :date_start AND :date_end )'; // Monthly by date $strQuery .= ' OR ( sked_events.interval = "Monthly" AND sked_events.Mon = 0 AND sked_events.Tue = 0 AND sked_events.Wed = 0 AND sked_events.Thu = 0 AND sked_events.Fri = 0 AND sked_events.Sat = 0 AND sked_events.Sun = 0 AND DAYOFMONTH(sked_events.starts_at) = :date_start_DAYOFMONTH AND (:date_start_YEARMONTH - EXTRACT(YEAR_MONTH FROM sked_events.starts_at)) % sked_events.frequency = 0 )'; $strQuery .= '))'; $strQuery .= ')' . $this->queryGroupAndOrder(); // PDO return $this->queryPDO($strQuery, $this->aQueryParams + [ ':date_start' => $strDateStart, ':date_start_NOTIME' => date('Y-m-d', strtotime($strDateStart)), ':date_start_DAYOFMONTH' => date('d', strtotime($strDateStart)), ':date_start_YEARMONTH' => date('Ym', strtotime($strDateStart)), ':date_end' => $strDateEnd, ]); }
php
protected function queryDay(string $strDateStart, string $strDateEnd) { $strQuery = $this->querySelectFrom($strDateStart) . $this->queryJoin() . $this->queryWhereNotExpired(); // Happening today $strQuery .= ' AND ('; // Original date matches $strQuery .= ' sked_events.starts_at BETWEEN :date_start AND :date_end'; // Or it's already started and... $strQuery .= ' OR (sked_events.starts_at <= :date_start AND ('; // Daily $strQuery .= ' ( sked_events.interval = "1" AND ( DATEDIFF( :date_start_NOTIME, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d") )/sked_events.frequency ) % 1 =0 )'; // Day of week matches for weekly events $strQuery .= ' OR ( sked_events.interval = "7" AND sked_events.' . date('D', strtotime($strDateStart)) . ' = 1 AND ( DATEDIFF( :date_start_NOTIME, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d") )/7 ) % sked_events.frequency = 0 )'; // Monthly by day of week // Calculate how many months since first session, see if it's an exact match for today $strQuery .= ' OR ( sked_events.interval = "Monthly" AND sked_events.' . date('D', strtotime($strDateStart)) . ' = 1 AND TIMESTAMPADD( MONTH, ROUND(DATEDIFF(:date_start, DATE_FORMAT(sked_events.starts_at, "%Y-%m-%d"))/30), sked_events.starts_at ) BETWEEN :date_start AND :date_end )'; // Monthly by date $strQuery .= ' OR ( sked_events.interval = "Monthly" AND sked_events.Mon = 0 AND sked_events.Tue = 0 AND sked_events.Wed = 0 AND sked_events.Thu = 0 AND sked_events.Fri = 0 AND sked_events.Sat = 0 AND sked_events.Sun = 0 AND DAYOFMONTH(sked_events.starts_at) = :date_start_DAYOFMONTH AND (:date_start_YEARMONTH - EXTRACT(YEAR_MONTH FROM sked_events.starts_at)) % sked_events.frequency = 0 )'; $strQuery .= '))'; $strQuery .= ')' . $this->queryGroupAndOrder(); // PDO return $this->queryPDO($strQuery, $this->aQueryParams + [ ':date_start' => $strDateStart, ':date_start_NOTIME' => date('Y-m-d', strtotime($strDateStart)), ':date_start_DAYOFMONTH' => date('d', strtotime($strDateStart)), ':date_start_YEARMONTH' => date('Ym', strtotime($strDateStart)), ':date_end' => $strDateEnd, ]); }
[ "protected", "function", "queryDay", "(", "string", "$", "strDateStart", ",", "string", "$", "strDateEnd", ")", "{", "$", "strQuery", "=", "$", "this", "->", "querySelectFrom", "(", "$", "strDateStart", ")", ".", "$", "this", "->", "queryJoin", "(", ")", ...
Build the events query for today. @param string $strDateStart Datetime that today starts. @param string $strDateEnd Datetime that today ends. @return array
[ "Build", "the", "events", "query", "for", "today", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModelPDO.php#L61-L138
train
CampusUnion/Sked
src/Database/SkeModelPDO.php
SkeModelPDO.queryPDO
private function queryPDO(string $strQuery, array $aParams = []) { $oStmt = $this->oConnector->prepare($strQuery); if (!$oStmt->execute($aParams)) throw new \Exception(__METHOD__ . ' - ' . $oStmt->errorInfo()[2]); list($strMethod) = explode(' ', trim($strQuery)); switch (strtoupper($strMethod)) { case 'SELECT': return $oStmt->fetchAll(\PDO::FETCH_ASSOC); break; case 'INSERT': return $this->oConnector->lastInsertId(); break; case 'UPDATE': return $aParams[':id_value']; break; case 'DELETE': default: return true; break; } }
php
private function queryPDO(string $strQuery, array $aParams = []) { $oStmt = $this->oConnector->prepare($strQuery); if (!$oStmt->execute($aParams)) throw new \Exception(__METHOD__ . ' - ' . $oStmt->errorInfo()[2]); list($strMethod) = explode(' ', trim($strQuery)); switch (strtoupper($strMethod)) { case 'SELECT': return $oStmt->fetchAll(\PDO::FETCH_ASSOC); break; case 'INSERT': return $this->oConnector->lastInsertId(); break; case 'UPDATE': return $aParams[':id_value']; break; case 'DELETE': default: return true; break; } }
[ "private", "function", "queryPDO", "(", "string", "$", "strQuery", ",", "array", "$", "aParams", "=", "[", "]", ")", "{", "$", "oStmt", "=", "$", "this", "->", "oConnector", "->", "prepare", "(", "$", "strQuery", ")", ";", "if", "(", "!", "$", "oSt...
Execute the query with PDO and return results. @param string $strQuery SQL query. @param array $aParams Array of parameters to bind. @return array|int|bool
[ "Execute", "the", "query", "with", "PDO", "and", "return", "results", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModelPDO.php#L310-L336
train
CampusUnion/Sked
src/Database/SkeModelPDO.php
SkeModelPDO.saveEventMembers
protected function saveEventMembers(int $iEventId, array $aMembers) { if (!empty($aMembers)) { $aExecParams[':sked_event_id'] = $iEventId; $strQuery = 'INSERT IGNORE INTO `sked_event_members` (`sked_event_id`, `member_id`, `owner`, `lead_time`, `created_at`) VALUES '; $aValueSets = []; foreach ($aMembers as $iMemberId => $aSettings) { $strMemberParam = ':member_id_' . $iMemberId; $strOwnerParam = ':owner_' . $iMemberId; $strLeadTimeParam = ':lead_time_' . $iMemberId; $aValueSets[] = '(:sked_event_id, ' . $strMemberParam . ', ' . $strOwnerParam . ', ' . $strLeadTimeParam . ', NOW())'; $aExecParams[$strMemberParam] = $iMemberId; $aExecParams[$strOwnerParam] = $aSettings['owner'] ?? 0; $aExecParams[$strLeadTimeParam] = $aSettings['lead_time'] ?? 0; } $strQuery .= implode(',', $aValueSets) . ' ON DUPLICATE KEY UPDATE' . ' `owner` = VALUES(`owner`), `lead_time` = VALUES(`lead_time`)'; $this->queryPDO($strQuery, $aExecParams); } return true; }
php
protected function saveEventMembers(int $iEventId, array $aMembers) { if (!empty($aMembers)) { $aExecParams[':sked_event_id'] = $iEventId; $strQuery = 'INSERT IGNORE INTO `sked_event_members` (`sked_event_id`, `member_id`, `owner`, `lead_time`, `created_at`) VALUES '; $aValueSets = []; foreach ($aMembers as $iMemberId => $aSettings) { $strMemberParam = ':member_id_' . $iMemberId; $strOwnerParam = ':owner_' . $iMemberId; $strLeadTimeParam = ':lead_time_' . $iMemberId; $aValueSets[] = '(:sked_event_id, ' . $strMemberParam . ', ' . $strOwnerParam . ', ' . $strLeadTimeParam . ', NOW())'; $aExecParams[$strMemberParam] = $iMemberId; $aExecParams[$strOwnerParam] = $aSettings['owner'] ?? 0; $aExecParams[$strLeadTimeParam] = $aSettings['lead_time'] ?? 0; } $strQuery .= implode(',', $aValueSets) . ' ON DUPLICATE KEY UPDATE' . ' `owner` = VALUES(`owner`), `lead_time` = VALUES(`lead_time`)'; $this->queryPDO($strQuery, $aExecParams); } return true; }
[ "protected", "function", "saveEventMembers", "(", "int", "$", "iEventId", ",", "array", "$", "aMembers", ")", "{", "if", "(", "!", "empty", "(", "$", "aMembers", ")", ")", "{", "$", "aExecParams", "[", "':sked_event_id'", "]", "=", "$", "iEventId", ";", ...
Persist event member data to the database. @param int $iEventId Event that owns the tags. @param array $aMembers Array of data to persist. @return bool Success/failure.
[ "Persist", "event", "member", "data", "to", "the", "database", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModelPDO.php#L394-L420
train
CampusUnion/Sked
src/Database/SkeModelPDO.php
SkeModelPDO.saveEventTags
protected function saveEventTags(int $iEventId, array $aTags) { // Delete existing tags $this->queryPDO( 'DELETE FROM `sked_event_tags` WHERE `sked_event_id` = ?', [$iEventId] ); // Create new tags if (!empty($aTags)) { $aValueSets = []; $aExecParams[':sked_event_id'] = $iEventId; $strQuery = 'INSERT INTO `sked_event_tags` (`sked_event_id`, `tag_id`, `value`, `created_at`) VALUES '; foreach ($aTags as $iTagId => $mTagValue) { $strTagParam = ':tag_id_' . $iTagId; $strValueParam = ':value_' . $iTagId; $aValueSets[] = '(:sked_event_id, ' . $strTagParam . ', ' . $strValueParam . ', NOW())'; $aExecParams[$strTagParam] = $iTagId; $aExecParams[$strValueParam] = $mTagValue; } $strQuery .= implode(',', $aValueSets); $this->queryPDO($strQuery, $aExecParams); } return true; }
php
protected function saveEventTags(int $iEventId, array $aTags) { // Delete existing tags $this->queryPDO( 'DELETE FROM `sked_event_tags` WHERE `sked_event_id` = ?', [$iEventId] ); // Create new tags if (!empty($aTags)) { $aValueSets = []; $aExecParams[':sked_event_id'] = $iEventId; $strQuery = 'INSERT INTO `sked_event_tags` (`sked_event_id`, `tag_id`, `value`, `created_at`) VALUES '; foreach ($aTags as $iTagId => $mTagValue) { $strTagParam = ':tag_id_' . $iTagId; $strValueParam = ':value_' . $iTagId; $aValueSets[] = '(:sked_event_id, ' . $strTagParam . ', ' . $strValueParam . ', NOW())'; $aExecParams[$strTagParam] = $iTagId; $aExecParams[$strValueParam] = $mTagValue; } $strQuery .= implode(',', $aValueSets); $this->queryPDO($strQuery, $aExecParams); } return true; }
[ "protected", "function", "saveEventTags", "(", "int", "$", "iEventId", ",", "array", "$", "aTags", ")", "{", "// Delete existing tags", "$", "this", "->", "queryPDO", "(", "'DELETE FROM `sked_event_tags` WHERE `sked_event_id` = ?'", ",", "[", "$", "iEventId", "]", "...
Persist event tag data to the database. @param int $iEventId Event that owns the tags. @param array $aTags Array of data to persist. @return bool true On success. @throws \Exception On failure.
[ "Persist", "event", "tag", "data", "to", "the", "database", "." ]
5b51afdb56c0f607e54364635c4725627b19ecc6
https://github.com/CampusUnion/Sked/blob/5b51afdb56c0f607e54364635c4725627b19ecc6/src/Database/SkeModelPDO.php#L444-L470
train
motamonteiro/helpers
src/Traits/DataHelper.php
DataHelper.dataFormatoDestino
public function dataFormatoDestino($data, $formatoDestino) { $dataFormatada = false; if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_SQL)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_SQL, $formatoDestino); } if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_HORA_SQL)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_HORA_SQL, $formatoDestino); } if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_BR)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_BR, $formatoDestino); } if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_HORA_BR)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_HORA_BR, $formatoDestino); } return $dataFormatada; }
php
public function dataFormatoDestino($data, $formatoDestino) { $dataFormatada = false; if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_SQL)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_SQL, $formatoDestino); } if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_HORA_SQL)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_HORA_SQL, $formatoDestino); } if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_BR)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_BR, $formatoDestino); } if (!$dataFormatada && $this->validarDataPorFormato($data, $this->FORMATO_DATA_HORA_BR)) { $dataFormatada = $this->dataFormatoOrigemDestino($data, $this->FORMATO_DATA_HORA_BR, $formatoDestino); } return $dataFormatada; }
[ "public", "function", "dataFormatoDestino", "(", "$", "data", ",", "$", "formatoDestino", ")", "{", "$", "dataFormatada", "=", "false", ";", "if", "(", "!", "$", "dataFormatada", "&&", "$", "this", "->", "validarDataPorFormato", "(", "$", "data", ",", "$",...
Converter uma data identificando o formato origem para o formato destino informado. @param \DateTime|string $data @return false|string
[ "Converter", "uma", "data", "identificando", "o", "formato", "origem", "para", "o", "formato", "destino", "informado", "." ]
4cd246d454968865758e74c5be383063e0f7ccd4
https://github.com/motamonteiro/helpers/blob/4cd246d454968865758e74c5be383063e0f7ccd4/src/Traits/DataHelper.php#L74-L95
train
motamonteiro/helpers
src/Traits/DataHelper.php
DataHelper.dataFormatoOrigemDestino
public function dataFormatoOrigemDestino($data, $formatoOrigem, $formatoDestino) { $data = $this->converterParaDateTime($data, $formatoOrigem); if (!$data) { return false; } return ($data->format($formatoDestino)); }
php
public function dataFormatoOrigemDestino($data, $formatoOrigem, $formatoDestino) { $data = $this->converterParaDateTime($data, $formatoOrigem); if (!$data) { return false; } return ($data->format($formatoDestino)); }
[ "public", "function", "dataFormatoOrigemDestino", "(", "$", "data", ",", "$", "formatoOrigem", ",", "$", "formatoDestino", ")", "{", "$", "data", "=", "$", "this", "->", "converterParaDateTime", "(", "$", "data", ",", "$", "formatoOrigem", ")", ";", "if", ...
Converter uma data de um formato origem para um formato destino. @param \DateTime|string $data @param $formatoOrigem @param $formatoDestino @return false|string
[ "Converter", "uma", "data", "de", "um", "formato", "origem", "para", "um", "formato", "destino", "." ]
4cd246d454968865758e74c5be383063e0f7ccd4
https://github.com/motamonteiro/helpers/blob/4cd246d454968865758e74c5be383063e0f7ccd4/src/Traits/DataHelper.php#L105-L113
train
jayaregalinada/chikka
src/Chikka.php
Chikka.send
public function send($mobileNumber, $message, $messageId = null) { return $this->app['chikka.sender']->send($mobileNumber, $message, $messageId); }
php
public function send($mobileNumber, $message, $messageId = null) { return $this->app['chikka.sender']->send($mobileNumber, $message, $messageId); }
[ "public", "function", "send", "(", "$", "mobileNumber", ",", "$", "message", ",", "$", "messageId", "=", "null", ")", "{", "return", "$", "this", "->", "app", "[", "'chikka.sender'", "]", "->", "send", "(", "$", "mobileNumber", ",", "$", "message", ","...
Send capability. @param string $mobileNumber @param string $message @param string $messageId @return \GuzzleHttp\Promise\Promise
[ "Send", "capability", "." ]
eefd52c6a7c0e22fe82cef00c52874865456dddf
https://github.com/jayaregalinada/chikka/blob/eefd52c6a7c0e22fe82cef00c52874865456dddf/src/Chikka.php#L63-L66
train
jayaregalinada/chikka
src/Chikka.php
Chikka.sendAsync
public function sendAsync($mobileNumber, $message, $messageId = null) { return $this->app['chikka.sender']->sendAsync($mobileNumber, $message, $messageId); }
php
public function sendAsync($mobileNumber, $message, $messageId = null) { return $this->app['chikka.sender']->sendAsync($mobileNumber, $message, $messageId); }
[ "public", "function", "sendAsync", "(", "$", "mobileNumber", ",", "$", "message", ",", "$", "messageId", "=", "null", ")", "{", "return", "$", "this", "->", "app", "[", "'chikka.sender'", "]", "->", "sendAsync", "(", "$", "mobileNumber", ",", "$", "messa...
Send capability without async. @param string $mobileNumber @param string $message @param string $messageId [description] @return [type] [description]
[ "Send", "capability", "without", "async", "." ]
eefd52c6a7c0e22fe82cef00c52874865456dddf
https://github.com/jayaregalinada/chikka/blob/eefd52c6a7c0e22fe82cef00c52874865456dddf/src/Chikka.php#L75-L78
train
atelierspierrot/library
src/Library/Helper/File.php
File.getUniqFilename
public static function getUniqFilename($filename = '', $dir = null, $force_file = true, $extension = 'txt') { if (empty($filename)) { return ''; } $extension = trim($extension, '.'); if (empty($filename)){ $filename = uniqid(); if ($force_file) $filename .= '.'.$extension; } if (is_null($dir)) { $dir = defined('_DIR_TMP') ? _DIR_TMP : '/tmp'; } $dir = Directory::slashDirname($dir); $_ext = self::getExtension($filename, true); $_fname = str_replace($_ext, '', $filename); $i = 0; while (file_exists($dir.$_fname.$_ext)) { $_fname .= ($i==0 ? '_' : '').rand(10, 99); $i++; } return $_fname.$_ext; }
php
public static function getUniqFilename($filename = '', $dir = null, $force_file = true, $extension = 'txt') { if (empty($filename)) { return ''; } $extension = trim($extension, '.'); if (empty($filename)){ $filename = uniqid(); if ($force_file) $filename .= '.'.$extension; } if (is_null($dir)) { $dir = defined('_DIR_TMP') ? _DIR_TMP : '/tmp'; } $dir = Directory::slashDirname($dir); $_ext = self::getExtension($filename, true); $_fname = str_replace($_ext, '', $filename); $i = 0; while (file_exists($dir.$_fname.$_ext)) { $_fname .= ($i==0 ? '_' : '').rand(10, 99); $i++; } return $_fname.$_ext; }
[ "public", "static", "function", "getUniqFilename", "(", "$", "filename", "=", "''", ",", "$", "dir", "=", "null", ",", "$", "force_file", "=", "true", ",", "$", "extension", "=", "'txt'", ")", "{", "if", "(", "empty", "(", "$", "filename", ")", ")", ...
Returns a filename or directory that does not exist in the destination @param string $filename The name of the file or folder you want to create @param string $dir The destination directory @param boolean $force_file Should we force the creation of a file, adding an extension? (TRUE by default) @param string $extension The extension to add in the case of a file @return string The filename or directory, with a possible addition to be sure that it does not exist in the destination directory
[ "Returns", "a", "filename", "or", "directory", "that", "does", "not", "exist", "in", "the", "destination" ]
a2988a11370d13c7e0dc47f9d2d81c664c30b8dd
https://github.com/atelierspierrot/library/blob/a2988a11370d13c7e0dc47f9d2d81c664c30b8dd/src/Library/Helper/File.php#L51-L74
train
atelierspierrot/library
src/Library/Helper/File.php
File.formatFilename
public static function formatFilename($filename = '', $lowercase = false, $delimiter = '-') { if (empty($filename)) { return ''; } $_ext = self::getExtension($filename, true); if ($_ext) { $filename = str_replace($_ext, '', $filename); } $string = $filename; if ($lowercase) { $string = strtolower($string); } $string = str_replace(" ",$delimiter,$string); $string = preg_replace('#\-+#',$delimiter,$string); $string = preg_replace('#([-]+)#',$delimiter,$string); $string = trim($string,$delimiter); $string = TextHelper::stripSpecialChars($string, $delimiter.'.'); if ($_ext) { $string .= $_ext; } return $string; }
php
public static function formatFilename($filename = '', $lowercase = false, $delimiter = '-') { if (empty($filename)) { return ''; } $_ext = self::getExtension($filename, true); if ($_ext) { $filename = str_replace($_ext, '', $filename); } $string = $filename; if ($lowercase) { $string = strtolower($string); } $string = str_replace(" ",$delimiter,$string); $string = preg_replace('#\-+#',$delimiter,$string); $string = preg_replace('#([-]+)#',$delimiter,$string); $string = trim($string,$delimiter); $string = TextHelper::stripSpecialChars($string, $delimiter.'.'); if ($_ext) { $string .= $_ext; } return $string; }
[ "public", "static", "function", "formatFilename", "(", "$", "filename", "=", "''", ",", "$", "lowercase", "=", "false", ",", "$", "delimiter", "=", "'-'", ")", "{", "if", "(", "empty", "(", "$", "filename", ")", ")", "{", "return", "''", ";", "}", ...
Formatting file names @param string $filename The filename to format @param boolean $lowercase Should we return the name un lowercase (FALSE by default) @param string $delimiter The delimiter used for special chars substitution @return string A filename valid on (almost) all systems
[ "Formatting", "file", "names" ]
a2988a11370d13c7e0dc47f9d2d81c664c30b8dd
https://github.com/atelierspierrot/library/blob/a2988a11370d13c7e0dc47f9d2d81c664c30b8dd/src/Library/Helper/File.php#L84-L112
train
atelierspierrot/library
src/Library/Helper/File.php
File.getExtension
public static function getExtension($filename = '', $dot = false) { if (empty($filename)) { return ''; } $exploded_file_name = explode('.', $filename); return (strpos($filename, '.') ? ($dot ? '.' : '').end($exploded_file_name) : null); }
php
public static function getExtension($filename = '', $dot = false) { if (empty($filename)) { return ''; } $exploded_file_name = explode('.', $filename); return (strpos($filename, '.') ? ($dot ? '.' : '').end($exploded_file_name) : null); }
[ "public", "static", "function", "getExtension", "(", "$", "filename", "=", "''", ",", "$", "dot", "=", "false", ")", "{", "if", "(", "empty", "(", "$", "filename", ")", ")", "{", "return", "''", ";", "}", "$", "exploded_file_name", "=", "explode", "(...
Returns the extension of a file name It basically returns everything after last dot. No validation is done. @param string $filename The file_name to work on @param bool $dot @return null|string The extension if found, `null` otherwise
[ "Returns", "the", "extension", "of", "a", "file", "name" ]
a2988a11370d13c7e0dc47f9d2d81c664c30b8dd
https://github.com/atelierspierrot/library/blob/a2988a11370d13c7e0dc47f9d2d81c664c30b8dd/src/Library/Helper/File.php#L123-L130
train
atelierspierrot/library
src/Library/Helper/File.php
File.touch
public static function touch($file_path = null, array &$logs = array()) { if (is_null($file_path)) { return null; } if (!file_exists($file_path)) { $target_dir = dirname($file_path); $ok = !file_exists($target_dir) ? Directory::create($target_dir) : true; } else { $ok = true; } if (touch($file_path)) { clearstatcache(); return true; } else { $logs[] = sprintf('Can not touch file "%s".', $file_path); } return false; }
php
public static function touch($file_path = null, array &$logs = array()) { if (is_null($file_path)) { return null; } if (!file_exists($file_path)) { $target_dir = dirname($file_path); $ok = !file_exists($target_dir) ? Directory::create($target_dir) : true; } else { $ok = true; } if (touch($file_path)) { clearstatcache(); return true; } else { $logs[] = sprintf('Can not touch file "%s".', $file_path); } return false; }
[ "public", "static", "function", "touch", "(", "$", "file_path", "=", "null", ",", "array", "&", "$", "logs", "=", "array", "(", ")", ")", "{", "if", "(", "is_null", "(", "$", "file_path", ")", ")", "{", "return", "null", ";", "}", "if", "(", "!",...
Create an empty file or touch an existing file @param string $file_path @param array $logs Logs registry passed by reference @return bool
[ "Create", "an", "empty", "file", "or", "touch", "an", "existing", "file" ]
a2988a11370d13c7e0dc47f9d2d81c664c30b8dd
https://github.com/atelierspierrot/library/blob/a2988a11370d13c7e0dc47f9d2d81c664c30b8dd/src/Library/Helper/File.php#L204-L222
train
atelierspierrot/library
src/Library/Helper/File.php
File.remove
public static function remove($file_path = null, array &$logs = array()) { if (is_null($file_path)) { return null; } if (file_exists($file_path)) { if (unlink($file_path)) { clearstatcache(); return true; } else { $logs[] = sprintf('Can not unlink file "%s".', $file_path); } } else { $logs[] = sprintf('File path "%s" does not exist (can not be removed).', $file_path); } return false; }
php
public static function remove($file_path = null, array &$logs = array()) { if (is_null($file_path)) { return null; } if (file_exists($file_path)) { if (unlink($file_path)) { clearstatcache(); return true; } else { $logs[] = sprintf('Can not unlink file "%s".', $file_path); } } else { $logs[] = sprintf('File path "%s" does not exist (can not be removed).', $file_path); } return false; }
[ "public", "static", "function", "remove", "(", "$", "file_path", "=", "null", ",", "array", "&", "$", "logs", "=", "array", "(", ")", ")", "{", "if", "(", "is_null", "(", "$", "file_path", ")", ")", "{", "return", "null", ";", "}", "if", "(", "fi...
Remove a file if it exists @param string $file_path @param array $logs Logs registry passed by reference @return bool
[ "Remove", "a", "file", "if", "it", "exists" ]
a2988a11370d13c7e0dc47f9d2d81c664c30b8dd
https://github.com/atelierspierrot/library/blob/a2988a11370d13c7e0dc47f9d2d81c664c30b8dd/src/Library/Helper/File.php#L231-L247
train
atelierspierrot/library
src/Library/Helper/File.php
File.write
public static function write($file_path = null, $content, $type = 'a', $force = false, array &$logs = array()) { if (is_null($file_path)) { return null; } if (!file_exists($file_path)) { if (true===$force) { self::touch($file_path, $logs); } else { $logs[] = sprintf('File path "%s" to copy was not found.', $file_path); return false; } } if (is_writable($file_path)) { $h = fopen($file_path, $type); if (false !== fwrite($h, $content)) { fclose($h); return true; } } $logs[] = sprintf('Can not write in file "%s".', $file_path); return false; }
php
public static function write($file_path = null, $content, $type = 'a', $force = false, array &$logs = array()) { if (is_null($file_path)) { return null; } if (!file_exists($file_path)) { if (true===$force) { self::touch($file_path, $logs); } else { $logs[] = sprintf('File path "%s" to copy was not found.', $file_path); return false; } } if (is_writable($file_path)) { $h = fopen($file_path, $type); if (false !== fwrite($h, $content)) { fclose($h); return true; } } $logs[] = sprintf('Can not write in file "%s".', $file_path); return false; }
[ "public", "static", "function", "write", "(", "$", "file_path", "=", "null", ",", "$", "content", ",", "$", "type", "=", "'a'", ",", "$", "force", "=", "false", ",", "array", "&", "$", "logs", "=", "array", "(", ")", ")", "{", "if", "(", "is_null...
Write a content in a file @param string $file_path @param string $content @param string $type @param bool $force @param array $logs @return bool
[ "Write", "a", "content", "in", "a", "file" ]
a2988a11370d13c7e0dc47f9d2d81c664c30b8dd
https://github.com/atelierspierrot/library/blob/a2988a11370d13c7e0dc47f9d2d81c664c30b8dd/src/Library/Helper/File.php#L295-L317
train
webriq/core
module/Customize/src/Grid/Customize/Model/Sheet/Mapper.php
Mapper.find
public function find( $primaryKeys ) { if ( is_array( $primaryKeys ) ) { $primaryKeys = reset( $primaryKeys ); } $rootId = ( (int) $primaryKeys ) ?: null; return $this->createStructure( array( 'rootId' => $rootId, 'extra' => $this->getExtraMapper() ->findByRoot( $rootId ), 'rules' => $this->getRuleMapper() ->findAllByRoot( $rootId, $this->getRuleOrder() ), ) ); }
php
public function find( $primaryKeys ) { if ( is_array( $primaryKeys ) ) { $primaryKeys = reset( $primaryKeys ); } $rootId = ( (int) $primaryKeys ) ?: null; return $this->createStructure( array( 'rootId' => $rootId, 'extra' => $this->getExtraMapper() ->findByRoot( $rootId ), 'rules' => $this->getRuleMapper() ->findAllByRoot( $rootId, $this->getRuleOrder() ), ) ); }
[ "public", "function", "find", "(", "$", "primaryKeys", ")", "{", "if", "(", "is_array", "(", "$", "primaryKeys", ")", ")", "{", "$", "primaryKeys", "=", "reset", "(", "$", "primaryKeys", ")", ";", "}", "$", "rootId", "=", "(", "(", "int", ")", "$",...
Find a structure by root paragraph id @param int|array $primaryKeys @return Structure
[ "Find", "a", "structure", "by", "root", "paragraph", "id" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/Customize/src/Grid/Customize/Model/Sheet/Mapper.php#L240-L259
train
webriq/core
module/Customize/src/Grid/Customize/Model/Sheet/Mapper.php
Mapper.findByExtra
public function findByExtra( ExtraStructure $extra ) { $rootId = $extra->rootParagraphId; return $this->createStructure( array( 'rootId' => $rootId, 'extra' => $extra, 'rules' => $this->getRuleMapper() ->findAllByRoot( $rootId, $this->getRuleOrder() ), ) ); }
php
public function findByExtra( ExtraStructure $extra ) { $rootId = $extra->rootParagraphId; return $this->createStructure( array( 'rootId' => $rootId, 'extra' => $extra, 'rules' => $this->getRuleMapper() ->findAllByRoot( $rootId, $this->getRuleOrder() ), ) ); }
[ "public", "function", "findByExtra", "(", "ExtraStructure", "$", "extra", ")", "{", "$", "rootId", "=", "$", "extra", "->", "rootParagraphId", ";", "return", "$", "this", "->", "createStructure", "(", "array", "(", "'rootId'", "=>", "$", "rootId", ",", "'e...
Find a structure by its extra structure @param int|array $primaryKeys @return Structure
[ "Find", "a", "structure", "by", "its", "extra", "structure" ]
cfeb6e8a4732561c2215ec94e736c07f9b8bc990
https://github.com/webriq/core/blob/cfeb6e8a4732561c2215ec94e736c07f9b8bc990/module/Customize/src/Grid/Customize/Model/Sheet/Mapper.php#L267-L280
train
hschulz/data-structures
src/Queue/PriorityQueue.php
PriorityQueue.toArray
public function toArray(): array { /* Enable extraction of data and priority */ $this->setExtractFlags(self::EXTR_BOTH); /* Prepare output */ $data = []; /* Iterate yourself */ foreach ($this as $item) { $data[] = $item; } return $data; }
php
public function toArray(): array { /* Enable extraction of data and priority */ $this->setExtractFlags(self::EXTR_BOTH); /* Prepare output */ $data = []; /* Iterate yourself */ foreach ($this as $item) { $data[] = $item; } return $data; }
[ "public", "function", "toArray", "(", ")", ":", "array", "{", "/* Enable extraction of data and priority */", "$", "this", "->", "setExtractFlags", "(", "self", "::", "EXTR_BOTH", ")", ";", "/* Prepare output */", "$", "data", "=", "[", "]", ";", "/* Iterate yours...
Iterates the queue and returns an array containing each item with the data and priority set. @return array The array representation of the queue
[ "Iterates", "the", "queue", "and", "returns", "an", "array", "containing", "each", "item", "with", "the", "data", "and", "priority", "set", "." ]
b563be1ecde746fe32dd8bcbf72cbbf4ea522075
https://github.com/hschulz/data-structures/blob/b563be1ecde746fe32dd8bcbf72cbbf4ea522075/src/Queue/PriorityQueue.php#L27-L41
train
hschulz/data-structures
src/Queue/PriorityQueue.php
PriorityQueue.insert
public function insert($data, $priority = self::PIRORITY_DEFAULT): void { parent::insert($data, $priority); }
php
public function insert($data, $priority = self::PIRORITY_DEFAULT): void { parent::insert($data, $priority); }
[ "public", "function", "insert", "(", "$", "data", ",", "$", "priority", "=", "self", "::", "PIRORITY_DEFAULT", ")", ":", "void", "{", "parent", "::", "insert", "(", "$", "data", ",", "$", "priority", ")", ";", "}" ]
Allows inserting data into the queue without explicitly setting a priority value. Inserts without a priority will use the PRIORITY_DEFAULT value. @param mixed $data The data to insert @param mixed $priority The priority @return void
[ "Allows", "inserting", "data", "into", "the", "queue", "without", "explicitly", "setting", "a", "priority", "value", ".", "Inserts", "without", "a", "priority", "will", "use", "the", "PRIORITY_DEFAULT", "value", "." ]
b563be1ecde746fe32dd8bcbf72cbbf4ea522075
https://github.com/hschulz/data-structures/blob/b563be1ecde746fe32dd8bcbf72cbbf4ea522075/src/Queue/PriorityQueue.php#L52-L55
train
hschulz/data-structures
src/Queue/PriorityQueue.php
PriorityQueue.unserialize
public function unserialize($queue) { foreach (unserialize($queue) as $item) { $this->insert($item['data'], $item['priority']); } }
php
public function unserialize($queue) { foreach (unserialize($queue) as $item) { $this->insert($item['data'], $item['priority']); } }
[ "public", "function", "unserialize", "(", "$", "queue", ")", "{", "foreach", "(", "unserialize", "(", "$", "queue", ")", "as", "$", "item", ")", "{", "$", "this", "->", "insert", "(", "$", "item", "[", "'data'", "]", ",", "$", "item", "[", "'priori...
Unserializes the queue. @param string $queue The serialized queue data @return void
[ "Unserializes", "the", "queue", "." ]
b563be1ecde746fe32dd8bcbf72cbbf4ea522075
https://github.com/hschulz/data-structures/blob/b563be1ecde746fe32dd8bcbf72cbbf4ea522075/src/Queue/PriorityQueue.php#L73-L78
train
hschulz/data-structures
src/Queue/PriorityQueue.php
PriorityQueue.merge
public function merge(self $queue): void { $data = $queue->toArray(); foreach ($data as $item) { $this->insert($item['data'], $item['priority']); } }
php
public function merge(self $queue): void { $data = $queue->toArray(); foreach ($data as $item) { $this->insert($item['data'], $item['priority']); } }
[ "public", "function", "merge", "(", "self", "$", "queue", ")", ":", "void", "{", "$", "data", "=", "$", "queue", "->", "toArray", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "item", ")", "{", "$", "this", "->", "insert", "(", "$", "i...
Merges the given queue data into this queue. @param PriorityQueue $queue The queue to merge @return void
[ "Merges", "the", "given", "queue", "data", "into", "this", "queue", "." ]
b563be1ecde746fe32dd8bcbf72cbbf4ea522075
https://github.com/hschulz/data-structures/blob/b563be1ecde746fe32dd8bcbf72cbbf4ea522075/src/Queue/PriorityQueue.php#L86-L93
train
ItinerisLtd/preflight-command
src/CLI/ResultCollectionPresenter.php
ResultCollectionPresenter.display
public static function display(array $assocArgs, ResultCollection $resultCollection): void { // TODO: Use null coalescing assignment operator. $assocArgs['fields'] = $assocArgs['fields'] ?? self::DEFAULT_FIELDS; $formatter = new Formatter($assocArgs, $assocArgs['fields']); $formatter->display_items( self::toTable($resultCollection), true ); }
php
public static function display(array $assocArgs, ResultCollection $resultCollection): void { // TODO: Use null coalescing assignment operator. $assocArgs['fields'] = $assocArgs['fields'] ?? self::DEFAULT_FIELDS; $formatter = new Formatter($assocArgs, $assocArgs['fields']); $formatter->display_items( self::toTable($resultCollection), true ); }
[ "public", "static", "function", "display", "(", "array", "$", "assocArgs", ",", "ResultCollection", "$", "resultCollection", ")", ":", "void", "{", "// TODO: Use null coalescing assignment operator.", "$", "assocArgs", "[", "'fields'", "]", "=", "$", "assocArgs", "[...
Display a result collection in a given format. @param array $assocArgs Associative CLI argument. @param ResultCollection $resultCollection The checker collection instance.
[ "Display", "a", "result", "collection", "in", "a", "given", "format", "." ]
d1c1360ea8d7de0312b5c0c09c9c486949594049
https://github.com/ItinerisLtd/preflight-command/blob/d1c1360ea8d7de0312b5c0c09c9c486949594049/src/CLI/ResultCollectionPresenter.php#L28-L38
train
ItinerisLtd/preflight-command
src/CLI/ResultCollectionPresenter.php
ResultCollectionPresenter.toTable
private static function toTable(ResultCollection $resultCollection): array { return array_map(function (ResultInterface $result): array { return self::toRow($result); }, $resultCollection->all()); }
php
private static function toTable(ResultCollection $resultCollection): array { return array_map(function (ResultInterface $result): array { return self::toRow($result); }, $resultCollection->all()); }
[ "private", "static", "function", "toTable", "(", "ResultCollection", "$", "resultCollection", ")", ":", "array", "{", "return", "array_map", "(", "function", "(", "ResultInterface", "$", "result", ")", ":", "array", "{", "return", "self", "::", "toRow", "(", ...
Converts the underlying results into a plain PHP array which printable on console tables. @param ResultCollection $resultCollection The result collection instance. @return array
[ "Converts", "the", "underlying", "results", "into", "a", "plain", "PHP", "array", "which", "printable", "on", "console", "tables", "." ]
d1c1360ea8d7de0312b5c0c09c9c486949594049
https://github.com/ItinerisLtd/preflight-command/blob/d1c1360ea8d7de0312b5c0c09c9c486949594049/src/CLI/ResultCollectionPresenter.php#L47-L52
train
ItinerisLtd/preflight-command
src/CLI/ResultCollectionPresenter.php
ResultCollectionPresenter.toRow
private static function toRow(ResultInterface $result): array { $row = [ 'id' => $result->getChecker()->getId(), 'link' => $result->getChecker()->getLink(), 'description' => $result->getChecker()->getDescription(), 'status' => $result->getStatus(), 'messages' => $result->getMessages(), ]; $row['status'] = self::colorize($result, $row['status']); $row['message'] = implode(PHP_EOL, $row['messages']); return $row; }
php
private static function toRow(ResultInterface $result): array { $row = [ 'id' => $result->getChecker()->getId(), 'link' => $result->getChecker()->getLink(), 'description' => $result->getChecker()->getDescription(), 'status' => $result->getStatus(), 'messages' => $result->getMessages(), ]; $row['status'] = self::colorize($result, $row['status']); $row['message'] = implode(PHP_EOL, $row['messages']); return $row; }
[ "private", "static", "function", "toRow", "(", "ResultInterface", "$", "result", ")", ":", "array", "{", "$", "row", "=", "[", "'id'", "=>", "$", "result", "->", "getChecker", "(", ")", "->", "getId", "(", ")", ",", "'link'", "=>", "$", "result", "->...
Converts the underlying result into a plain PHP array which printable as console table row. Note: One checker might yields multiple result instances. @param ResultInterface $result The result instance. @return array
[ "Converts", "the", "underlying", "result", "into", "a", "plain", "PHP", "array", "which", "printable", "as", "console", "table", "row", "." ]
d1c1360ea8d7de0312b5c0c09c9c486949594049
https://github.com/ItinerisLtd/preflight-command/blob/d1c1360ea8d7de0312b5c0c09c9c486949594049/src/CLI/ResultCollectionPresenter.php#L63-L77
train
ItinerisLtd/preflight-command
src/CLI/ResultCollectionPresenter.php
ResultCollectionPresenter.colorize
private static function colorize(ResultInterface $result, string $text): string { $colors = [ Success::class => '%G', Disabled::class => '%P', Failure::class => '%R', Error::class => '%1%w', 'reset' => '%n', ]; $color = $colors[get_class($result)] ?? $colors['reset']; return WP_CLI::colorize($color . $text . '%n'); }
php
private static function colorize(ResultInterface $result, string $text): string { $colors = [ Success::class => '%G', Disabled::class => '%P', Failure::class => '%R', Error::class => '%1%w', 'reset' => '%n', ]; $color = $colors[get_class($result)] ?? $colors['reset']; return WP_CLI::colorize($color . $text . '%n'); }
[ "private", "static", "function", "colorize", "(", "ResultInterface", "$", "result", ",", "string", "$", "text", ")", ":", "string", "{", "$", "colors", "=", "[", "Success", "::", "class", "=>", "'%G'", ",", "Disabled", "::", "class", "=>", "'%P'", ",", ...
Colorize a string for output. @param ResultInterface $result The result instance. @param string $text The text to be printed. @return string
[ "Colorize", "a", "string", "for", "output", "." ]
d1c1360ea8d7de0312b5c0c09c9c486949594049
https://github.com/ItinerisLtd/preflight-command/blob/d1c1360ea8d7de0312b5c0c09c9c486949594049/src/CLI/ResultCollectionPresenter.php#L87-L100
train
nirix/radium
src/Http/Response.php
Response.header
public function header($header, $value, $replace = true) { $this->headers[] = array($header, $value, $replace); }
php
public function header($header, $value, $replace = true) { $this->headers[] = array($header, $value, $replace); }
[ "public", "function", "header", "(", "$", "header", ",", "$", "value", ",", "$", "replace", "=", "true", ")", "{", "$", "this", "->", "headers", "[", "]", "=", "array", "(", "$", "header", ",", "$", "value", ",", "$", "replace", ")", ";", "}" ]
Sets a response header. @param string $header @param string $value
[ "Sets", "a", "response", "header", "." ]
cc6907bfee296b64a7630b0b188e233d7cdb86fd
https://github.com/nirix/radium/blob/cc6907bfee296b64a7630b0b188e233d7cdb86fd/src/Http/Response.php#L89-L92
train
heyday/heystack-ecommerce-core
src/Currency/Input/Processor.php
Processor.process
public function process(\SS_HTTPRequest $request) { if ($identifier = $request->param('ID')) { if ($this->currencyService->setActiveCurrency(new Identifier($identifier))) { return [ 'Success' => true ]; } } return [ 'Success' => false ]; }
php
public function process(\SS_HTTPRequest $request) { if ($identifier = $request->param('ID')) { if ($this->currencyService->setActiveCurrency(new Identifier($identifier))) { return [ 'Success' => true ]; } } return [ 'Success' => false ]; }
[ "public", "function", "process", "(", "\\", "SS_HTTPRequest", "$", "request", ")", "{", "if", "(", "$", "identifier", "=", "$", "request", "->", "param", "(", "'ID'", ")", ")", "{", "if", "(", "$", "this", "->", "currencyService", "->", "setActiveCurrenc...
Method to determine how to handle the request. Uses the currency service to set the active currency @param \SS_HTTPRequest $request @return array
[ "Method", "to", "determine", "how", "to", "handle", "the", "request", ".", "Uses", "the", "currency", "service", "to", "set", "the", "active", "currency" ]
b56c83839cd3396da6bc881d843fcb4f28b74685
https://github.com/heyday/heystack-ecommerce-core/blob/b56c83839cd3396da6bc881d843fcb4f28b74685/src/Currency/Input/Processor.php#L58-L71
train
sellerlabs/nucleus
src/SellerLabs/Nucleus/Transformation/TransformPipeline.php
TransformPipeline.run
public function run(array $input) { return Std::foldl(function ($current, TransformInterface $input) { return $input->run($current); }, $input, $this->transforms); }
php
public function run(array $input) { return Std::foldl(function ($current, TransformInterface $input) { return $input->run($current); }, $input, $this->transforms); }
[ "public", "function", "run", "(", "array", "$", "input", ")", "{", "return", "Std", "::", "foldl", "(", "function", "(", "$", "current", ",", "TransformInterface", "$", "input", ")", "{", "return", "$", "input", "->", "run", "(", "$", "current", ")", ...
Run the input through the pipeline. @param array $input @return array
[ "Run", "the", "input", "through", "the", "pipeline", "." ]
c05d9c23d424a6bd5ab2e29140805cc6e37e4623
https://github.com/sellerlabs/nucleus/blob/c05d9c23d424a6bd5ab2e29140805cc6e37e4623/src/SellerLabs/Nucleus/Transformation/TransformPipeline.php#L73-L78
train
takatost/php-pubsub-cmq
src/CMQPubSubAdapter.php
CMQPubSubAdapter.subscribe
public function subscribe($topicQueueName, callable $handler) { $isSubscriptionLoopActive = true; while ($isSubscriptionLoopActive) { $request = new SubscribeMessageRequest([ 'queueName' => $topicQueueName, 'pollingWaitSeconds' => 0, ]); try { $message = $this->client->send($request); } catch (RequestException $e) { throw $e; } catch (ResponseException $e) { $message = $e->getBody(); if (!$message->has('code')) { throw $e; } else if (!in_array($message->get('code'), ['7000', '6070'])) { // 队列没有消息或队列中有太多不可见或者延时消息 throw $e; } } catch (\Exception $e) { throw $e; } if ($message === null || $message->get('msgBody') === null) { sleep(mt_rand(1, 5)); continue; } call_user_func($handler, Utils::unserializeMessagePayload($message->get('msgBody')), new MessageHandler($this->client, $topicQueueName, $message) ); unset($message); } }
php
public function subscribe($topicQueueName, callable $handler) { $isSubscriptionLoopActive = true; while ($isSubscriptionLoopActive) { $request = new SubscribeMessageRequest([ 'queueName' => $topicQueueName, 'pollingWaitSeconds' => 0, ]); try { $message = $this->client->send($request); } catch (RequestException $e) { throw $e; } catch (ResponseException $e) { $message = $e->getBody(); if (!$message->has('code')) { throw $e; } else if (!in_array($message->get('code'), ['7000', '6070'])) { // 队列没有消息或队列中有太多不可见或者延时消息 throw $e; } } catch (\Exception $e) { throw $e; } if ($message === null || $message->get('msgBody') === null) { sleep(mt_rand(1, 5)); continue; } call_user_func($handler, Utils::unserializeMessagePayload($message->get('msgBody')), new MessageHandler($this->client, $topicQueueName, $message) ); unset($message); } }
[ "public", "function", "subscribe", "(", "$", "topicQueueName", ",", "callable", "$", "handler", ")", "{", "$", "isSubscriptionLoopActive", "=", "true", ";", "while", "(", "$", "isSubscriptionLoopActive", ")", "{", "$", "request", "=", "new", "SubscribeMessageReq...
Subscribe a handler to a topic queue. @param string $topicQueueName @param callable $handler @throws RequestException @throws ResponseException @throws \Exception
[ "Subscribe", "a", "handler", "to", "a", "topic", "queue", "." ]
74c980b5dd4e98150d01b8e50d3dfb9a02c7d4fd
https://github.com/takatost/php-pubsub-cmq/blob/74c980b5dd4e98150d01b8e50d3dfb9a02c7d4fd/src/CMQPubSubAdapter.php#L50-L87
train
titon/model
src/Titon/Model/Relation.php
Relation.detectForeignKey
public function detectForeignKey($config, $class) { $foreignKey = $this->getConfig($config); if (!$foreignKey) { $foreignKey = $this->buildForeignKey($class); $this->setConfig($config, $foreignKey); } return $foreignKey; }
php
public function detectForeignKey($config, $class) { $foreignKey = $this->getConfig($config); if (!$foreignKey) { $foreignKey = $this->buildForeignKey($class); $this->setConfig($config, $foreignKey); } return $foreignKey; }
[ "public", "function", "detectForeignKey", "(", "$", "config", ",", "$", "class", ")", "{", "$", "foreignKey", "=", "$", "this", "->", "getConfig", "(", "$", "config", ")", ";", "if", "(", "!", "$", "foreignKey", ")", "{", "$", "foreignKey", "=", "$",...
Return a foreign key either for the primary or related model. If no foreign key is defined, automatically inflect one and set it. @param string $config @param string $class @return string
[ "Return", "a", "foreign", "key", "either", "for", "the", "primary", "or", "related", "model", ".", "If", "no", "foreign", "key", "is", "defined", "automatically", "inflect", "one", "and", "set", "it", "." ]
274e3810c2cfbb6818a388daaa462ff05de99cbd
https://github.com/titon/model/blob/274e3810c2cfbb6818a388daaa462ff05de99cbd/src/Titon/Model/Relation.php#L142-L152
train
titon/model
src/Titon/Model/Relation.php
Relation.getPrimaryModel
public function getPrimaryModel() { if ($model = $this->_model) { return $model; } $class = $this->getPrimaryClass(); if (!$class) { return null; } $this->setPrimaryModel(new $class()); return $this->_model; }
php
public function getPrimaryModel() { if ($model = $this->_model) { return $model; } $class = $this->getPrimaryClass(); if (!$class) { return null; } $this->setPrimaryModel(new $class()); return $this->_model; }
[ "public", "function", "getPrimaryModel", "(", ")", "{", "if", "(", "$", "model", "=", "$", "this", "->", "_model", ")", "{", "return", "$", "model", ";", "}", "$", "class", "=", "$", "this", "->", "getPrimaryClass", "(", ")", ";", "if", "(", "!", ...
Return a primary model object. @return \Titon\Model\Model
[ "Return", "a", "primary", "model", "object", "." ]
274e3810c2cfbb6818a388daaa462ff05de99cbd
https://github.com/titon/model/blob/274e3810c2cfbb6818a388daaa462ff05de99cbd/src/Titon/Model/Relation.php#L232-L246
train
titon/model
src/Titon/Model/Relation.php
Relation.getRelatedModel
public function getRelatedModel() { if ($model = $this->_relatedModel) { return $model; } $class = $this->getRelatedClass(); $this->setRelatedModel(new $class()); return $this->_relatedModel; }
php
public function getRelatedModel() { if ($model = $this->_relatedModel) { return $model; } $class = $this->getRelatedClass(); $this->setRelatedModel(new $class()); return $this->_relatedModel; }
[ "public", "function", "getRelatedModel", "(", ")", "{", "if", "(", "$", "model", "=", "$", "this", "->", "_relatedModel", ")", "{", "return", "$", "model", ";", "}", "$", "class", "=", "$", "this", "->", "getRelatedClass", "(", ")", ";", "$", "this",...
Return a related model object. @return \Titon\Model\Model
[ "Return", "a", "related", "model", "object", "." ]
274e3810c2cfbb6818a388daaa462ff05de99cbd
https://github.com/titon/model/blob/274e3810c2cfbb6818a388daaa462ff05de99cbd/src/Titon/Model/Relation.php#L271-L281
train
titon/model
src/Titon/Model/Relation.php
Relation.setPrimaryModel
public function setPrimaryModel(Model $model) { $this->_model = $model; $this->setPrimaryClass(get_class($model)); return $this; }
php
public function setPrimaryModel(Model $model) { $this->_model = $model; $this->setPrimaryClass(get_class($model)); return $this; }
[ "public", "function", "setPrimaryModel", "(", "Model", "$", "model", ")", "{", "$", "this", "->", "_model", "=", "$", "model", ";", "$", "this", "->", "setPrimaryClass", "(", "get_class", "(", "$", "model", ")", ")", ";", "return", "$", "this", ";", ...
Set the primary model object. @param \Titon\Model\Model $model @return $this
[ "Set", "the", "primary", "model", "object", "." ]
274e3810c2cfbb6818a388daaa462ff05de99cbd
https://github.com/titon/model/blob/274e3810c2cfbb6818a388daaa462ff05de99cbd/src/Titon/Model/Relation.php#L420-L425
train
titon/model
src/Titon/Model/Relation.php
Relation.setRelatedModel
public function setRelatedModel(Model $model) { $this->_relatedModel = $model; $this->setRelatedClass(get_class($model)); return $this; }
php
public function setRelatedModel(Model $model) { $this->_relatedModel = $model; $this->setRelatedClass(get_class($model)); return $this; }
[ "public", "function", "setRelatedModel", "(", "Model", "$", "model", ")", "{", "$", "this", "->", "_relatedModel", "=", "$", "model", ";", "$", "this", "->", "setRelatedClass", "(", "get_class", "(", "$", "model", ")", ")", ";", "return", "$", "this", ...
Set the related model object. @param \Titon\Model\Model $model @return $this
[ "Set", "the", "related", "model", "object", "." ]
274e3810c2cfbb6818a388daaa462ff05de99cbd
https://github.com/titon/model/blob/274e3810c2cfbb6818a388daaa462ff05de99cbd/src/Titon/Model/Relation.php#L457-L462
train
remote-office/libx
src/External/SimplePay/User.php
User.setHash
public function setHash($hash) { if(!is_string($hash) || strlen(trim($hash)) == 0) throw new InvalidArgumentException(__METHOD__ . '; Invalid hash, must be a non empty string'); $this->hash = $hash; }
php
public function setHash($hash) { if(!is_string($hash) || strlen(trim($hash)) == 0) throw new InvalidArgumentException(__METHOD__ . '; Invalid hash, must be a non empty string'); $this->hash = $hash; }
[ "public", "function", "setHash", "(", "$", "hash", ")", "{", "if", "(", "!", "is_string", "(", "$", "hash", ")", "||", "strlen", "(", "trim", "(", "$", "hash", ")", ")", "==", "0", ")", "throw", "new", "InvalidArgumentException", "(", "__METHOD__", "...
Set hash of this User @param string $hash @return void
[ "Set", "hash", "of", "this", "User" ]
8baeaae99a6110e7c588bc0388df89a0dc0768b5
https://github.com/remote-office/libx/blob/8baeaae99a6110e7c588bc0388df89a0dc0768b5/src/External/SimplePay/User.php#L72-L78
train
consigliere/components
src/Publishing/Publisher.php
Publisher.publish
public function publish() { if (!$this->console instanceof Command) { $message = "The 'console' property must instance of \\Illuminate\\Console\\Command."; throw new \RuntimeException($message); } if (!$this->getFilesystem()->isDirectory($sourcePath = $this->getSourcePath())) { return; } if (!$this->getFilesystem()->isDirectory($destinationPath = $this->getDestinationPath())) { $this->getFilesystem()->makeDirectory($destinationPath, 0775, true); } if ($this->getFilesystem()->copyDirectory($sourcePath, $destinationPath)) { if ($this->showMessage === true) { $this->console->line("<info>Published</info>: {$this->component->getStudlyName()}"); } } else { $this->console->error($this->error); } }
php
public function publish() { if (!$this->console instanceof Command) { $message = "The 'console' property must instance of \\Illuminate\\Console\\Command."; throw new \RuntimeException($message); } if (!$this->getFilesystem()->isDirectory($sourcePath = $this->getSourcePath())) { return; } if (!$this->getFilesystem()->isDirectory($destinationPath = $this->getDestinationPath())) { $this->getFilesystem()->makeDirectory($destinationPath, 0775, true); } if ($this->getFilesystem()->copyDirectory($sourcePath, $destinationPath)) { if ($this->showMessage === true) { $this->console->line("<info>Published</info>: {$this->component->getStudlyName()}"); } } else { $this->console->error($this->error); } }
[ "public", "function", "publish", "(", ")", "{", "if", "(", "!", "$", "this", "->", "console", "instanceof", "Command", ")", "{", "$", "message", "=", "\"The 'console' property must instance of \\\\Illuminate\\\\Console\\\\Command.\"", ";", "throw", "new", "\\", "Run...
Publish something.
[ "Publish", "something", "." ]
9b08bb111f0b55b0a860ed9c3407eda0d9cc1252
https://github.com/consigliere/components/blob/9b08bb111f0b55b0a860ed9c3407eda0d9cc1252/src/Publishing/Publisher.php#L173-L196
train
dbtlr/php-env-builder
src/EnvWriter.php
EnvWriter.save
public function save(array $answers) { $path = $this->directory . DIRECTORY_SEPARATOR . $this->file; if (!file_exists($path)) { if (!is_writable($this->directory)) { throw new WritableException( sprintf( 'The env file is not present and the directory `%s` is not writeable!', $this->directory ) ); } touch($path); } if (!is_writable($path)) { throw new WritableException(sprintf('The env file `%s` is not writeable!', $path)); } $text = ''; foreach ($answers as $key => $value) { $text .= sprintf("%s=%s\n", $key, $value); } file_put_contents($path, $text); }
php
public function save(array $answers) { $path = $this->directory . DIRECTORY_SEPARATOR . $this->file; if (!file_exists($path)) { if (!is_writable($this->directory)) { throw new WritableException( sprintf( 'The env file is not present and the directory `%s` is not writeable!', $this->directory ) ); } touch($path); } if (!is_writable($path)) { throw new WritableException(sprintf('The env file `%s` is not writeable!', $path)); } $text = ''; foreach ($answers as $key => $value) { $text .= sprintf("%s=%s\n", $key, $value); } file_put_contents($path, $text); }
[ "public", "function", "save", "(", "array", "$", "answers", ")", "{", "$", "path", "=", "$", "this", "->", "directory", ".", "DIRECTORY_SEPARATOR", ".", "$", "this", "->", "file", ";", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", ...
Save the given answers to the env file. @throws WritableException @param array $answers
[ "Save", "the", "given", "answers", "to", "the", "env", "file", "." ]
94b78bcd308d58dc7994164a87e80fe39ed871c7
https://github.com/dbtlr/php-env-builder/blob/94b78bcd308d58dc7994164a87e80fe39ed871c7/src/EnvWriter.php#L32-L59
train
oaugustus/direct-silex-provider
src/Direct/Router/Request.php
Request.getCalls
public function getCalls() { if (null == $this->calls) { $this->calls = $this->extractCalls(); } return $this->calls; }
php
public function getCalls() { if (null == $this->calls) { $this->calls = $this->extractCalls(); } return $this->calls; }
[ "public", "function", "getCalls", "(", ")", "{", "if", "(", "null", "==", "$", "this", "->", "calls", ")", "{", "$", "this", "->", "calls", "=", "$", "this", "->", "extractCalls", "(", ")", ";", "}", "return", "$", "this", "->", "calls", ";", "}"...
Get the direct calls object. @return array
[ "Get", "the", "direct", "calls", "object", "." ]
8d92afdf5ede04c3048cde82b9879de7e1d6c153
https://github.com/oaugustus/direct-silex-provider/blob/8d92afdf5ede04c3048cde82b9879de7e1d6c153/src/Direct/Router/Request.php#L96-L103
train
oaugustus/direct-silex-provider
src/Direct/Router/Request.php
Request.extractCalls
public function extractCalls() { $calls = array(); if ('form' == $this->callType) { $calls[] = new Call($this->post, 'form'); } else { $decoded = json_decode($this->rawPost); $decoded = !is_array($decoded) ? array($decoded) : $decoded; array_walk_recursive($decoded, array($this, 'parseRawToArray')); if ($this->requestDecode) array_walk_recursive($decoded, array($this, 'decode')); foreach ($decoded as $call) { $calls[] = new Call((array)$call, 'single'); } } return $calls; }
php
public function extractCalls() { $calls = array(); if ('form' == $this->callType) { $calls[] = new Call($this->post, 'form'); } else { $decoded = json_decode($this->rawPost); $decoded = !is_array($decoded) ? array($decoded) : $decoded; array_walk_recursive($decoded, array($this, 'parseRawToArray')); if ($this->requestDecode) array_walk_recursive($decoded, array($this, 'decode')); foreach ($decoded as $call) { $calls[] = new Call((array)$call, 'single'); } } return $calls; }
[ "public", "function", "extractCalls", "(", ")", "{", "$", "calls", "=", "array", "(", ")", ";", "if", "(", "'form'", "==", "$", "this", "->", "callType", ")", "{", "$", "calls", "[", "]", "=", "new", "Call", "(", "$", "this", "->", "post", ",", ...
Extract the ExtDirect calls from request. @return array
[ "Extract", "the", "ExtDirect", "calls", "from", "request", "." ]
8d92afdf5ede04c3048cde82b9879de7e1d6c153
https://github.com/oaugustus/direct-silex-provider/blob/8d92afdf5ede04c3048cde82b9879de7e1d6c153/src/Direct/Router/Request.php#L110-L131
train
oaugustus/direct-silex-provider
src/Direct/Router/Request.php
Request.parseRawToArray
private function parseRawToArray(&$value, &$key) { // parse a json string to an array if (is_string($value)) { $pos = substr($value,0,1); if ($pos == '[' || $pos == '(' || $pos == '{') { $json = json_decode($value); } else { $json = $value; } $pos = substr($value,0,1); if ($pos == '[' || $pos == '(' || $pos == '{') { $json = json_decode($value); } else { $json = $value; } if ($json) { $value = $json; } } // if the value is an object, parse it to an array if (is_object($value)) { $value = (array)$value; } // call the recursive function to all keys of array if (is_array($value)) { array_walk_recursive($value, array($this, 'parseRawToArray')); } }
php
private function parseRawToArray(&$value, &$key) { // parse a json string to an array if (is_string($value)) { $pos = substr($value,0,1); if ($pos == '[' || $pos == '(' || $pos == '{') { $json = json_decode($value); } else { $json = $value; } $pos = substr($value,0,1); if ($pos == '[' || $pos == '(' || $pos == '{') { $json = json_decode($value); } else { $json = $value; } if ($json) { $value = $json; } } // if the value is an object, parse it to an array if (is_object($value)) { $value = (array)$value; } // call the recursive function to all keys of array if (is_array($value)) { array_walk_recursive($value, array($this, 'parseRawToArray')); } }
[ "private", "function", "parseRawToArray", "(", "&", "$", "value", ",", "&", "$", "key", ")", "{", "// parse a json string to an array", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "pos", "=", "substr", "(", "$", "value", ",", "0", ",...
Parse a raw http post to a php array. @param mixed $value @param string $key
[ "Parse", "a", "raw", "http", "post", "to", "a", "php", "array", "." ]
8d92afdf5ede04c3048cde82b9879de7e1d6c153
https://github.com/oaugustus/direct-silex-provider/blob/8d92afdf5ede04c3048cde82b9879de7e1d6c153/src/Direct/Router/Request.php#L152-L187
train
SagePHP/System
src/SagePHP/System/Exec.php
Exec.run
public function run() { $process = $this->getProcessExecutor(); $process->setCommandLine($this->getCommand()); $logger = function ($error, $line) { call_user_func_array(array($this, 'logLine'), array($error, $line)); }; return $process->run($logger); }
php
public function run() { $process = $this->getProcessExecutor(); $process->setCommandLine($this->getCommand()); $logger = function ($error, $line) { call_user_func_array(array($this, 'logLine'), array($error, $line)); }; return $process->run($logger); }
[ "public", "function", "run", "(", ")", "{", "$", "process", "=", "$", "this", "->", "getProcessExecutor", "(", ")", ";", "$", "process", "->", "setCommandLine", "(", "$", "this", "->", "getCommand", "(", ")", ")", ";", "$", "logger", "=", "function", ...
executes the command. @return integer the return code of the executed command
[ "executes", "the", "command", "." ]
4fbac093c16c65607e75dc31b54be9593b82c56a
https://github.com/SagePHP/System/blob/4fbac093c16c65607e75dc31b54be9593b82c56a/src/SagePHP/System/Exec.php#L98-L108
train
SagePHP/System
src/SagePHP/System/Exec.php
Exec.logLine
protected function logLine($messageType, $messageText) { switch ($messageType) { case Process::ERR: $typeStr = "[Error]"; break; default: $typeStr = ""; break; } echo sprintf("\n%s %s\n", $typeStr, $messageText); }
php
protected function logLine($messageType, $messageText) { switch ($messageType) { case Process::ERR: $typeStr = "[Error]"; break; default: $typeStr = ""; break; } echo sprintf("\n%s %s\n", $typeStr, $messageText); }
[ "protected", "function", "logLine", "(", "$", "messageType", ",", "$", "messageText", ")", "{", "switch", "(", "$", "messageType", ")", "{", "case", "Process", "::", "ERR", ":", "$", "typeStr", "=", "\"[Error]\"", ";", "break", ";", "default", ":", "$", ...
logs a line from the command output @return [type]
[ "logs", "a", "line", "from", "the", "command", "output" ]
4fbac093c16c65607e75dc31b54be9593b82c56a
https://github.com/SagePHP/System/blob/4fbac093c16c65607e75dc31b54be9593b82c56a/src/SagePHP/System/Exec.php#L137-L149
train
kreta-plugins/VCS
src/Kreta/Component/VCS/EventSubscriber/DoctrineEventSubscriber.php
DoctrineEventSubscriber.postPersist
public function postPersist(LifecycleEventArgs $args) { if ($args->getObject() instanceof CommitInterface) { $this->dispatcher->dispatch(NewCommitEvent::NAME, new NewCommitEvent($args->getObject())); } elseif ($args->getObject() instanceof BranchInterface) { $this->dispatcher->dispatch(NewBranchEvent::NAME, new NewBranchEvent($args->getObject())); } }
php
public function postPersist(LifecycleEventArgs $args) { if ($args->getObject() instanceof CommitInterface) { $this->dispatcher->dispatch(NewCommitEvent::NAME, new NewCommitEvent($args->getObject())); } elseif ($args->getObject() instanceof BranchInterface) { $this->dispatcher->dispatch(NewBranchEvent::NAME, new NewBranchEvent($args->getObject())); } }
[ "public", "function", "postPersist", "(", "LifecycleEventArgs", "$", "args", ")", "{", "if", "(", "$", "args", "->", "getObject", "(", ")", "instanceof", "CommitInterface", ")", "{", "$", "this", "->", "dispatcher", "->", "dispatch", "(", "NewCommitEvent", "...
Handles postPersist event triggered by doctrine. @param \Doctrine\ORM\Event\LifecycleEventArgs $args The arguments
[ "Handles", "postPersist", "event", "triggered", "by", "doctrine", "." ]
0b6daae2b8044d9250adc8009d03a6745370cd2e
https://github.com/kreta-plugins/VCS/blob/0b6daae2b8044d9250adc8009d03a6745370cd2e/src/Kreta/Component/VCS/EventSubscriber/DoctrineEventSubscriber.php#L62-L69
train
NitroXy/php-forms
src/lib/FormUtils.php
FormUtils.serializeAttr
public static function serializeAttr(array $data, array $order=[]){ $attr = []; /* convert data to sorted array */ $sorted = static::sortedAttr($data, $order); foreach ( $sorted as list($key, $value) ){ if ( is_array($value) ){ /* ignore empty arrays */ if ( count($value) === 0 ){ continue; } foreach ( static::_serializeAttrArray($key, $value) as $sub ){ $value = htmlspecialchars($sub[1], ENT_QUOTES | ENT_HTML5); $attr[] = "{$sub[0]}=\"{$value}\""; } } else { if ( $value === true ){ $attr[] = "$key"; } else if ( $value === false ){ /* ignore */ } else { $value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5); $attr[] = "$key=\"$value\""; } } } return implode(' ', $attr); }
php
public static function serializeAttr(array $data, array $order=[]){ $attr = []; /* convert data to sorted array */ $sorted = static::sortedAttr($data, $order); foreach ( $sorted as list($key, $value) ){ if ( is_array($value) ){ /* ignore empty arrays */ if ( count($value) === 0 ){ continue; } foreach ( static::_serializeAttrArray($key, $value) as $sub ){ $value = htmlspecialchars($sub[1], ENT_QUOTES | ENT_HTML5); $attr[] = "{$sub[0]}=\"{$value}\""; } } else { if ( $value === true ){ $attr[] = "$key"; } else if ( $value === false ){ /* ignore */ } else { $value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5); $attr[] = "$key=\"$value\""; } } } return implode(' ', $attr); }
[ "public", "static", "function", "serializeAttr", "(", "array", "$", "data", ",", "array", "$", "order", "=", "[", "]", ")", "{", "$", "attr", "=", "[", "]", ";", "/* convert data to sorted array */", "$", "sorted", "=", "static", "::", "sortedAttr", "(", ...
Takes key-value array and serializes them to a string as 'key="value" foo="bar"'. ['foo' => 'bar'] becomes foo="bar". ['class' => ['foo', 'bar'] becomes class="foo bar" ['data' => ['foo' => 'bar'] becomes data-foo="bar" @param $data Data to serializeattr @param $order Array with predefined order keys should appear in. Keys not in this array will appear last in any order.
[ "Takes", "key", "-", "value", "array", "and", "serializes", "them", "to", "a", "string", "as", "key", "=", "value", "foo", "=", "bar", "." ]
28970779c3b438372c83f4f651a9897a542c1e54
https://github.com/NitroXy/php-forms/blob/28970779c3b438372c83f4f651a9897a542c1e54/src/lib/FormUtils.php#L18-L46
train
zicht/version
src/Zicht/Version/Constraint.php
Constraint.fromString
public static function fromString($constraintExpression) { if (!preg_match('/^(==?|\!=?|~|[<>]=?)?((?:\*|[0-9]+)(?:.(?:\*|[0-9]+))*)(?:\@(\w+))?$/', $constraintExpression, $m)) { throw new \InvalidArgumentException("Constraint expression '$constraintExpression' could not be parsed"); } return new self( !empty($m[1]) ? $m[1] : '=', $m[2], !empty($m[3]) ? $m[3] : 'stable' ); }
php
public static function fromString($constraintExpression) { if (!preg_match('/^(==?|\!=?|~|[<>]=?)?((?:\*|[0-9]+)(?:.(?:\*|[0-9]+))*)(?:\@(\w+))?$/', $constraintExpression, $m)) { throw new \InvalidArgumentException("Constraint expression '$constraintExpression' could not be parsed"); } return new self( !empty($m[1]) ? $m[1] : '=', $m[2], !empty($m[3]) ? $m[3] : 'stable' ); }
[ "public", "static", "function", "fromString", "(", "$", "constraintExpression", ")", "{", "if", "(", "!", "preg_match", "(", "'/^(==?|\\!=?|~|[<>]=?)?((?:\\*|[0-9]+)(?:.(?:\\*|[0-9]+))*)(?:\\@(\\w+))?$/'", ",", "$", "constraintExpression", ",", "$", "m", ")", ")", "{", ...
Construct a Constraint instance based on the passed string constraint. @param string $constraintExpression @return Constraint @throws \InvalidArgumentException
[ "Construct", "a", "Constraint", "instance", "based", "on", "the", "passed", "string", "constraint", "." ]
2653209f2620e1d4a8baf17a0b5b74fd339abba3
https://github.com/zicht/version/blob/2653209f2620e1d4a8baf17a0b5b74fd339abba3/src/Zicht/Version/Constraint.php#L43-L53
train
zicht/version
src/Zicht/Version/Constraint.php
Constraint.match
public function match(Version $version) { $versionStabilityIndex = array_search($version->getStability(), Version::$stabilities); $constraintStabilityIndex = array_search($this->stability, Version::$stabilities); if ($this->compare($versionStabilityIndex, $constraintStabilityIndex) !== 0) { return false; } $numericValues = $version->numeric(); $comparisons = array(); foreach ($this->version as $i => $value) { $comparisons[$i] = $this->compare($numericValues[$i], $value); } switch ($this->operator) { case '=': case '==': // all parts must be equal: return array_filter($comparisons) === array(); break; case '!': case '!=': // any part must be unequal: return array_filter($comparisons) !== array(); break; case '>=': case '<=': case '>': case '<': // the first mismatch is the tie breaker $mismatches = array_filter($comparisons); if (!count($mismatches)) { // if no mismatches, only ok if equality operator return in_array($this->operator, array('<=', '>=')); } else { $first = array_shift($mismatches); return ($this->operator === '<' && $first < 0) || ($this->operator === '<=' && $first < 0) || ($this->operator === '>' && $first > 0) || ($this->operator === '>=' && $first > 0) ; } } throw new \UnexpectedValueException("An unknown edge case was encountered. Is the constraint valid?"); }
php
public function match(Version $version) { $versionStabilityIndex = array_search($version->getStability(), Version::$stabilities); $constraintStabilityIndex = array_search($this->stability, Version::$stabilities); if ($this->compare($versionStabilityIndex, $constraintStabilityIndex) !== 0) { return false; } $numericValues = $version->numeric(); $comparisons = array(); foreach ($this->version as $i => $value) { $comparisons[$i] = $this->compare($numericValues[$i], $value); } switch ($this->operator) { case '=': case '==': // all parts must be equal: return array_filter($comparisons) === array(); break; case '!': case '!=': // any part must be unequal: return array_filter($comparisons) !== array(); break; case '>=': case '<=': case '>': case '<': // the first mismatch is the tie breaker $mismatches = array_filter($comparisons); if (!count($mismatches)) { // if no mismatches, only ok if equality operator return in_array($this->operator, array('<=', '>=')); } else { $first = array_shift($mismatches); return ($this->operator === '<' && $first < 0) || ($this->operator === '<=' && $first < 0) || ($this->operator === '>' && $first > 0) || ($this->operator === '>=' && $first > 0) ; } } throw new \UnexpectedValueException("An unknown edge case was encountered. Is the constraint valid?"); }
[ "public", "function", "match", "(", "Version", "$", "version", ")", "{", "$", "versionStabilityIndex", "=", "array_search", "(", "$", "version", "->", "getStability", "(", ")", ",", "Version", "::", "$", "stabilities", ")", ";", "$", "constraintStabilityIndex"...
Match the constraint against the passed version. @param Version $version @return bool @throws \UnexpectedValueException
[ "Match", "the", "constraint", "against", "the", "passed", "version", "." ]
2653209f2620e1d4a8baf17a0b5b74fd339abba3
https://github.com/zicht/version/blob/2653209f2620e1d4a8baf17a0b5b74fd339abba3/src/Zicht/Version/Constraint.php#L83-L129
train
Attibee/Bumble-Form
src/Element/Element.php
Element.setAttribute
public function setAttribute( $attr, $value ) { //data-* attribute or in valid attribute array if( strpos( $attr, 'data-' ) === 0 || in_array( $attr, $this->validAttributes ) ) { $this->attrs[$attr] = $value; } else { throw new Exception\InvalidAttributeException( $attr ); } }
php
public function setAttribute( $attr, $value ) { //data-* attribute or in valid attribute array if( strpos( $attr, 'data-' ) === 0 || in_array( $attr, $this->validAttributes ) ) { $this->attrs[$attr] = $value; } else { throw new Exception\InvalidAttributeException( $attr ); } }
[ "public", "function", "setAttribute", "(", "$", "attr", ",", "$", "value", ")", "{", "//data-* attribute or in valid attribute array\r", "if", "(", "strpos", "(", "$", "attr", ",", "'data-'", ")", "===", "0", "||", "in_array", "(", "$", "attr", ",", "$", "...
Sets an attribute given the name and value. @param $attr the name of the attribute @param $value the value of the attribute @throws Exception\InvalidAttributeException if an invalid attribute is provided
[ "Sets", "an", "attribute", "given", "the", "name", "and", "value", "." ]
546c4b01806c68d8ffc09766f74dc157d9ab4960
https://github.com/Attibee/Bumble-Form/blob/546c4b01806c68d8ffc09766f74dc157d9ab4960/src/Element/Element.php#L57-L64
train
Attibee/Bumble-Form
src/Element/Element.php
Element.getAttribute
public function getAttribute( $name ) { if( key_exists( $name, $this->attrs ) ) { return $this->attrs[$name]; } else { return null; } }
php
public function getAttribute( $name ) { if( key_exists( $name, $this->attrs ) ) { return $this->attrs[$name]; } else { return null; } }
[ "public", "function", "getAttribute", "(", "$", "name", ")", "{", "if", "(", "key_exists", "(", "$", "name", ",", "$", "this", "->", "attrs", ")", ")", "{", "return", "$", "this", "->", "attrs", "[", "$", "name", "]", ";", "}", "else", "{", "retu...
Gets an attribute given the attribute name. @param $name The name of the attribute.
[ "Gets", "an", "attribute", "given", "the", "attribute", "name", "." ]
546c4b01806c68d8ffc09766f74dc157d9ab4960
https://github.com/Attibee/Bumble-Form/blob/546c4b01806c68d8ffc09766f74dc157d9ab4960/src/Element/Element.php#L83-L89
train
Attibee/Bumble-Form
src/Element/Element.php
Element.getHTML
public function getHTML() { $tag = "<" . $this->name; $q = $this->quoteType; //build attribute strings foreach( $this->attrs as $name=>$value ) { //if true, such as CHECKED, we just add the name if( $value === true ) { $tag .= " $name"; } else if( is_string( $value ) ) { //if it's a string, we add attr="value" $tag .= " {$name}={$q}{$value}{$q}"; } } //short tag? close it and return if( $this->isShortTag ) { $tag .= ' />'; return $tag; } //not a short tag, close it $tag .= '>'; //add the children if they exist if( $this->hasChildren() ) { foreach( $this->getChildren() as $child ) { $tag .= $child->getHTML(); } } //closing tag $tag .= "</{$this->name}>"; return $tag; }
php
public function getHTML() { $tag = "<" . $this->name; $q = $this->quoteType; //build attribute strings foreach( $this->attrs as $name=>$value ) { //if true, such as CHECKED, we just add the name if( $value === true ) { $tag .= " $name"; } else if( is_string( $value ) ) { //if it's a string, we add attr="value" $tag .= " {$name}={$q}{$value}{$q}"; } } //short tag? close it and return if( $this->isShortTag ) { $tag .= ' />'; return $tag; } //not a short tag, close it $tag .= '>'; //add the children if they exist if( $this->hasChildren() ) { foreach( $this->getChildren() as $child ) { $tag .= $child->getHTML(); } } //closing tag $tag .= "</{$this->name}>"; return $tag; }
[ "public", "function", "getHTML", "(", ")", "{", "$", "tag", "=", "\"<\"", ".", "$", "this", "->", "name", ";", "$", "q", "=", "$", "this", "->", "quoteType", ";", "//build attribute strings\r", "foreach", "(", "$", "this", "->", "attrs", "as", "$", "...
Parses the class data and outputs the HTML. @return the HTML string of the element
[ "Parses", "the", "class", "data", "and", "outputs", "the", "HTML", "." ]
546c4b01806c68d8ffc09766f74dc157d9ab4960
https://github.com/Attibee/Bumble-Form/blob/546c4b01806c68d8ffc09766f74dc157d9ab4960/src/Element/Element.php#L96-L131
train
Attibee/Bumble-Form
src/Element/Element.php
Element.setQuote
public function setQuote( $type ) { $this->quoteType = $quoteType == self::SINGLE_QUOTE ? self::SINGLE_QUOTE : self::DOUBLE_QUOTE; }
php
public function setQuote( $type ) { $this->quoteType = $quoteType == self::SINGLE_QUOTE ? self::SINGLE_QUOTE : self::DOUBLE_QUOTE; }
[ "public", "function", "setQuote", "(", "$", "type", ")", "{", "$", "this", "->", "quoteType", "=", "$", "quoteType", "==", "self", "::", "SINGLE_QUOTE", "?", "self", "::", "SINGLE_QUOTE", ":", "self", "::", "DOUBLE_QUOTE", ";", "}" ]
Sets the type of quote to use. Default quote type is double quotes. @param $type Element::DOUBLE_QUOTE or Element::SINGLE_QUOTE
[ "Sets", "the", "type", "of", "quote", "to", "use", ".", "Default", "quote", "type", "is", "double", "quotes", "." ]
546c4b01806c68d8ffc09766f74dc157d9ab4960
https://github.com/Attibee/Bumble-Form/blob/546c4b01806c68d8ffc09766f74dc157d9ab4960/src/Element/Element.php#L137-L139
train
Attibee/Bumble-Form
src/Element/Element.php
Element.addValidAttributes
protected function addValidAttributes( $attrs ) { foreach( $attrs as $attr ) { //add if string if( is_string( $attr ) ) { $this->validAttributes[] = $attr; } } }
php
protected function addValidAttributes( $attrs ) { foreach( $attrs as $attr ) { //add if string if( is_string( $attr ) ) { $this->validAttributes[] = $attr; } } }
[ "protected", "function", "addValidAttributes", "(", "$", "attrs", ")", "{", "foreach", "(", "$", "attrs", "as", "$", "attr", ")", "{", "//add if string\r", "if", "(", "is_string", "(", "$", "attr", ")", ")", "{", "$", "this", "->", "validAttributes", "["...
Adds array of attributes to the valid attributes. @param $attrs an array of attributes
[ "Adds", "array", "of", "attributes", "to", "the", "valid", "attributes", "." ]
546c4b01806c68d8ffc09766f74dc157d9ab4960
https://github.com/Attibee/Bumble-Form/blob/546c4b01806c68d8ffc09766f74dc157d9ab4960/src/Element/Element.php#L155-L162
train
agalbourdin/agl-core
src/Mysql/Query/Select.php
Select._formatOrder
private function _formatOrder() { $orders = array(); if (isset($this->_order[DbInterface::ORDER_RAND])) { $orders[] = 'RAND()'; } else { foreach ($this->_order as $field => $order) { $orders[] = "`$field` $order"; } } return ' ORDER BY ' . implode(', ', $orders); }
php
private function _formatOrder() { $orders = array(); if (isset($this->_order[DbInterface::ORDER_RAND])) { $orders[] = 'RAND()'; } else { foreach ($this->_order as $field => $order) { $orders[] = "`$field` $order"; } } return ' ORDER BY ' . implode(', ', $orders); }
[ "private", "function", "_formatOrder", "(", ")", "{", "$", "orders", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "this", "->", "_order", "[", "DbInterface", "::", "ORDER_RAND", "]", ")", ")", "{", "$", "orders", "[", "]", "=", "'RAND...
Format the order fields to be included into the query. @return string
[ "Format", "the", "order", "fields", "to", "be", "included", "into", "the", "query", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Mysql/Query/Select.php#L36-L49
train
agalbourdin/agl-core
src/Mysql/Query/Select.php
Select._doQuery
private function _doQuery($pLimitOne) { try { if (empty($this->_fields)) { $fields = '*'; } else { $fields = '`' . implode('`, `', $this->_fields) . '`'; } $query = " SELECT $fields FROM `" . $this->getDbPrefix() . $this->_dbContainer . "`"; if ($this->_conditions->count()) { $query .= " WHERE " . $this->_conditions->getPreparedConditions($this->_dbContainer) . ""; } if (! empty($this->_order)) { $query .= $this->_formatOrder(); } if ($pLimitOne) { $query .= ' LIMIT 0, 1'; } else if ($this->_limit !== NULL or $this->_skip !== NULL) { $query .= $this->_formatLimit(); } $this->_stm = Agl::app()->getDb()->getConnection()->prepare($query, array( PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL )); if (! $this->_stm->execute($this->_conditions->getPreparedValues())) { $error = $this->_stm->errorInfo(); throw new Exception("The select query failed (table '" . $this->getDbPrefix() . $this->_dbContainer . "') with message '" . $error[2] . "'"); } if (Agl::app()->isDebugMode()) { Agl::app()->getDb()->incrementCounter(); } return $this; } catch (Exception $e) { throw new Exception($e); } }
php
private function _doQuery($pLimitOne) { try { if (empty($this->_fields)) { $fields = '*'; } else { $fields = '`' . implode('`, `', $this->_fields) . '`'; } $query = " SELECT $fields FROM `" . $this->getDbPrefix() . $this->_dbContainer . "`"; if ($this->_conditions->count()) { $query .= " WHERE " . $this->_conditions->getPreparedConditions($this->_dbContainer) . ""; } if (! empty($this->_order)) { $query .= $this->_formatOrder(); } if ($pLimitOne) { $query .= ' LIMIT 0, 1'; } else if ($this->_limit !== NULL or $this->_skip !== NULL) { $query .= $this->_formatLimit(); } $this->_stm = Agl::app()->getDb()->getConnection()->prepare($query, array( PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL )); if (! $this->_stm->execute($this->_conditions->getPreparedValues())) { $error = $this->_stm->errorInfo(); throw new Exception("The select query failed (table '" . $this->getDbPrefix() . $this->_dbContainer . "') with message '" . $error[2] . "'"); } if (Agl::app()->isDebugMode()) { Agl::app()->getDb()->incrementCounter(); } return $this; } catch (Exception $e) { throw new Exception($e); } }
[ "private", "function", "_doQuery", "(", "$", "pLimitOne", ")", "{", "try", "{", "if", "(", "empty", "(", "$", "this", "->", "_fields", ")", ")", "{", "$", "fields", "=", "'*'", ";", "}", "else", "{", "$", "fields", "=", "'`'", ".", "implode", "("...
Commit the select query to the database. @return Select
[ "Commit", "the", "select", "query", "to", "the", "database", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Mysql/Query/Select.php#L78-L127
train
agalbourdin/agl-core
src/Mysql/Query/Select.php
Select.fetchAll
public function fetchAll($pSingle = false) { if ($this->_stm === false) { return array(); } if ($pSingle) { return $this->_stm->fetch(PDO::FETCH_ASSOC); } return $this->_stm->fetchAll(PDO::FETCH_ASSOC); }
php
public function fetchAll($pSingle = false) { if ($this->_stm === false) { return array(); } if ($pSingle) { return $this->_stm->fetch(PDO::FETCH_ASSOC); } return $this->_stm->fetchAll(PDO::FETCH_ASSOC); }
[ "public", "function", "fetchAll", "(", "$", "pSingle", "=", "false", ")", "{", "if", "(", "$", "this", "->", "_stm", "===", "false", ")", "{", "return", "array", "(", ")", ";", "}", "if", "(", "$", "pSingle", ")", "{", "return", "$", "this", "->"...
Fetch all the results as array. @param bool $pSingle Return a single row or an array of rows. @return array
[ "Fetch", "all", "the", "results", "as", "array", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Mysql/Query/Select.php#L169-L180
train
agalbourdin/agl-core
src/Mysql/Query/Select.php
Select.fetchAllAsItems
public function fetchAllAsItems($pSingle = false) { $data = array(); if ($this->_stm === false) { return $data; } while ($row = $this->_stm->fetch(PDO::FETCH_ASSOC)) { if ($pSingle) { return Agl::getModel($this->_dbContainer, $row); } $data[] = Agl::getModel($this->_dbContainer, $row); } return $data; }
php
public function fetchAllAsItems($pSingle = false) { $data = array(); if ($this->_stm === false) { return $data; } while ($row = $this->_stm->fetch(PDO::FETCH_ASSOC)) { if ($pSingle) { return Agl::getModel($this->_dbContainer, $row); } $data[] = Agl::getModel($this->_dbContainer, $row); } return $data; }
[ "public", "function", "fetchAllAsItems", "(", "$", "pSingle", "=", "false", ")", "{", "$", "data", "=", "array", "(", ")", ";", "if", "(", "$", "this", "->", "_stm", "===", "false", ")", "{", "return", "$", "data", ";", "}", "while", "(", "$", "r...
Fetch all the results as array of items. @param bool $pSingle Return a single Item or an array of Items. @return array|Item
[ "Fetch", "all", "the", "results", "as", "array", "of", "items", "." ]
1db556f9a49488aa9fab6887fefb7141a79ad97d
https://github.com/agalbourdin/agl-core/blob/1db556f9a49488aa9fab6887fefb7141a79ad97d/src/Mysql/Query/Select.php#L188-L205
train
gios-asu/nectary
src/configuration/configuration.php
Configuration.add
public function add( $key, $value ) { if ( ! array_key_exists( $key, $this->attributes ) ) { $this->attributes[ $key ] = $value; } else { if ( ! \is_array( $this->attributes[ $key ] ) ) { $this->attributes[ $key ] = array( $this->attributes[ $key ], $value ); } else { $this->attributes[ $key ][] = $value; } } }
php
public function add( $key, $value ) { if ( ! array_key_exists( $key, $this->attributes ) ) { $this->attributes[ $key ] = $value; } else { if ( ! \is_array( $this->attributes[ $key ] ) ) { $this->attributes[ $key ] = array( $this->attributes[ $key ], $value ); } else { $this->attributes[ $key ][] = $value; } } }
[ "public", "function", "add", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "attributes", ")", ")", "{", "$", "this", "->", "attributes", "[", "$", "key", "]", "=", "$", ...
Add to an new or existing value. This will promote scalar values into an array to contain multiple values. @param string $key @param mixed $value
[ "Add", "to", "an", "new", "or", "existing", "value", ".", "This", "will", "promote", "scalar", "values", "into", "an", "array", "to", "contain", "multiple", "values", "." ]
f972c737a9036a3090652950a1309a62c07d86c0
https://github.com/gios-asu/nectary/blob/f972c737a9036a3090652950a1309a62c07d86c0/src/configuration/configuration.php#L48-L58
train
maestrano/maestrano-php
lib/Saml/Response.php
Maestrano_Saml_Response.getAttributes
public function getAttributes() { if ($this->cachedAttributes != null) { return $this->cachedAttributes; } $entries = $this->_queryAssertion('/saml:AttributeStatement/saml:Attribute'); $this->cachedAttributes = array(); /** $entry DOMNode */ foreach ($entries as $entry) { $attributeName = $entry->attributes->getNamedItem('Name')->nodeValue; // Keep only one value for each entry type foreach ($entry->childNodes as $childNode) { if (is_a($childNode, 'DOMElement') && preg_match('/AttributeValue/',$childNode->tagName)){ $attributeValue = $childNode->nodeValue; } } $this->cachedAttributes[$attributeName] = $attributeValue; } return $this->cachedAttributes; }
php
public function getAttributes() { if ($this->cachedAttributes != null) { return $this->cachedAttributes; } $entries = $this->_queryAssertion('/saml:AttributeStatement/saml:Attribute'); $this->cachedAttributes = array(); /** $entry DOMNode */ foreach ($entries as $entry) { $attributeName = $entry->attributes->getNamedItem('Name')->nodeValue; // Keep only one value for each entry type foreach ($entry->childNodes as $childNode) { if (is_a($childNode, 'DOMElement') && preg_match('/AttributeValue/',$childNode->tagName)){ $attributeValue = $childNode->nodeValue; } } $this->cachedAttributes[$attributeName] = $attributeValue; } return $this->cachedAttributes; }
[ "public", "function", "getAttributes", "(", ")", "{", "if", "(", "$", "this", "->", "cachedAttributes", "!=", "null", ")", "{", "return", "$", "this", "->", "cachedAttributes", ";", "}", "$", "entries", "=", "$", "this", "->", "_queryAssertion", "(", "'/...
Return the attributes of a SAML response @return array
[ "Return", "the", "attributes", "of", "a", "SAML", "response" ]
757cbefb0f0bf07cb35ea7442041d9bfdcce1558
https://github.com/maestrano/maestrano-php/blob/757cbefb0f0bf07cb35ea7442041d9bfdcce1558/lib/Saml/Response.php#L79-L102
train
rikby/console-helper
src/Helper/SimpleQuestionHelper.php
SimpleQuestionHelper.getFormattedQuestion
public function getFormattedQuestion($question, $default, array $options) { if ($this->isList($options)) { /** * Options list mode */ return $this->getFormattedListQuestion($question, $default, $options); } else { /** * Simple options mode */ return $this->getFormattedSimpleQuestion($question, $default, $options); } }
php
public function getFormattedQuestion($question, $default, array $options) { if ($this->isList($options)) { /** * Options list mode */ return $this->getFormattedListQuestion($question, $default, $options); } else { /** * Simple options mode */ return $this->getFormattedSimpleQuestion($question, $default, $options); } }
[ "public", "function", "getFormattedQuestion", "(", "$", "question", ",", "$", "default", ",", "array", "$", "options", ")", "{", "if", "(", "$", "this", "->", "isList", "(", "$", "options", ")", ")", "{", "/**\n * Options list mode\n */",...
Get formatted question @param string $question @param string $default @param array $options @return string
[ "Get", "formatted", "question" ]
c618daf79e01439ea6cd60a75c9ff5b09de9b75d
https://github.com/rikby/console-helper/blob/c618daf79e01439ea6cd60a75c9ff5b09de9b75d/src/Helper/SimpleQuestionHelper.php#L94-L107
train
rikby/console-helper
src/Helper/SimpleQuestionHelper.php
SimpleQuestionHelper.getFormattedListQuestion
protected function getFormattedListQuestion($question, $default, array $options) { $list = ''; foreach ($options as $key => $title) { $list .= " $key - $title".($default == $key ? ' (Default)' : '').PHP_EOL; } return $question.":\n".$list; }
php
protected function getFormattedListQuestion($question, $default, array $options) { $list = ''; foreach ($options as $key => $title) { $list .= " $key - $title".($default == $key ? ' (Default)' : '').PHP_EOL; } return $question.":\n".$list; }
[ "protected", "function", "getFormattedListQuestion", "(", "$", "question", ",", "$", "default", ",", "array", "$", "options", ")", "{", "$", "list", "=", "''", ";", "foreach", "(", "$", "options", "as", "$", "key", "=>", "$", "title", ")", "{", "$", ...
Get formatted "list" question @param array $question @param string|int $default @param array $options @return string
[ "Get", "formatted", "list", "question" ]
c618daf79e01439ea6cd60a75c9ff5b09de9b75d
https://github.com/rikby/console-helper/blob/c618daf79e01439ea6cd60a75c9ff5b09de9b75d/src/Helper/SimpleQuestionHelper.php#L128-L136
train