repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
amarcinkowski/hospitalplugin | src/WP/Menu.php | Menu.registerPage | private function registerPage($title, $capabilities, $url_param, $class, $callback, $type)
{
if ($type == 'submenu') {
add_submenu_page($this->url, $title, $title, $capabilities, $url_param, array(
$class,
$callback
));
} else {
add_menu_page($title, $title, $capabilities, $url_param, array(
$class,
$callback
));
}
} | php | private function registerPage($title, $capabilities, $url_param, $class, $callback, $type)
{
if ($type == 'submenu') {
add_submenu_page($this->url, $title, $title, $capabilities, $url_param, array(
$class,
$callback
));
} else {
add_menu_page($title, $title, $capabilities, $url_param, array(
$class,
$callback
));
}
} | register using add_submenu_page | https://github.com/amarcinkowski/hospitalplugin/blob/acdc2be5157abfbdcafb4dcf6c6ba505e291263f/src/WP/Menu.php#L86-L99 |
luoxiaojun1992/lb_framework | components/queues/drivers/BaseQueue.php | BaseQueue.serialize | protected function serialize($unserialized_data)
{
switch ($this->serializer) {
case self::SERIALIZER_JSON:
break;
case self::SERIALIZER_PHP:
//todo not allowed to contain closure
return Lb::app()->serialize($unserialized_data);
}
return $unserialized_data;
} | php | protected function serialize($unserialized_data)
{
switch ($this->serializer) {
case self::SERIALIZER_JSON:
break;
case self::SERIALIZER_PHP:
//todo not allowed to contain closure
return Lb::app()->serialize($unserialized_data);
}
return $unserialized_data;
} | Serializer
@param $unserialized_data
@return string | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/queues/drivers/BaseQueue.php#L41-L52 |
luoxiaojun1992/lb_framework | components/queues/drivers/BaseQueue.php | BaseQueue.deserialize | protected function deserialize($serialized_data)
{
switch ($this->serializer) {
case self::SERIALIZER_JSON:
break;
case self::SERIALIZER_PHP:
//todo not allowed to contain closure
return Lb::app()->unserialize($serialized_data);
}
return $serialized_data;
} | php | protected function deserialize($serialized_data)
{
switch ($this->serializer) {
case self::SERIALIZER_JSON:
break;
case self::SERIALIZER_PHP:
//todo not allowed to contain closure
return Lb::app()->unserialize($serialized_data);
}
return $serialized_data;
} | Deserializer
@param $serialized_data
@return mixed | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/queues/drivers/BaseQueue.php#L60-L71 |
ProgMiner/php-datagen | app/Command/Compile.php | Compile.compileFile | protected function compileFile(
string $file,
Compiler $compiler,
Style\OutputStyle $io,
PrettyPrinterAbstract $printer,
bool $force = true,
bool $checkTime = true
) {
$phpParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7);
$phpAST = $phpParser->parse(file_get_contents($file));
$phpWalker = new PHPWalker();
$phpTraverser = new NodeTraverser();
$phpTraverser->addVisitor($phpWalker);
$phpTraverser->traverse($phpAST);
$pdglParser = new PDGL\Parser(
new PDGL\Lexer($phpWalker->getCode())
);
$nodes = [];
try {
$nodes = $pdglParser->yyparse() ?? [];
} catch (Exception\Parsing $e) {
$io->error("Parsing error: {$e->getMessage()}");
return;
}
$node = $phpWalker->getNode();
$nodes = (function($classes) use($node) {
$ret = [];
foreach ($classes as $class) {
$node->class = $class;
$ret[] = clone $node;
}
return $ret;
})($nodes);
$editTime = -1;
if ($checkTime) {
$editTime = filemtime($file);
}
foreach ($nodes as $node) {
$this->compileNode($node, $compiler, $io, $printer, $force, $editTime);
}
} | php | protected function compileFile(
string $file,
Compiler $compiler,
Style\OutputStyle $io,
PrettyPrinterAbstract $printer,
bool $force = true,
bool $checkTime = true
) {
$phpParser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7);
$phpAST = $phpParser->parse(file_get_contents($file));
$phpWalker = new PHPWalker();
$phpTraverser = new NodeTraverser();
$phpTraverser->addVisitor($phpWalker);
$phpTraverser->traverse($phpAST);
$pdglParser = new PDGL\Parser(
new PDGL\Lexer($phpWalker->getCode())
);
$nodes = [];
try {
$nodes = $pdglParser->yyparse() ?? [];
} catch (Exception\Parsing $e) {
$io->error("Parsing error: {$e->getMessage()}");
return;
}
$node = $phpWalker->getNode();
$nodes = (function($classes) use($node) {
$ret = [];
foreach ($classes as $class) {
$node->class = $class;
$ret[] = clone $node;
}
return $ret;
})($nodes);
$editTime = -1;
if ($checkTime) {
$editTime = filemtime($file);
}
foreach ($nodes as $node) {
$this->compileNode($node, $compiler, $io, $printer, $force, $editTime);
}
} | TODO Config | https://github.com/ProgMiner/php-datagen/blob/a78f29223bdbb1926c3c21371a30d2b09041335b/app/Command/Compile.php#L55-L104 |
LoggerEssentials/LoggerEssentials | src/Loggers/CallbackLogger.php | CallbackLogger.log | public function log($level, $message, array $context = array()) {
try {
call_user_func($this->callable, $level, $message, $context);
} catch(\Exception $e) {
}
} | php | public function log($level, $message, array $context = array()) {
try {
call_user_func($this->callable, $level, $message, $context);
} catch(\Exception $e) {
}
} | Logs with an arbitrary level.
@param mixed $level
@param string $message
@param array $context
@return void | https://github.com/LoggerEssentials/LoggerEssentials/blob/f32f9b865eacfccced90697f3eb69dc4ad80dc96/src/Loggers/CallbackLogger.php#L25-L30 |
schpill/thin | src/Cache.php | Cache.retrieve | protected function retrieve($key)
{
if (!File::exists($this->path . $key)) {
return null;
}
// File based caches store have the expiration timestamp stored in
// UNIX format prepended to their contents. We'll compare the
// timestamp to the current time when we read the file.
if (time() >= substr($cache = fgc($this->path . $key), 0, 10)) {
return $this->forget($key);
}
return unserialize(substr($cache, 10));
} | php | protected function retrieve($key)
{
if (!File::exists($this->path . $key)) {
return null;
}
// File based caches store have the expiration timestamp stored in
// UNIX format prepended to their contents. We'll compare the
// timestamp to the current time when we read the file.
if (time() >= substr($cache = fgc($this->path . $key), 0, 10)) {
return $this->forget($key);
}
return unserialize(substr($cache, 10));
} | Retrieve an item from the cache driver.
@param string $key
@return mixed | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Cache.php#L42-L56 |
schpill/thin | src/Cache.php | Cache.forget | public function forget($key)
{
if (File::exists($this->path . $key)) {
unlink($this->path . $key);
}
} | php | public function forget($key)
{
if (File::exists($this->path . $key)) {
unlink($this->path . $key);
}
} | Delete an item from the cache.
@param string $key
@return void | https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Cache.php#L95-L100 |
zhenggg/easy-ihuyi | src/Gateways/ErrorLogGateway.php | ErrorLogGateway.send | public function send($to)
{
$this->params['content'] = sprintf(
"[%s] to: %s, message: \"%s\", data: %s\n",
date('Y-m-d H:i:s'),
$to,
addcslashes($this->params['content'], '"'),
json_encode($this->params)
);
return error_log($this->params['content'], 3, Config::get('file', ini_get('error_log')));
} | php | public function send($to)
{
$this->params['content'] = sprintf(
"[%s] to: %s, message: \"%s\", data: %s\n",
date('Y-m-d H:i:s'),
$to,
addcslashes($this->params['content'], '"'),
json_encode($this->params)
);
return error_log($this->params['content'], 3, Config::get('file', ini_get('error_log')));
} | Send a short message.
@param string|int $to
@return mixed | https://github.com/zhenggg/easy-ihuyi/blob/90ff0da31de3974e2a7b6e59f76f8f1ccec06aca/src/Gateways/ErrorLogGateway.php#L23-L33 |
vincenttouzet/BootstrapFormBundle | Form/Type/DatePickerType.php | DatePickerType.buildForm | public function buildForm(FormBuilderInterface $builder, array $options)
{
$dateFormat = \IntlDateFormatter::MEDIUM;
$timeFormat = \IntlDateFormatter::NONE;
$calendar = \IntlDateFormatter::GREGORIAN;
$pattern = $options['format'];
if (!in_array($dateFormat, self::$acceptedFormats, true)) {
throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
}
$builder->addViewTransformer(new DateTimeToLocalizedStringTransformer(
null,
null,
$dateFormat,
$timeFormat,
$calendar,
$pattern
));
if ( $options['input'] == 'single_text' ) {
$builder->addModelTransformer(new ReversedTransformer(
new DateTimeToStringTransformer(null, null, 'Y-m-d')
));
}
} | php | public function buildForm(FormBuilderInterface $builder, array $options)
{
$dateFormat = \IntlDateFormatter::MEDIUM;
$timeFormat = \IntlDateFormatter::NONE;
$calendar = \IntlDateFormatter::GREGORIAN;
$pattern = $options['format'];
if (!in_array($dateFormat, self::$acceptedFormats, true)) {
throw new InvalidOptionsException('The "format" option must be one of the IntlDateFormatter constants (FULL, LONG, MEDIUM, SHORT) or a string representing a custom format.');
}
$builder->addViewTransformer(new DateTimeToLocalizedStringTransformer(
null,
null,
$dateFormat,
$timeFormat,
$calendar,
$pattern
));
if ( $options['input'] == 'single_text' ) {
$builder->addModelTransformer(new ReversedTransformer(
new DateTimeToStringTransformer(null, null, 'Y-m-d')
));
}
} | {@inheritdoc} | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/Type/DatePickerType.php#L49-L74 |
vincenttouzet/BootstrapFormBundle | Form/Type/DatePickerType.php | DatePickerType.buildView | public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars = array_replace($view->vars, array(
'format' => $options['format']
));
$view->vars['attr']['data-week-start'] = $options['week_start'];
$view->vars['attr']['data-calendar-weeks'] = json_encode($options['calendar_weeks']);
$view->vars['attr']['data-start-date'] = $options['start_date'];
$view->vars['attr']['data-end-date'] = $options['end_date'];
$view->vars['attr']['data-days-of-week-disabled'] = $options['days_of_week_disabled'];
$view->vars['attr']['data-autoclose'] = json_encode($options['autoclose']);
$view->vars['attr']['data-start-view'] = $options['start_view'];
$view->vars['attr']['data-min-view-mode'] = $options['min_view_mode'];
$today_btn = $options['today_btn'];
if (is_bool($today_btn)) {
$today_btn = json_encode($today_btn);
}
$view->vars['attr']['data-today-btn'] = $today_btn;
$view->vars['attr']['data-today-highlight'] = json_encode($options['today_highlight']);
$view->vars['attr']['data-clear-btn'] = json_encode($options['clear_btn']);
$language = $options['language'];
if ($language === false) {
$language = $this->getLocale();
}
$view->vars['attr']['data-language'] = $language;
} | php | public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars = array_replace($view->vars, array(
'format' => $options['format']
));
$view->vars['attr']['data-week-start'] = $options['week_start'];
$view->vars['attr']['data-calendar-weeks'] = json_encode($options['calendar_weeks']);
$view->vars['attr']['data-start-date'] = $options['start_date'];
$view->vars['attr']['data-end-date'] = $options['end_date'];
$view->vars['attr']['data-days-of-week-disabled'] = $options['days_of_week_disabled'];
$view->vars['attr']['data-autoclose'] = json_encode($options['autoclose']);
$view->vars['attr']['data-start-view'] = $options['start_view'];
$view->vars['attr']['data-min-view-mode'] = $options['min_view_mode'];
$today_btn = $options['today_btn'];
if (is_bool($today_btn)) {
$today_btn = json_encode($today_btn);
}
$view->vars['attr']['data-today-btn'] = $today_btn;
$view->vars['attr']['data-today-highlight'] = json_encode($options['today_highlight']);
$view->vars['attr']['data-clear-btn'] = json_encode($options['clear_btn']);
$language = $options['language'];
if ($language === false) {
$language = $this->getLocale();
}
$view->vars['attr']['data-language'] = $language;
} | {@inheritdoc} | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/Type/DatePickerType.php#L79-L104 |
andyburton/Sonic-Framework | src/View/JSON.php | JSON.display | public function display ($output = TRUE)
{
// JSON encode
$response = json_encode ($this->response);
// Output
if ($output)
{
// Output headers
header ('Cache-Control: no-cache, must-revalidate');
header ('Content-type: application/json; charset=utf-8');
// Output response
echo $response;
}
// Return
return $response;
} | php | public function display ($output = TRUE)
{
// JSON encode
$response = json_encode ($this->response);
// Output
if ($output)
{
// Output headers
header ('Cache-Control: no-cache, must-revalidate');
header ('Content-type: application/json; charset=utf-8');
// Output response
echo $response;
}
// Return
return $response;
} | Display a template
@param boolean $output Whether to output the rendered template
@return string | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/View/JSON.php#L27-L54 |
graze/csv-token | src/Tokeniser/Token/TokenStore.php | TokenStore.getTokens | public function getTokens($mask = Token::T_ANY)
{
if (!array_key_exists($mask, $this->maskStore)) {
$this->maskStore[$mask] = array_filter($this->tokens, function ($type) use ($mask) {
return $type & $mask;
});
}
return $this->maskStore[$mask];
} | php | public function getTokens($mask = Token::T_ANY)
{
if (!array_key_exists($mask, $this->maskStore)) {
$this->maskStore[$mask] = array_filter($this->tokens, function ($type) use ($mask) {
return $type & $mask;
});
}
return $this->maskStore[$mask];
} | @param int $mask
@return int[] | https://github.com/graze/csv-token/blob/ad11cfc83e7f0cae56da6844f9216bbaf5c8dcb8/src/Tokeniser/Token/TokenStore.php#L44-L53 |
graze/csv-token | src/Tokeniser/Token/TokenStore.php | TokenStore.buildTokens | private function buildTokens(CsvConfigurationInterface $config)
{
$tokens = [
$config->getDelimiter() => Token::T_DELIMITER,
];
if ($config->getQuote() != '') {
$tokens[$config->getQuote()] = Token::T_QUOTE;
if ($config->useDoubleQuotes()) {
$tokens[str_repeat($config->getQuote(), 2)] = Token::T_DOUBLE_QUOTE;
}
}
if ($config->getEscape() != '') {
$tokens[$config->getEscape()] = Token::T_ESCAPE;
}
foreach ($config->getNewLines() as $newLine) {
$tokens[$newLine] = Token::T_NEW_LINE;
}
if (!is_null($config->getNullValue())) {
$tokens[$config->getNullValue()] = Token::T_NULL;
}
foreach ($config->getBoms() as $bom) {
$tokens[$bom] = Token::T_BOM;
}
return $tokens;
} | php | private function buildTokens(CsvConfigurationInterface $config)
{
$tokens = [
$config->getDelimiter() => Token::T_DELIMITER,
];
if ($config->getQuote() != '') {
$tokens[$config->getQuote()] = Token::T_QUOTE;
if ($config->useDoubleQuotes()) {
$tokens[str_repeat($config->getQuote(), 2)] = Token::T_DOUBLE_QUOTE;
}
}
if ($config->getEscape() != '') {
$tokens[$config->getEscape()] = Token::T_ESCAPE;
}
foreach ($config->getNewLines() as $newLine) {
$tokens[$newLine] = Token::T_NEW_LINE;
}
if (!is_null($config->getNullValue())) {
$tokens[$config->getNullValue()] = Token::T_NULL;
}
foreach ($config->getBoms() as $bom) {
$tokens[$bom] = Token::T_BOM;
}
return $tokens;
} | @param CsvConfigurationInterface $config
@return int[] | https://github.com/graze/csv-token/blob/ad11cfc83e7f0cae56da6844f9216bbaf5c8dcb8/src/Tokeniser/Token/TokenStore.php#L60-L88 |
graze/csv-token | src/Tokeniser/Token/TokenStore.php | TokenStore.sort | private function sort()
{
// sort by reverse key length
uksort($this->tokens, function ($first, $second) {
return strlen($second) - strlen($first);
});
} | php | private function sort()
{
// sort by reverse key length
uksort($this->tokens, function ($first, $second) {
return strlen($second) - strlen($first);
});
} | Sort the tokens into reverse key length order | https://github.com/graze/csv-token/blob/ad11cfc83e7f0cae56da6844f9216bbaf5c8dcb8/src/Tokeniser/Token/TokenStore.php#L123-L129 |
aledefreitas/zlx_security | src/Security/Security.php | Security.validHmac | private function validHmac($hmac, $compareHmac)
{
if(function_exists("hash_equals")) {
return hash_equals($hmac, $compareHmac);
}
$hashLength = mb_strlen($hmac, '8bit');
$compareLength = mb_strlen($compareHmac, '8bit');
if ($hashLength !== $compareLength) {
return false;
}
$result = 0;
for ($i = 0; $i < $hashLength; $i++) {
$result |= (ord($hmac[$i]) ^ ord($compareHmac[$i]));
}
return $result === 0;
} | php | private function validHmac($hmac, $compareHmac)
{
if(function_exists("hash_equals")) {
return hash_equals($hmac, $compareHmac);
}
$hashLength = mb_strlen($hmac, '8bit');
$compareLength = mb_strlen($compareHmac, '8bit');
if ($hashLength !== $compareLength) {
return false;
}
$result = 0;
for ($i = 0; $i < $hashLength; $i++) {
$result |= (ord($hmac[$i]) ^ ord($compareHmac[$i]));
}
return $result === 0;
} | Validates if the provided hmac is equal to the expected hmac
@param string $hmac Provided hmac
@param string $compareHmac Expected hmac
@return boolean | https://github.com/aledefreitas/zlx_security/blob/3281db6bacfff51695835e1e6fc5bbddcf1a028a/src/Security/Security.php#L66-L86 |
aledefreitas/zlx_security | src/Security/Security.php | Security.encrypt | public function encrypt($original_string, $cipher_key)
{
$cipher_key = $this->_genKey($cipher_key);
$ivSize = openssl_cipher_iv_length('AES-256-CBC');
$iv = openssl_random_pseudo_bytes($ivSize);
$cipher_text = $iv . openssl_encrypt($original_string, 'AES-256-CBC', $cipher_key, OPENSSL_RAW_DATA, $iv);
return $this->_genHmac($cipher_text, $cipher_key) . $cipher_text;
} | php | public function encrypt($original_string, $cipher_key)
{
$cipher_key = $this->_genKey($cipher_key);
$ivSize = openssl_cipher_iv_length('AES-256-CBC');
$iv = openssl_random_pseudo_bytes($ivSize);
$cipher_text = $iv . openssl_encrypt($original_string, 'AES-256-CBC', $cipher_key, OPENSSL_RAW_DATA, $iv);
return $this->_genHmac($cipher_text, $cipher_key) . $cipher_text;
} | Encrypts a string using a secret
@param string $original_string Original string
@param string $cipher_key Secret used to encrypt
@return string | https://github.com/aledefreitas/zlx_security/blob/3281db6bacfff51695835e1e6fc5bbddcf1a028a/src/Security/Security.php#L108-L118 |
aledefreitas/zlx_security | src/Security/Security.php | Security.decrypt | public function decrypt($cipher_string, $cipher_key)
{
$cipher_key = $this->_genKey($cipher_key);
$hmacSize = 64;
$hmacString = mb_substr($cipher_string, 0, $hmacSize, "8bit");
$cipher_text = mb_substr($cipher_string, $hmacSize, null, "8bit");
if(!$this->validHmac($hmacString, $this->_genHmac($cipher_text, $cipher_key)))
return false;
$ivSize = openssl_cipher_iv_length('AES-256-CBC');
$iv = mb_substr($cipher_text, 0, $ivSize, '8bit');
$cipher_text = mb_substr($cipher_text, $ivSize, null, '8bit');
return openssl_decrypt($cipher_text, 'AES-256-CBC', $cipher_key, OPENSSL_RAW_DATA, $iv);
} | php | public function decrypt($cipher_string, $cipher_key)
{
$cipher_key = $this->_genKey($cipher_key);
$hmacSize = 64;
$hmacString = mb_substr($cipher_string, 0, $hmacSize, "8bit");
$cipher_text = mb_substr($cipher_string, $hmacSize, null, "8bit");
if(!$this->validHmac($hmacString, $this->_genHmac($cipher_text, $cipher_key)))
return false;
$ivSize = openssl_cipher_iv_length('AES-256-CBC');
$iv = mb_substr($cipher_text, 0, $ivSize, '8bit');
$cipher_text = mb_substr($cipher_text, $ivSize, null, '8bit');
return openssl_decrypt($cipher_text, 'AES-256-CBC', $cipher_key, OPENSSL_RAW_DATA, $iv);
} | Decrypts a string using a secret
@param string $cipher_string Ciphered string
@param string $cipher_key Secret used to encrypt
@return string | https://github.com/aledefreitas/zlx_security/blob/3281db6bacfff51695835e1e6fc5bbddcf1a028a/src/Security/Security.php#L128-L144 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Http/Ajax.php | Ajax.listen | public function listen($action, $logged = 'no', $callable)
{
if (!is_string($action) || strlen($action) == 0)
{
throw new AjaxException("Invalid parameter for the action.");
}
// resolve callable
if (is_callable($callable))
{
$this->registerWithClosure($action, $logged, $callable);
}
else
{
if (strpos($callable, '@') !== false)
{
$parts = explode('@', $callable);
$callable = $parts[0];
$method = $parts[1];
}
else
{
$method = 'run';// default
}
try
{
$resolvedCallback = $this->app->make($callable);
$this->registerWithClassInstance($action, $logged, $resolvedCallback, $method);
} catch (\Exception $e)
{
throw new AjaxException($e->getMessage());
}
}
} | php | public function listen($action, $logged = 'no', $callable)
{
if (!is_string($action) || strlen($action) == 0)
{
throw new AjaxException("Invalid parameter for the action.");
}
// resolve callable
if (is_callable($callable))
{
$this->registerWithClosure($action, $logged, $callable);
}
else
{
if (strpos($callable, '@') !== false)
{
$parts = explode('@', $callable);
$callable = $parts[0];
$method = $parts[1];
}
else
{
$method = 'run';// default
}
try
{
$resolvedCallback = $this->app->make($callable);
$this->registerWithClassInstance($action, $logged, $resolvedCallback, $method);
} catch (\Exception $e)
{
throw new AjaxException($e->getMessage());
}
}
} | Handle the Ajax response. Run the appropriate
action hooks used by WordPress in order to perform
POST ajax request securely.
Developers have the option to run ajax for the
Front-end, Back-end either users are logged in or not
or both.
@param string $action Your ajax 'action' name
@param string $logged Accepted values are 'no', 'yes', 'both'
@param callable|string $callable The function to run when ajax action is called
@throws AjaxException | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Http/Ajax.php#L43-L82 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Http/Ajax.php | Ajax.validate | public function validate($nonce = null, $value = null, $message = null, $data = null)
{
$nonce = ($nonce) ? $nonce : $this->app['request']->get('nonce');
$value = ($value) ? $value : $this->app['config']->get('app.key');
if (!wp_verify_nonce($nonce, $value))
{
$default = ($msg = trans('ajax.invalid')) ? $msg : 'AJAX is invalid.';
$data = ($data) ? $data : $this->app['request']->except(['nonce', 'action']);
wp_send_json([
'error' => true,
'msg' => ($message) ? $message : $default,
'data' => $data
]);
}
} | php | public function validate($nonce = null, $value = null, $message = null, $data = null)
{
$nonce = ($nonce) ? $nonce : $this->app['request']->get('nonce');
$value = ($value) ? $value : $this->app['config']->get('app.key');
if (!wp_verify_nonce($nonce, $value))
{
$default = ($msg = trans('ajax.invalid')) ? $msg : 'AJAX is invalid.';
$data = ($data) ? $data : $this->app['request']->except(['nonce', 'action']);
wp_send_json([
'error' => true,
'msg' => ($message) ? $message : $default,
'data' => $data
]);
}
} | Check nonce against app.key
@param null|string $nonce By default will use 'nonce' index
@param null|string $value By default will get app.key
@param null|string $message By default try to get translation on ajax.invalid
@param null|mixed $data | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Http/Ajax.php#L93-L111 |
kmfk/slowdb | src/File.php | File.insert | public function insert($key, $value)
{
$this->file->flock(LOCK_SH);
$this->file->fseek(0, SEEK_END);
$position = $this->file->ftell();
if (is_array($value) || is_object($value)) {
$value = json_encode($value);
}
$this->file->flock(LOCK_EX);
$this->file->fwrite(
pack('N*', strlen($key)) .
pack('N*', strlen($value)) .
$key .
$value
);
$this->file->flock(LOCK_UN);
return $position;
} | php | public function insert($key, $value)
{
$this->file->flock(LOCK_SH);
$this->file->fseek(0, SEEK_END);
$position = $this->file->ftell();
if (is_array($value) || is_object($value)) {
$value = json_encode($value);
}
$this->file->flock(LOCK_EX);
$this->file->fwrite(
pack('N*', strlen($key)) .
pack('N*', strlen($value)) .
$key .
$value
);
$this->file->flock(LOCK_UN);
return $position;
} | Write the new record to the database file
We store metadata (lengths) in the first 8 bytes of each row
allowing us to use binary searches and indexing key/value positions
@param string $key The Key to be stored
@param mixed $value The Value to be stored
@return integer Returns the position of the data | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L75-L96 |
kmfk/slowdb | src/File.php | File.read | public function read($position)
{
$this->file->flock(LOCK_SH);
$metadata = $this->getMetadata($position);
$this->file->fseek($metadata->klen, SEEK_CUR);
$value = $this->file->fread($metadata->vlen);
$this->file->flock(LOCK_UN);
$mixed = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return $value;
}
return $mixed;
} | php | public function read($position)
{
$this->file->flock(LOCK_SH);
$metadata = $this->getMetadata($position);
$this->file->fseek($metadata->klen, SEEK_CUR);
$value = $this->file->fread($metadata->vlen);
$this->file->flock(LOCK_UN);
$mixed = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return $value;
}
return $mixed;
} | Retrieves the data from the database for a Key based on position
@param integer $position The offset in the file where the data is stored
@return array | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L105-L120 |
kmfk/slowdb | src/File.php | File.update | public function update($position, $key, $value)
{
$this->remove($position);
return $this->insert($key, $value);
} | php | public function update($position, $key, $value)
{
$this->remove($position);
return $this->insert($key, $value);
} | Updates an existing key by removing it from the existing file and
appending the new value to the end of the file.
@param string $key The Key to be stored
@param mixed $value The Value to be stored
@return integer | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L131-L136 |
kmfk/slowdb | src/File.php | File.remove | public function remove($position)
{
$temp = new \SplTempFileObject(-1);
$this->file->flock(LOCK_EX);
$filesize = $this->file->getSize();
$metadata = $this->getMetadata($position);
// Seek past the document we want to remove
$this->file->fseek($metadata->length, SEEK_CUR);
// Write everything after the target document to memory
$temp->fwrite($this->file->fread($filesize));
// Clear the file up to the target document
$this->file->ftruncate($position);
// Write Temp back to the end of the file
$temp->fseek(0);
$this->file->fseek(0, SEEK_END);
$this->file->fwrite($temp->fread($filesize));
$this->file->flock(LOCK_UN);
} | php | public function remove($position)
{
$temp = new \SplTempFileObject(-1);
$this->file->flock(LOCK_EX);
$filesize = $this->file->getSize();
$metadata = $this->getMetadata($position);
// Seek past the document we want to remove
$this->file->fseek($metadata->length, SEEK_CUR);
// Write everything after the target document to memory
$temp->fwrite($this->file->fread($filesize));
// Clear the file up to the target document
$this->file->ftruncate($position);
// Write Temp back to the end of the file
$temp->fseek(0);
$this->file->fseek(0, SEEK_END);
$this->file->fwrite($temp->fread($filesize));
$this->file->flock(LOCK_UN);
} | Removes a Key/Value pair based on its position in the file
@param integer $position The offset position in the file | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L143-L167 |
kmfk/slowdb | src/File.php | File.truncate | public function truncate()
{
$this->file->flock(LOCK_EX);
$result = $this->file->ftruncate(0);
$this->file->flock(LOCK_UN);
return $result;
} | php | public function truncate()
{
$this->file->flock(LOCK_EX);
$result = $this->file->ftruncate(0);
$this->file->flock(LOCK_UN);
return $result;
} | Truncates the collection, removing all the data from the file
@return bool | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L174-L181 |
kmfk/slowdb | src/File.php | File.buildIndex | public function buildIndex()
{
$this->file->flock(LOCK_SH);
$this->file->fseek(0);
$indexes = [];
while (!$this->file->eof()) {
$position = $this->file->ftell();
// Grab key and value lengths - if its the last (empty) line, break
if (!$metadata = $this->getMetadata()) {
break;
}
// Gets the key and adds the key and position to the index
$indexes[$this->file->fread($metadata->klen)] = $position;
//Skip over the value, to the next key/value pair
$this->file->fseek($metadata->vlen, SEEK_CUR);
}
$this->file->flock(LOCK_UN);
return $indexes;
} | php | public function buildIndex()
{
$this->file->flock(LOCK_SH);
$this->file->fseek(0);
$indexes = [];
while (!$this->file->eof()) {
$position = $this->file->ftell();
// Grab key and value lengths - if its the last (empty) line, break
if (!$metadata = $this->getMetadata()) {
break;
}
// Gets the key and adds the key and position to the index
$indexes[$this->file->fread($metadata->klen)] = $position;
//Skip over the value, to the next key/value pair
$this->file->fseek($metadata->vlen, SEEK_CUR);
}
$this->file->flock(LOCK_UN);
return $indexes;
} | Index the file by getting key/value positions within the file
@return array | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L189-L212 |
kmfk/slowdb | src/File.php | File.getMetadata | protected function getMetadata($position = null)
{
if (!is_null($position)) {
$this->file->fseek($position);
}
$metadata = $this->file->fread(8);
if ($metadata) {
list(, $klen, $vlen) = unpack('N*', $metadata);
return (object) ['klen' => $klen, 'vlen' => $vlen, 'length' => $klen + $vlen];
}
return false;
} | php | protected function getMetadata($position = null)
{
if (!is_null($position)) {
$this->file->fseek($position);
}
$metadata = $this->file->fread(8);
if ($metadata) {
list(, $klen, $vlen) = unpack('N*', $metadata);
return (object) ['klen' => $klen, 'vlen' => $vlen, 'length' => $klen + $vlen];
}
return false;
} | Retrieves the Metadata for a Key/Value pair
Optionally allows a specific position offset in the file
Return Array
- klen: The length of the Key
- vlen: The length of the Value
- length: The total combined length of the Key and the Value
@param integer $position An offset to seek to in a file
@return array|bool | https://github.com/kmfk/slowdb/blob/7461771b8ddc0c9887e2ee69a76ff5ffc763974c/src/File.php#L227-L241 |
phpextra/event-manager-silex-provider | src/PHPExtra/EventManager/Silex/EventManagerServiceProvider.php | EventManagerServiceProvider.register | public function register(Application $app)
{
$app['dispatcher_class'] = 'PHPExtra\\EventManager\\Silex\\CustomEventDispatcher';
$app['event_manager'] = $app->share(
function (Application $app) {
$em = new EventManager();
if ($app['debug'] == true) {
$em->setThrowExceptions(true);
}
if ($app['logger'] !== null) {
$em->setLogger($app['logger']);
}
return $em;
}
);
$app['event_manager.proxy_mapper'] = $app->share(
function (Application $app) {
return new ProxyMapper();
}
);
$app->extend(
'dispatcher',
function (CustomEventDispatcher $dispatcher, Application $app) {
$dispatcher
->setProxyMapper($app['event_manager.proxy_mapper'])
->setEventManager($app['event_manager']);
return $dispatcher;
}
);
} | php | public function register(Application $app)
{
$app['dispatcher_class'] = 'PHPExtra\\EventManager\\Silex\\CustomEventDispatcher';
$app['event_manager'] = $app->share(
function (Application $app) {
$em = new EventManager();
if ($app['debug'] == true) {
$em->setThrowExceptions(true);
}
if ($app['logger'] !== null) {
$em->setLogger($app['logger']);
}
return $em;
}
);
$app['event_manager.proxy_mapper'] = $app->share(
function (Application $app) {
return new ProxyMapper();
}
);
$app->extend(
'dispatcher',
function (CustomEventDispatcher $dispatcher, Application $app) {
$dispatcher
->setProxyMapper($app['event_manager.proxy_mapper'])
->setEventManager($app['event_manager']);
return $dispatcher;
}
);
} | {@inheritdoc} | https://github.com/phpextra/event-manager-silex-provider/blob/9952b237feffa5a469dd2976317736a570526249/src/PHPExtra/EventManager/Silex/EventManagerServiceProvider.php#L19-L55 |
symfonette/neon-integration | src/DependencyInjection/NeonFileLoader.php | NeonFileLoader.load | public function load($resource, $type = null)
{
$path = $this->locator->locate($resource);
$content = $this->loadFile($path);
$this->container->addResource(new FileResource($path));
if (null === $content) {
return;
}
$this->parseImports($content, $path);
if (isset($content['parameters'])) {
if (!is_array($content['parameters'])) {
throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your NEON syntax.', $resource));
}
foreach ($content['parameters'] as $key => $value) {
$this->container->setParameter($key, $this->resolveServices($value, $path));
}
}
$this->loadFromExtensions($content);
$this->parseDefinitions($content, $resource);
} | php | public function load($resource, $type = null)
{
$path = $this->locator->locate($resource);
$content = $this->loadFile($path);
$this->container->addResource(new FileResource($path));
if (null === $content) {
return;
}
$this->parseImports($content, $path);
if (isset($content['parameters'])) {
if (!is_array($content['parameters'])) {
throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your NEON syntax.', $resource));
}
foreach ($content['parameters'] as $key => $value) {
$this->container->setParameter($key, $this->resolveServices($value, $path));
}
}
$this->loadFromExtensions($content);
$this->parseDefinitions($content, $resource);
} | {@inheritdoc} | https://github.com/symfonette/neon-integration/blob/d8ea225fd21453fd3adf7d1544b84e7cde66fc16/src/DependencyInjection/NeonFileLoader.php#L69-L96 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Socket.php | Socket.create | public static function create($context, $type, LoggerInterface $logger = null, $persistentId = null, $onNewSocket = null)
{
if (!is_callable($onNewSocket)) {
$onNewSocket = null;
}
$newSocket = false;
$callback = function() use ($onNewSocket, &$newSocket) {
$newSocket = true;
if ($onNewSocket !== null) {
$onNewSocket();
}
};
$instance = new self($context, $type, $persistentId, $callback);
$instance->setId(self::$nextId);
$instance->setNewSocket($newSocket);
$instance->setSockOpt(ZMQ::SOCKOPT_LINGER, 0);
self::$nextId++;
if (null !== $logger) {
$instance->setLogger($logger);
}
return $instance;
} | php | public static function create($context, $type, LoggerInterface $logger = null, $persistentId = null, $onNewSocket = null)
{
if (!is_callable($onNewSocket)) {
$onNewSocket = null;
}
$newSocket = false;
$callback = function() use ($onNewSocket, &$newSocket) {
$newSocket = true;
if ($onNewSocket !== null) {
$onNewSocket();
}
};
$instance = new self($context, $type, $persistentId, $callback);
$instance->setId(self::$nextId);
$instance->setNewSocket($newSocket);
$instance->setSockOpt(ZMQ::SOCKOPT_LINGER, 0);
self::$nextId++;
if (null !== $logger) {
$instance->setLogger($logger);
}
return $instance;
} | Create a new Socket.
@param \ZMQContext $context The Context to create this Socket with
@param integer $type One of the ZMQ::SOCKET_{PUB,SUB,PUSH,PULL,REQ,REP,ROUTER,DEALER} contants.
@param LoggerInterface $logger A Logger
@param string $persistentId When using a persistent socket: the persistence ID
@param callable|null $onNewSocket Callback to use when a new socket is created
@return \AlphaRPC\Common\Socket\Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Socket.php#L54-L79 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Socket.php | Socket.hasEvents | public function hasEvents($timeout = 0)
{
$poll = new ZMQPoll();
$poll->add($this, ZMQ::POLL_IN);
$read = $write = array();
$events = $poll->poll($read, $write, $timeout);
if ($events > 0) {
return true;
}
return false;
} | php | public function hasEvents($timeout = 0)
{
$poll = new ZMQPoll();
$poll->add($this, ZMQ::POLL_IN);
$read = $write = array();
$events = $poll->poll($read, $write, $timeout);
if ($events > 0) {
return true;
}
return false;
} | Poll for new Events on this Socket.
@param integer $timeout Timeout in milliseconds. Defaults to 0 (return immediately).
@return boolean | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Socket.php#L88-L99 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Socket.php | Socket.mrecv | public function mrecv($mode = 0)
{
if ($this->verbose) {
$this->getLogger()->debug('PRE RECV: '.$this->id);
}
$data = array();
while (true) {
$data[] = $this->recv($mode);
if (!$this->getSockOpt(ZMQ::SOCKOPT_RCVMORE)) {
break;
}
}
$message = new Message($data);
if ($this->verbose) {
$this->getLogger()->debug('RECV: '.$this->id);
$this->getLogger()->debug($message);
}
if (ZMQ::SOCKET_ROUTER === $this->getSocketType()) {
$message->stripRoutingInformation();
}
return $message;
} | php | public function mrecv($mode = 0)
{
if ($this->verbose) {
$this->getLogger()->debug('PRE RECV: '.$this->id);
}
$data = array();
while (true) {
$data[] = $this->recv($mode);
if (!$this->getSockOpt(ZMQ::SOCKOPT_RCVMORE)) {
break;
}
}
$message = new Message($data);
if ($this->verbose) {
$this->getLogger()->debug('RECV: '.$this->id);
$this->getLogger()->debug($message);
}
if (ZMQ::SOCKET_ROUTER === $this->getSocketType()) {
$message->stripRoutingInformation();
}
return $message;
} | Receive a Message.
Use this instead of {@see ::recv}.
@param int $mode
@return \AlphaRPC\Common\Socket\Message | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Socket.php#L166-L190 |
alphacomm/alpharpc | src/AlphaRPC/Common/Socket/Socket.php | Socket.msend | public function msend(Message $msg)
{
if (ZMQ::SOCKET_ROUTER === $this->getSocketType()) {
$msg->prepend($msg->getRoutingInformation());
}
if ($this->verbose) {
$this->getLogger()->debug('SEND: '.$this->id);
$this->getLogger()->debug($msg);
}
$parts = $msg->toArray();
$iMax = count($parts)-1;
if ($iMax < 0) {
throw new RuntimeException('No parts to send.');
}
for ($i = 0; $i < $iMax; $i++) {
$this->send($parts[$i], ZMQ::MODE_SNDMORE);
}
$this->send($parts[$iMax]);
if ($this->verbose) {
$this->getLogger()->debug('Message sent.');
}
return $this;
} | php | public function msend(Message $msg)
{
if (ZMQ::SOCKET_ROUTER === $this->getSocketType()) {
$msg->prepend($msg->getRoutingInformation());
}
if ($this->verbose) {
$this->getLogger()->debug('SEND: '.$this->id);
$this->getLogger()->debug($msg);
}
$parts = $msg->toArray();
$iMax = count($parts)-1;
if ($iMax < 0) {
throw new RuntimeException('No parts to send.');
}
for ($i = 0; $i < $iMax; $i++) {
$this->send($parts[$i], ZMQ::MODE_SNDMORE);
}
$this->send($parts[$iMax]);
if ($this->verbose) {
$this->getLogger()->debug('Message sent.');
}
return $this;
} | Send a Messsage.
@param Message $msg
@return Socket | https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Common/Socket/Socket.php#L199-L223 |
wigedev/farm | src/FormBuilder/FormElement/Textarea.php | Textarea.outputElement | public function outputElement() : string
{
$atts = [];
foreach ($this->attributes as $name => $value) {
$atts[] = $name . '="' . $value . '"';
}
$return = '<textarea ' . implode(' ', $atts) . '>' . "\n";
$return .= $this->getValue();
$return .= '</textarea>';
return $return;
} | php | public function outputElement() : string
{
$atts = [];
foreach ($this->attributes as $name => $value) {
$atts[] = $name . '="' . $value . '"';
}
$return = '<textarea ' . implode(' ', $atts) . '>' . "\n";
$return .= $this->getValue();
$return .= '</textarea>';
return $return;
} | Returns the form element as an HTML tag | https://github.com/wigedev/farm/blob/7a1729ec78628b7e5435e4a42e42d547a07af851/src/FormBuilder/FormElement/Textarea.php#L29-L39 |
K-Phoen/gaufrette-extras-bundle | DependencyInjection/KPhoenGaufretteExtrasExtension.php | KPhoenGaufretteExtrasExtension.load | public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
// first assemble the adapter factories
$factoryConfig = new FactoryConfiguration();
$config = $processor->processConfiguration($factoryConfig, $configs);
$factories = $this->createResolverFactories($config, $container);
// then normalize the configs
$configuration = new Configuration($factories);
$config = $this->processConfiguration($configuration, $configs);
// create the resolvers
$resolvers = array();
foreach ($config['resolvers'] as $fs_name => $resolver) {
$resolvers[$fs_name] = $this->createResolver($fs_name, $resolver, $container, $factories);
}
} | php | public function load(array $configs, ContainerBuilder $container)
{
$processor = new Processor();
$loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.xml');
// first assemble the adapter factories
$factoryConfig = new FactoryConfiguration();
$config = $processor->processConfiguration($factoryConfig, $configs);
$factories = $this->createResolverFactories($config, $container);
// then normalize the configs
$configuration = new Configuration($factories);
$config = $this->processConfiguration($configuration, $configs);
// create the resolvers
$resolvers = array();
foreach ($config['resolvers'] as $fs_name => $resolver) {
$resolvers[$fs_name] = $this->createResolver($fs_name, $resolver, $container, $factories);
}
} | Loads the extension
@param array $configs
@param ContainerBuilder $container | https://github.com/K-Phoen/gaufrette-extras-bundle/blob/3f05779179117d5649184164544e1f22de28d706/DependencyInjection/KPhoenGaufretteExtrasExtension.php#L22-L43 |
K-Phoen/gaufrette-extras-bundle | DependencyInjection/KPhoenGaufretteExtrasExtension.php | KPhoenGaufretteExtrasExtension.createResolverFactories | private function createResolverFactories($config, ContainerBuilder $container)
{
if (null !== $this->factories) {
return $this->factories;
}
// load bundled adapter factories
$tempContainer = new ContainerBuilder();
$parameterBag = $container->getParameterBag();
$loader = new XmlFileLoader($tempContainer, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('resolver_factories.xml');
// load user-created adapter factories
foreach ($config['factories'] as $factory) {
$loader->load($parameterBag->resolveValue($factory));
}
$services = $tempContainer->findTaggedServiceIds('gaufrette.resolver.factory');
$factories = array();
foreach (array_keys($services) as $id) {
$factory = $tempContainer->get($id);
$factories[str_replace('-', '_', $factory->getKey())] = $factory;
}
return $this->factories = $factories;
} | php | private function createResolverFactories($config, ContainerBuilder $container)
{
if (null !== $this->factories) {
return $this->factories;
}
// load bundled adapter factories
$tempContainer = new ContainerBuilder();
$parameterBag = $container->getParameterBag();
$loader = new XmlFileLoader($tempContainer, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('resolver_factories.xml');
// load user-created adapter factories
foreach ($config['factories'] as $factory) {
$loader->load($parameterBag->resolveValue($factory));
}
$services = $tempContainer->findTaggedServiceIds('gaufrette.resolver.factory');
$factories = array();
foreach (array_keys($services) as $id) {
$factory = $tempContainer->get($id);
$factories[str_replace('-', '_', $factory->getKey())] = $factory;
}
return $this->factories = $factories;
} | Creates the resolver factories
@param array $config
@param ContainerBuilder $container | https://github.com/K-Phoen/gaufrette-extras-bundle/blob/3f05779179117d5649184164544e1f22de28d706/DependencyInjection/KPhoenGaufretteExtrasExtension.php#L66-L92 |
hal-platform/hal-core | src/Repository/AuditEventRepository.php | AuditEventRepository.getPagedResults | public function getPagedResults($limit = 50, $page = 0)
{
$dql = sprintf(self::DQL_GET_PAGED, AuditEvent::class);
return $this->getPaginator($dql, $limit, $page);
} | php | public function getPagedResults($limit = 50, $page = 0)
{
$dql = sprintf(self::DQL_GET_PAGED, AuditEvent::class);
return $this->getPaginator($dql, $limit, $page);
} | Get all audit events, paged.
@param int $limit
@param int $page
@return Paginator | https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Repository/AuditEventRepository.php#L33-L37 |
zikula/FileSystem | Ftp.php | Ftp.connect | public function connect()
{
$this->errorHandler->start();
//create the connection
if ($this->configuration->getSSL()) {
$this->resource = $this->driver->sslConnect($this->configuration->getHost(), $this->configuration->getPort(), $this->configuration->getTimeout());
} else {
$this->resource = $this->driver->connect($this->configuration->getHost(), $this->configuration->getPort(), $this->configuration->getTimeout());
}
if ($this->resource !== false) {
//log in
if ($this->driver->login($this->resource, $this->configuration->getUser(), $this->configuration->getPass())) {
//change directory
if ($this->driver->pasv($this->resource, $this->configuration->getPasv())) {
if ($this->driver->chdir($this->resource, $this->configuration->getDir())) {
$this->dir = ftp_pwd($this->resource);
$this->errorHandler->stop();
return true;
}
}
}
}
$this->errorHandler->stop();
return false;
} | php | public function connect()
{
$this->errorHandler->start();
//create the connection
if ($this->configuration->getSSL()) {
$this->resource = $this->driver->sslConnect($this->configuration->getHost(), $this->configuration->getPort(), $this->configuration->getTimeout());
} else {
$this->resource = $this->driver->connect($this->configuration->getHost(), $this->configuration->getPort(), $this->configuration->getTimeout());
}
if ($this->resource !== false) {
//log in
if ($this->driver->login($this->resource, $this->configuration->getUser(), $this->configuration->getPass())) {
//change directory
if ($this->driver->pasv($this->resource, $this->configuration->getPasv())) {
if ($this->driver->chdir($this->resource, $this->configuration->getDir())) {
$this->dir = ftp_pwd($this->resource);
$this->errorHandler->stop();
return true;
}
}
}
}
$this->errorHandler->stop();
return false;
} | Standard function for creating a FTP connection and logging in.
This must be called before any of the other functions in the
Interface. However the construct itself calles this
function upon completion, which alleviates the need to ever call
this function manualy.
@return boolean | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L47-L75 |
zikula/FileSystem | Ftp.php | Ftp.fput | public function fput($stream, $remote)
{
$this->isAlive(true);
$this->errorHandler->start();
if ($this->driver->fput($this->resource, $remote, $stream, FTP_BINARY)) {
$this->errorHandler->stop();
return true;
}
$this->errorHandler->stop();
return false;
} | php | public function fput($stream, $remote)
{
$this->isAlive(true);
$this->errorHandler->start();
if ($this->driver->fput($this->resource, $remote, $stream, FTP_BINARY)) {
$this->errorHandler->stop();
return true;
}
$this->errorHandler->stop();
return false;
} | Similar to put but does not get the file localy.
This should be used instead of put in most cases.
@param stream|resource $stream The resource to put remotely, probably the resource returned from a fget.
@param string $remote The pathname to the desired remote pathname.
@return integer|boolean number of bytes written on success, false on failure. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L113-L125 |
zikula/FileSystem | Ftp.php | Ftp.putContents | public function putContents($contents, $remote)
{
$stream = fopen('data://text/plain,' . $contents, 'r');
return $this->fput($stream, $remote);
} | php | public function putContents($contents, $remote)
{
$stream = fopen('data://text/plain,' . $contents, 'r');
return $this->fput($stream, $remote);
} | Write the contents of a string to the remote.
@param string $contents The contents to put remotely.
@param string $remote The pathname to the desired remote pathname.
@return boolean|integer Number of bytes written on success, false on failure. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L135-L140 |
zikula/FileSystem | Ftp.php | Ftp.get | public function get($local, $remote)
{
$this->isAlive(true);
$this->errorHandler->start();
if ($this->driver->get($this->resource, $local, $remote, FTP_BINARY)) {
$this->errorHandler->stop();
return true;
}
$this->errorHandler->stop();
return false;
} | php | public function get($local, $remote)
{
$this->isAlive(true);
$this->errorHandler->start();
if ($this->driver->get($this->resource, $local, $remote, FTP_BINARY)) {
$this->errorHandler->stop();
return true;
}
$this->errorHandler->stop();
return false;
} | Get a remote file and save it localy, opposite of put function.
This method should be used with caution because it undermines the purpose of the
FileSystem classes by the fact that it saves the file localy without using the
local driver.
@param string $local The pathname to the desired local file.
@param string $remote The pathname to the remote file to get.
@return bool True on success, false on failure. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L166-L178 |
zikula/FileSystem | Ftp.php | Ftp.fget | public function fget($remote)
{
$this->isAlive(true);
$this->errorHandler->start();
$handle = fopen('php://temp', 'r+');
if ($this->driver->fget($this->resource, $handle, $remote, FTP_BINARY)) {
rewind($handle);
$this->errorHandler->stop();
return $handle;
}
$this->errorHandler->stop();
return false;
} | php | public function fget($remote)
{
$this->isAlive(true);
$this->errorHandler->start();
$handle = fopen('php://temp', 'r+');
if ($this->driver->fget($this->resource, $handle, $remote, FTP_BINARY)) {
rewind($handle);
$this->errorHandler->stop();
return $handle;
}
$this->errorHandler->stop();
return false;
} | Similar to get but does not save file localy.
This should usually be used instead of get in most cases.
@param string $remote The path to the remote file.
@return resource|boolean The resource on success false on fail. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L189-L203 |
zikula/FileSystem | Ftp.php | Ftp.chmod | public function chmod($perm, $file)
{
$this->isAlive(true);
$this->errorHandler->start();
$perm = (int) octdec(str_pad($perm, 4, '0', STR_PAD_LEFT));
if (($perm = $this->driver->chmod($this->resource, $perm, $file)) !== false) {
$perm = (int) decoct(str_pad($perm, 4, '0', STR_PAD_LEFT));
$this->errorHandler->stop();
return $perm;
}
$this->errorHandler->stop();
return false;
} | php | public function chmod($perm, $file)
{
$this->isAlive(true);
$this->errorHandler->start();
$perm = (int) octdec(str_pad($perm, 4, '0', STR_PAD_LEFT));
if (($perm = $this->driver->chmod($this->resource, $perm, $file)) !== false) {
$perm = (int) decoct(str_pad($perm, 4, '0', STR_PAD_LEFT));
$this->errorHandler->stop();
return $perm;
}
$this->errorHandler->stop();
return false;
} | Change the permissions of a file.
@param integer $perm The permission to assign to the file, unix style (example: 777 for full permission).
@param string $file The pathname to the remote file to chmod.
@return integer|boolean The new permission or false if failed. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L213-L227 |
zikula/FileSystem | Ftp.php | Ftp.ls | public function ls($dir = '')
{
$this->isAlive(true);
$this->errorHandler->start();
$dir = ($dir == '' ? ftp_pwd($this->resource) : $dir);
if (($ls = $this->driver->nlist($this->resource, $dir)) !== false) {
$this->errorHandler->stop();
return $ls;
}
$this->errorHandler->stop();
return false;
} | php | public function ls($dir = '')
{
$this->isAlive(true);
$this->errorHandler->start();
$dir = ($dir == '' ? ftp_pwd($this->resource) : $dir);
if (($ls = $this->driver->nlist($this->resource, $dir)) !== false) {
$this->errorHandler->stop();
return $ls;
}
$this->errorHandler->stop();
return false;
} | Get the entire contents of a directory.
@param string $dir The directory to get the contents of, blank for current directory, start with / for absolute path.
@return array|boolean An array of the contents of $dir or false if fail. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L236-L249 |
zikula/FileSystem | Ftp.php | Ftp.cp | public function cp($sourcepath, $destpath)
{
$this->isAlive(true);
$this->errorHandler->start();
if (($handle = $this->fget($sourcepath)) !== false) {
if ($this->fput($handle, $destpath)) {
$this->errorHandler->stop();
return true;
};
}
$this->errorHandler->stop();
return false;
} | php | public function cp($sourcepath, $destpath)
{
$this->isAlive(true);
$this->errorHandler->start();
if (($handle = $this->fget($sourcepath)) !== false) {
if ($this->fput($handle, $destpath)) {
$this->errorHandler->stop();
return true;
};
}
$this->errorHandler->stop();
return false;
} | Copy a file on the remote server to a new location on the remote.
Same as mv method but leaves the original file.
@param string $sourcepath The path to the original source file.
@param string $destpath The path to where you want to copy the source file.
@return boolean True on success, false on failure. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L306-L320 |
zikula/FileSystem | Ftp.php | Ftp.isAlive | public function isAlive($reconnect = false)
{
if (!$this->driver->systype($this->resource)) {
if ($reconnect) {
return $this->connect();
}
return false;
}
return true;
} | php | public function isAlive($reconnect = false)
{
if (!$this->driver->systype($this->resource)) {
if ($reconnect) {
return $this->connect();
}
return false;
}
return true;
} | Checks to see if connection is alive(experimental).
Reconnects if not still alive, this function needs to
be fixed up.
TODO: make this better.
@param boolean $reconnect Reconnect if connection is dead?.
@return boolean True if connected, false if not. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L354-L365 |
zikula/FileSystem | Ftp.php | Ftp.isWritable | public function isWritable($remote_file)
{
$this->errorHandler->start();
//remove slashes at beginning and end of dir's, beginning of file
$dir = substr($this->configuration->getDir(), 0, 1) == '/' ? substr($this->configuration->getDir(), 1) : $this->configuration->getDir();
$dir = substr($dir, -1, 1) == '/' ? substr($dir, 0, -1) : $dir;
$remote_file = substr($remote_file, 0, 1) == '/' ? substr($remote_file, 1) : $remote_file;
//get path info setup properly.
$dirname = pathinfo('/' . $dir . '/' . $remote_file);
$dirname = $dirname['dirname'];
//get a directory listing and check that the file in question is listed (workaround for file_exists)
$dirlist = $this->driver->nlist($this->resource, $dirname);
if (is_array($dirlist) && in_array("/$dir/$remote_file", $dirlist)) {
//file exists, check if we can open the file for appending
if (!$handle = $this->driver->fopen($dir . '/' . $remote_file, 'a', $this->configuration)) {
$this->errorHandler->stop();
return false;
}
//attempt to do an empty append
if (!fwrite($handle, '') === FALSE) {
$this->errorHandler->stop();
return false;
}
$this->errorHandler->stop();
return true;
}
//file not found, return false
$this->errorHandler->stop();
return false;
} | php | public function isWritable($remote_file)
{
$this->errorHandler->start();
//remove slashes at beginning and end of dir's, beginning of file
$dir = substr($this->configuration->getDir(), 0, 1) == '/' ? substr($this->configuration->getDir(), 1) : $this->configuration->getDir();
$dir = substr($dir, -1, 1) == '/' ? substr($dir, 0, -1) : $dir;
$remote_file = substr($remote_file, 0, 1) == '/' ? substr($remote_file, 1) : $remote_file;
//get path info setup properly.
$dirname = pathinfo('/' . $dir . '/' . $remote_file);
$dirname = $dirname['dirname'];
//get a directory listing and check that the file in question is listed (workaround for file_exists)
$dirlist = $this->driver->nlist($this->resource, $dirname);
if (is_array($dirlist) && in_array("/$dir/$remote_file", $dirlist)) {
//file exists, check if we can open the file for appending
if (!$handle = $this->driver->fopen($dir . '/' . $remote_file, 'a', $this->configuration)) {
$this->errorHandler->stop();
return false;
}
//attempt to do an empty append
if (!fwrite($handle, '') === FALSE) {
$this->errorHandler->stop();
return false;
}
$this->errorHandler->stop();
return true;
}
//file not found, return false
$this->errorHandler->stop();
return false;
} | Check if a file is writable.
@param string $sourcepath The path to the file to check if is writable.
@return boolean True if is writable False if not. | https://github.com/zikula/FileSystem/blob/8e12d6839aa50a7590f5ad22cc2d33c8f88ff726/Ftp.php#L374-L412 |
villermen/runescape-lookup-commons | src/Activity.php | Activity.initializeActivities | public static function initializeActivities()
{
if (self::$activities) {
return;
}
self::$activities = [
self::ACTIVITY_BOUNTY_HUNTER => new Activity(self::ACTIVITY_BOUNTY_HUNTER, "Bounty Hunter: Bounty Kills"),
self::ACTIVITY_BOUNTY_HUNTER_ROGUE => new Activity(self::ACTIVITY_BOUNTY_HUNTER_ROGUE, "Bounty Hunter: Rogue Kills"),
self::ACTIVITY_DOMINION_TOWER => new Activity(self::ACTIVITY_DOMINION_TOWER, "Dominion Tower"),
self::ACTIVITY_CRUCIBLE => new Activity(self::ACTIVITY_CRUCIBLE, "The Crucible"),
self::ACTIVITY_CASTLE_WARS => new Activity(self::ACTIVITY_CASTLE_WARS, "Castle Wars Games"),
self::ACTIVITY_BARBARIAN_ASSAULT_ATTACKER => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_ATTACKER, "Barbarian Assault Attackers"),
self::ACTIVITY_BARBARIAN_ASSAULT_DEFENDER => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_DEFENDER, "Barbarian Assault Defenders"),
self::ACTIVITY_BARBARIAN_ASSAULT_COLLECTOR => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_COLLECTOR, "Barbarian Assault Collectors"),
self::ACTIVITY_BARBARIAN_ASSAULT_HEALER => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_HEALER, "Barbarian Assault Healers"),
self::ACTIVITY_DUEL_TOURNAMENT => new Activity(self::ACTIVITY_DUEL_TOURNAMENT, "Duel Tournament"),
self::ACTIVITY_MOBILISING_ARMIES => new Activity(self::ACTIVITY_MOBILISING_ARMIES, "Mobilising Armies"),
self::ACTIVITY_CONQUEST => new Activity(self::ACTIVITY_CONQUEST, "Conquest"),
self::ACTIVITY_FIST_OF_GUTHIX => new Activity(self::ACTIVITY_FIST_OF_GUTHIX, "Fist of Guthix"),
self::ACTIVITY_GIELINOR_GAMES_RESOURCE_RACE => new Activity(self::ACTIVITY_GIELINOR_GAMES_RESOURCE_RACE, "Gielinor Games: Resource Race"),
self::ACTIVITY_GIELINOR_GAMES_ATHLETICS => new Activity(self::ACTIVITY_GIELINOR_GAMES_ATHLETICS, "Gielinor Games: Athletics"),
self::ACTIVITY_WORLD_EVENT_2_ARMADYL_CONTRIBUTION => new Activity(self::ACTIVITY_WORLD_EVENT_2_ARMADYL_CONTRIBUTION, "World Event 2: Armadyl Lifetime Contribution"),
self::ACTIVITY_WORLD_EVENT_2_BANDOS_CONTRIBUTION => new Activity(self::ACTIVITY_WORLD_EVENT_2_BANDOS_CONTRIBUTION, "World Event 2: Bandos Lifetime Contribution"),
self::ACTIVITY_WORLD_EVENT_2_ARMADYL_KILLS => new Activity(self::ACTIVITY_WORLD_EVENT_2_ARMADYL_KILLS, "World Event 2: Armadyl PvP Kills"),
self::ACTIVITY_WORLD_EVENT_2_BANDOS_KILLS => new Activity(self::ACTIVITY_WORLD_EVENT_2_BANDOS_KILLS, "World Event 2: Bandos PvP Kills"),
self::ACTIVITY_HEIST_GUARD => new Activity(self::ACTIVITY_HEIST_GUARD, "Heist Guard Level"),
self::ACTIVITY_HEIST_ROBBER => new Activity(self::ACTIVITY_HEIST_ROBBER, "Heist Robber Level"),
self::ACTIVITY_CABBAGE_FACEPUNCH_BONANZA => new Activity(self::ACTIVITY_CABBAGE_FACEPUNCH_BONANZA, "Cabbage Facepunch Bonanza: 5 Game Average"),
self::ACTIVITY_APRIL_FOOLS_2015_COW_TIPPING => new Activity(self::ACTIVITY_APRIL_FOOLS_2015_COW_TIPPING, "April Fools 2015: Cow Tipping"),
self::ACTIVITY_APRIL_FOOLS_2015_RAT_KILLS => new Activity(self::ACTIVITY_APRIL_FOOLS_2015_RAT_KILLS, "April Fools 2015: Rat Kills"),
self::ACTIVITY_OLD_SCHOOL_EASY_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_EASY_CLUE_SCROLLS, "Clue Scrolls (easy)"),
self::ACTIVITY_OLD_SCHOOL_MEDIUM_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_MEDIUM_CLUE_SCROLLS, "Clue Scrolls (hard)"),
self::ACTIVITY_OLD_SCHOOL_ALL_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_ALL_CLUE_SCROLLS, "Clue Scrolls (all)"),
self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER_ROGUE => new Activity(self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER_ROGUE, "Bounty Hunter: Rogue Kills"),
self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER => new Activity(self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER, "Bounty Hunter: Bounty Kills"),
self::ACTIVITY_OLD_SCHOOL_HARD_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_ALL_CLUE_SCROLLS, "Clue Scrolls (hard)"),
self::ACTIVITY_OLD_SCHOOL_LAST_MAN_STANDING => new Activity(self::ACTIVITY_OLD_SCHOOL_LAST_MAN_STANDING, "Last Man Standing"),
self::ACTIVITY_OLD_SCHOOL_ELITE_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_ELITE_CLUE_SCROLLS, "Clue Scrolls (elite)"),
self::ACTIVITY_OLD_SCHOOL_MASTER_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_MASTER_CLUE_SCROLLS, "Clue Scrolls (master)")
];
} | php | public static function initializeActivities()
{
if (self::$activities) {
return;
}
self::$activities = [
self::ACTIVITY_BOUNTY_HUNTER => new Activity(self::ACTIVITY_BOUNTY_HUNTER, "Bounty Hunter: Bounty Kills"),
self::ACTIVITY_BOUNTY_HUNTER_ROGUE => new Activity(self::ACTIVITY_BOUNTY_HUNTER_ROGUE, "Bounty Hunter: Rogue Kills"),
self::ACTIVITY_DOMINION_TOWER => new Activity(self::ACTIVITY_DOMINION_TOWER, "Dominion Tower"),
self::ACTIVITY_CRUCIBLE => new Activity(self::ACTIVITY_CRUCIBLE, "The Crucible"),
self::ACTIVITY_CASTLE_WARS => new Activity(self::ACTIVITY_CASTLE_WARS, "Castle Wars Games"),
self::ACTIVITY_BARBARIAN_ASSAULT_ATTACKER => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_ATTACKER, "Barbarian Assault Attackers"),
self::ACTIVITY_BARBARIAN_ASSAULT_DEFENDER => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_DEFENDER, "Barbarian Assault Defenders"),
self::ACTIVITY_BARBARIAN_ASSAULT_COLLECTOR => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_COLLECTOR, "Barbarian Assault Collectors"),
self::ACTIVITY_BARBARIAN_ASSAULT_HEALER => new Activity(self::ACTIVITY_BARBARIAN_ASSAULT_HEALER, "Barbarian Assault Healers"),
self::ACTIVITY_DUEL_TOURNAMENT => new Activity(self::ACTIVITY_DUEL_TOURNAMENT, "Duel Tournament"),
self::ACTIVITY_MOBILISING_ARMIES => new Activity(self::ACTIVITY_MOBILISING_ARMIES, "Mobilising Armies"),
self::ACTIVITY_CONQUEST => new Activity(self::ACTIVITY_CONQUEST, "Conquest"),
self::ACTIVITY_FIST_OF_GUTHIX => new Activity(self::ACTIVITY_FIST_OF_GUTHIX, "Fist of Guthix"),
self::ACTIVITY_GIELINOR_GAMES_RESOURCE_RACE => new Activity(self::ACTIVITY_GIELINOR_GAMES_RESOURCE_RACE, "Gielinor Games: Resource Race"),
self::ACTIVITY_GIELINOR_GAMES_ATHLETICS => new Activity(self::ACTIVITY_GIELINOR_GAMES_ATHLETICS, "Gielinor Games: Athletics"),
self::ACTIVITY_WORLD_EVENT_2_ARMADYL_CONTRIBUTION => new Activity(self::ACTIVITY_WORLD_EVENT_2_ARMADYL_CONTRIBUTION, "World Event 2: Armadyl Lifetime Contribution"),
self::ACTIVITY_WORLD_EVENT_2_BANDOS_CONTRIBUTION => new Activity(self::ACTIVITY_WORLD_EVENT_2_BANDOS_CONTRIBUTION, "World Event 2: Bandos Lifetime Contribution"),
self::ACTIVITY_WORLD_EVENT_2_ARMADYL_KILLS => new Activity(self::ACTIVITY_WORLD_EVENT_2_ARMADYL_KILLS, "World Event 2: Armadyl PvP Kills"),
self::ACTIVITY_WORLD_EVENT_2_BANDOS_KILLS => new Activity(self::ACTIVITY_WORLD_EVENT_2_BANDOS_KILLS, "World Event 2: Bandos PvP Kills"),
self::ACTIVITY_HEIST_GUARD => new Activity(self::ACTIVITY_HEIST_GUARD, "Heist Guard Level"),
self::ACTIVITY_HEIST_ROBBER => new Activity(self::ACTIVITY_HEIST_ROBBER, "Heist Robber Level"),
self::ACTIVITY_CABBAGE_FACEPUNCH_BONANZA => new Activity(self::ACTIVITY_CABBAGE_FACEPUNCH_BONANZA, "Cabbage Facepunch Bonanza: 5 Game Average"),
self::ACTIVITY_APRIL_FOOLS_2015_COW_TIPPING => new Activity(self::ACTIVITY_APRIL_FOOLS_2015_COW_TIPPING, "April Fools 2015: Cow Tipping"),
self::ACTIVITY_APRIL_FOOLS_2015_RAT_KILLS => new Activity(self::ACTIVITY_APRIL_FOOLS_2015_RAT_KILLS, "April Fools 2015: Rat Kills"),
self::ACTIVITY_OLD_SCHOOL_EASY_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_EASY_CLUE_SCROLLS, "Clue Scrolls (easy)"),
self::ACTIVITY_OLD_SCHOOL_MEDIUM_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_MEDIUM_CLUE_SCROLLS, "Clue Scrolls (hard)"),
self::ACTIVITY_OLD_SCHOOL_ALL_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_ALL_CLUE_SCROLLS, "Clue Scrolls (all)"),
self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER_ROGUE => new Activity(self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER_ROGUE, "Bounty Hunter: Rogue Kills"),
self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER => new Activity(self::ACTIVITY_OLD_SCHOOL_BOUNTY_HUNTER, "Bounty Hunter: Bounty Kills"),
self::ACTIVITY_OLD_SCHOOL_HARD_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_ALL_CLUE_SCROLLS, "Clue Scrolls (hard)"),
self::ACTIVITY_OLD_SCHOOL_LAST_MAN_STANDING => new Activity(self::ACTIVITY_OLD_SCHOOL_LAST_MAN_STANDING, "Last Man Standing"),
self::ACTIVITY_OLD_SCHOOL_ELITE_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_ELITE_CLUE_SCROLLS, "Clue Scrolls (elite)"),
self::ACTIVITY_OLD_SCHOOL_MASTER_CLUE_SCROLLS => new Activity(self::ACTIVITY_OLD_SCHOOL_MASTER_CLUE_SCROLLS, "Clue Scrolls (master)")
];
} | Initializes the activities array.
Default values don't allow expressions (new objects). | https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/Activity.php#L51-L92 |
villermen/runescape-lookup-commons | src/Activity.php | Activity.getActivity | public static function getActivity(int $id): Activity
{
self::initializeActivities();
if (!isset(self::$activities[$id])) {
throw new RuneScapeException(sprintf("Activity with id %d does not exist.", $id));
}
return self::$activities[$id];
} | php | public static function getActivity(int $id): Activity
{
self::initializeActivities();
if (!isset(self::$activities[$id])) {
throw new RuneScapeException(sprintf("Activity with id %d does not exist.", $id));
}
return self::$activities[$id];
} | Retrieve an activity by ID.
You can use the ACTIVITY_ constants in this class for IDs.
@param int $id
@return Activity
@throws RuneScapeException When the requested activity does not exist. | https://github.com/villermen/runescape-lookup-commons/blob/3e24dadbdc5e20b755280e5110f4ca0a1758b04c/src/Activity.php#L112-L121 |
matryoshka-model/matryoshka | library/Criteria/CallbackCriteria.php | CallbackCriteria.apply | public function apply(ModelStubInterface $model)
{
$callback = $this->callback;
if ($callback instanceof \Closure) {
$callback = $callback->bindTo($this);
}
return call_user_func($callback, $model);
} | php | public function apply(ModelStubInterface $model)
{
$callback = $this->callback;
if ($callback instanceof \Closure) {
$callback = $callback->bindTo($this);
}
return call_user_func($callback, $model);
} | {@inheritdoc} | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Criteria/CallbackCriteria.php#L38-L45 |
chilimatic/chilimatic-framework | lib/database/sql/mysql/Command.php | Command.kill_process | public function kill_process($pid)
{
if (!is_numeric($pid)) return false;
$pid = (int)$pid;
$sql = "KILL $pid";
return $this->db->query($sql);
} | php | public function kill_process($pid)
{
if (!is_numeric($pid)) return false;
$pid = (int)$pid;
$sql = "KILL $pid";
return $this->db->query($sql);
} | kill a specific process
@param int $pid
@return boolean | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/database/sql/mysql/Command.php#L44-L52 |
fxpio/fxp-gluon | Block/Type/FabType.php | FabType.buildView | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
$view->vars = array_replace($view->vars, [
'absolute_position' => str_replace('_', '-', $options['absolute_position']),
]);
} | php | public function buildView(BlockView $view, BlockInterface $block, array $options)
{
$view->vars = array_replace($view->vars, [
'absolute_position' => str_replace('_', '-', $options['absolute_position']),
]);
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/FabType.php#L30-L35 |
fxpio/fxp-gluon | Block/Type/FabType.php | FabType.finishView | public function finishView(BlockView $view, BlockInterface $block, array $options)
{
if (isset($view->vars['dropdown']) && \in_array($options['absolute_position'], ['top_right', 'bottom_right'])) {
/* @var BlockView $dropView */
$dropView = $view->vars['dropdown'];
BlockUtil::addAttributeClass($dropView, 'fab-pull-right');
}
} | php | public function finishView(BlockView $view, BlockInterface $block, array $options)
{
if (isset($view->vars['dropdown']) && \in_array($options['absolute_position'], ['top_right', 'bottom_right'])) {
/* @var BlockView $dropView */
$dropView = $view->vars['dropdown'];
BlockUtil::addAttributeClass($dropView, 'fab-pull-right');
}
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/FabType.php#L40-L47 |
fxpio/fxp-gluon | Block/Type/FabType.php | FabType.configureOptions | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'absolute_position' => null,
'dropup' => function (Options $options) {
return \in_array($options['absolute_position'], ['bottom_left', 'bottom_right'])
? true
: false;
},
]);
$resolver->addAllowedTypes('absolute_position', ['null', 'string']);
$resolver->addAllowedValues('absolute_position', [
null, 'top_left', 'top_right', 'bottom_left', 'bottom_right',
]);
} | php | public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'absolute_position' => null,
'dropup' => function (Options $options) {
return \in_array($options['absolute_position'], ['bottom_left', 'bottom_right'])
? true
: false;
},
]);
$resolver->addAllowedTypes('absolute_position', ['null', 'string']);
$resolver->addAllowedValues('absolute_position', [
null, 'top_left', 'top_right', 'bottom_left', 'bottom_right',
]);
} | {@inheritdoc} | https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Block/Type/FabType.php#L52-L68 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.setArray | public function setArray($key, array $values)
{
$this->validateKey($key);
if (empty($values)) {
throw new \InvalidArgumentException("Missing value.");
}
foreach ($values as $v) {
$this->validateValue($v);
}
$this->params[$key] = [];
foreach ($values as $v) {
$this->params[$key][] = $v;
}
return $this;
} | php | public function setArray($key, array $values)
{
$this->validateKey($key);
if (empty($values)) {
throw new \InvalidArgumentException("Missing value.");
}
foreach ($values as $v) {
$this->validateValue($v);
}
$this->params[$key] = [];
foreach ($values as $v) {
$this->params[$key][] = $v;
}
return $this;
} | Sets several values for the given parameter key.
@param string $key
@param array $values
@throws \InvalidArgumentException If the key is empty, the key is not a string, no values are given or a value is not a string.
@return self | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L59-L73 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.remove | public function remove($key)
{
$this->validateKey($key);
if ($this->has($key)) {
unset($this->params[$key]);
return true;
} else {
return false;
}
} | php | public function remove($key)
{
$this->validateKey($key);
if ($this->has($key)) {
unset($this->params[$key]);
return true;
} else {
return false;
}
} | Return all parameters with the given key.
@param string $key
@return boolean True if the parameter existed. | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L81-L90 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.replace | public function replace(array $new)
{
foreach ($new as $key => $values) {
$this->validateKey($key);
if (! is_array($values)) {
$values = $new[$key] = [
$values
];
}
foreach ($values as $v) {
$this->validateValue($v);
}
}
foreach ($new as $key => $values) {
$this->setArray($key, $values);
}
} | php | public function replace(array $new)
{
foreach ($new as $key => $values) {
$this->validateKey($key);
if (! is_array($values)) {
$values = $new[$key] = [
$values
];
}
foreach ($values as $v) {
$this->validateValue($v);
}
}
foreach ($new as $key => $values) {
$this->setArray($key, $values);
}
} | Sets several new parameters, replacing the old values if already present.
The provided array must be associative with the parameter keys as array
keys and parameter values as array values.
The array values may be either a string (to set a single parameter value)
or an array (to set multiple parameter values).
@param array $new | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L103-L119 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.getArray | public function getArray($key)
{
$this->validateKey($key);
return $this->has($key) ? $this->params[$key] : [];
} | php | public function getArray($key)
{
$this->validateKey($key);
return $this->has($key) ? $this->params[$key] : [];
} | Returns all values of the parameters with the given key.
If no parameter with the given key exists, an empty array is returned.
@param string $key
@return array | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L140-L144 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.toArray | public function toArray($onlyFirst = false)
{
$r = [];
foreach ($this->params as $key => $values) {
$r[$key] = $onlyFirst ? $values[0] : $values;
}
return $r;
} | php | public function toArray($onlyFirst = false)
{
$r = [];
foreach ($this->params as $key => $values) {
$r[$key] = $onlyFirst ? $values[0] : $values;
}
return $r;
} | Get all parameters as an associative array with the parameter keys as array keys.
Returns either only the first values of the parameters, or all values of the parameters.
@param boolean $onlyFirst
@return array | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L153-L160 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.count | public function count($key = null)
{
if (is_null($key)) {
return count($this->params);
}
return count($this->getArray($key));
} | php | public function count($key = null)
{
if (is_null($key)) {
return count($this->params);
}
return count($this->getArray($key));
} | Counts the parameters.
Parameter keys that appear multiple times count as one array parameter.
If the $key parameter is used, the number of values of this parameter are counted.
@param string $key
@return int | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L182-L188 |
timostamm/url-builder | src/UrlQuery.php | UrlQuery.equals | public function equals($other) {
if ($other instanceof UrlQuery) {
return ($this->isEmpty() && $other->isEmpty()) || ($this->__toString() === $other->__toString() );
}
if (is_null($other)) {
return $this->isEmpty();
}
return false;
} | php | public function equals($other) {
if ($other instanceof UrlQuery) {
return ($this->isEmpty() && $other->isEmpty()) || ($this->__toString() === $other->__toString() );
}
if (is_null($other)) {
return $this->isEmpty();
}
return false;
} | @param UrlQuery|NULL $other
{@inheritDoc}
@see UrlComponentInterface::equals() | https://github.com/timostamm/url-builder/blob/9dec80635017415d83b7e6ef155e9324f4b27a00/src/UrlQuery.php#L286-L294 |
seferov/blog-bundle | DependencyInjection/Configuration.php | Configuration.getConfigTreeBuilder | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('seferov_blog');
$rootNode
->children()
->integerNode('max_posts_per_page')
->defaultValue(6)
->end()
->scalarNode('layout')
->cannotBeEmpty()
->defaultValue('SeferovBlogBundle::layout.html.twig')
->end()
->arrayNode('widgets')
->children()
->arrayNode('facebook')
->children()
->scalarNode('app_id')->end()
->scalarNode('locale')->defaultValue('en_US')->end()
->scalarNode('version')->defaultValue('v2.6')->end()
->arrayNode('page')
->children()
->scalarNode('username')->end()
->scalarNode('name')->end()
->end()
->end()
->arrayNode('comments')
->children()
->integerNode('numposts')->defaultValue(10)->end()
->integerNode('width')->end()
->end()
->end()
->end()
->end()
->arrayNode('disqus')
->children()
->scalarNode('username')->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | php | public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('seferov_blog');
$rootNode
->children()
->integerNode('max_posts_per_page')
->defaultValue(6)
->end()
->scalarNode('layout')
->cannotBeEmpty()
->defaultValue('SeferovBlogBundle::layout.html.twig')
->end()
->arrayNode('widgets')
->children()
->arrayNode('facebook')
->children()
->scalarNode('app_id')->end()
->scalarNode('locale')->defaultValue('en_US')->end()
->scalarNode('version')->defaultValue('v2.6')->end()
->arrayNode('page')
->children()
->scalarNode('username')->end()
->scalarNode('name')->end()
->end()
->end()
->arrayNode('comments')
->children()
->integerNode('numposts')->defaultValue(10)->end()
->integerNode('width')->end()
->end()
->end()
->end()
->end()
->arrayNode('disqus')
->children()
->scalarNode('username')->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
} | {@inheritdoc} | https://github.com/seferov/blog-bundle/blob/55f3fbdf07766c88e6f6e95a0ec06a55cf194379/DependencyInjection/Configuration.php#L27-L73 |
luoxiaojun1992/lb_framework | components/traits/lb/Serializer.php | Serializer.serializeClosure | public function serializeClosure(\Closure $closure)
{
if ($this->isSingle()) {
return SerializeHelper::component()->serializeClosure($closure);
}
return null;
} | php | public function serializeClosure(\Closure $closure)
{
if ($this->isSingle()) {
return SerializeHelper::component()->serializeClosure($closure);
}
return null;
} | Serialize Closure
@param \Closure $closure
@return null | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/traits/lb/Serializer.php#L15-L22 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Property.php | Property.isProperty | function isProperty()
{
//Get the annotation index
$i = $this->getAnnotationIndex(self::PROPERTY);
//If the property annotation is on here
if($i >= 0)
{
//Set the format (Date, JSON, scalar, etc)
$this->format = $this->annotations[$i]->format;
//This is a property
return true;
}
else
{
//Not a property
return false;
}
} | php | function isProperty()
{
//Get the annotation index
$i = $this->getAnnotationIndex(self::PROPERTY);
//If the property annotation is on here
if($i >= 0)
{
//Set the format (Date, JSON, scalar, etc)
$this->format = $this->annotations[$i]->format;
//This is a property
return true;
}
else
{
//Not a property
return false;
}
} | Checks if this property is indeed a property.
@return bool | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Property.php#L112-L132 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Property.php | Property.getValue | function getValue($entity)
{
$raw = $this->property->getValue($entity);
switch ($this->format)
{
case 'scalar':
return $raw;
//Serialize classes and arrays before putting them in the DB
case 'object':
case 'array':
return serialize($raw);
//Json encode before putting into DB
case 'json':
return json_encode($raw);
//Format the date correctly before putting in DB
case 'date':
if ($raw)
{
$value = clone $raw;
$value->setTimezone(new \DateTimeZone('UTC'));
return $value->format('Y-m-d H:i:s');
}
else
{
return null;
}
}
return null;
} | php | function getValue($entity)
{
$raw = $this->property->getValue($entity);
switch ($this->format)
{
case 'scalar':
return $raw;
//Serialize classes and arrays before putting them in the DB
case 'object':
case 'array':
return serialize($raw);
//Json encode before putting into DB
case 'json':
return json_encode($raw);
//Format the date correctly before putting in DB
case 'date':
if ($raw)
{
$value = clone $raw;
$value->setTimezone(new \DateTimeZone('UTC'));
return $value->format('Y-m-d H:i:s');
}
else
{
return null;
}
}
return null;
} | Gets this property's value in the given entity.
@param Relation|Node $entity The entity to get the value from.
@return mixed The property value. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Property.php#L160-L195 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Property.php | Property.setValue | function setValue($entity, $value)
{
switch ($this->format)
{
case 'scalar':
$this->property->setValue($entity, $value);
break;
//Unserialize classes and arrays before putting them back in the entity.
case 'object':
case 'array':
$this->property->setValue($entity, unserialize($value));
break;
//Decode Json from DB back into a regular assoc array before putting it into the entity.
case 'json':
$this->property->setValue($entity, json_decode($value, true));
break;
//Create a date time object out of the db stored date before putting it into the entity.
case 'date':
$date = null;
if ($value) {
$date = new \DateTime($value . ' UTC');
$date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
}
$this->property->setValue($entity, $date);
break;
}
} | php | function setValue($entity, $value)
{
switch ($this->format)
{
case 'scalar':
$this->property->setValue($entity, $value);
break;
//Unserialize classes and arrays before putting them back in the entity.
case 'object':
case 'array':
$this->property->setValue($entity, unserialize($value));
break;
//Decode Json from DB back into a regular assoc array before putting it into the entity.
case 'json':
$this->property->setValue($entity, json_decode($value, true));
break;
//Create a date time object out of the db stored date before putting it into the entity.
case 'date':
$date = null;
if ($value) {
$date = new \DateTime($value . ' UTC');
$date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
}
$this->property->setValue($entity, $date);
break;
}
} | Sets this property's value in the given entity.
@param Relation|Node $entity The entity to set the property of.
@param mixed $value The value to set it to. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Property.php#L203-L233 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Property.php | Property.matches | function matches($names)
{
//Check every argument supplied
foreach (func_get_args() as $name)
{
//Check for any possible match
if (
0 === strcasecmp($name, $this->name) ||
0 === strcasecmp($name, $this->property->getName()) ||
0 === strcasecmp($name, Reflection::normalizeProperty($this->property->getName()))
)
{
return true;
}
}
return false;
} | php | function matches($names)
{
//Check every argument supplied
foreach (func_get_args() as $name)
{
//Check for any possible match
if (
0 === strcasecmp($name, $this->name) ||
0 === strcasecmp($name, $this->property->getName()) ||
0 === strcasecmp($name, Reflection::normalizeProperty($this->property->getName()))
)
{
return true;
}
}
return false;
} | Checks if a supplied name matches this property's name.
@param mixed $names List of names to check.
@return bool | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Property.php#L251-L268 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Property.php | Property.validateAnnotations | private function validateAnnotations()
{
//Count annotations in the annotation namespace, ignore annotations not in our namespace
$count = 0;
foreach($this->annotations as $a)
{
//If you find the namespace in the class name, add to count
if(strrpos(get_class($a), self::ANNOTATION_NAMESPACE) !== false)
{
$count++;
}
}
switch($count)
{
//0 annotations, just ignore
case 0:
return;
//1 Annotation, it can't be index.
case 1:
if($this->getAnnotationIndex(self::INDEX) < 0)
{
//It's not index, return.
return;
}
throw new Exception("@Index cannot be the only annotation on {$this->name} in {$this->property->getDeclaringClass()->getName()}.");
//2 Annotations, they have to be index and property.
case 2:
if( ($this->getAnnotationIndex(self::PROPERTY) >= 0) && ($this->getAnnotationIndex(self::INDEX) >= 0))
{
//They are index and property, return
return;
}
break;
}
//It didn't fall into any of the categories, must be invalid
throw new Exception("Invalid annotation combination on {$this->name} in {$this->property->getDeclaringClass()->getName()}.");
} | php | private function validateAnnotations()
{
//Count annotations in the annotation namespace, ignore annotations not in our namespace
$count = 0;
foreach($this->annotations as $a)
{
//If you find the namespace in the class name, add to count
if(strrpos(get_class($a), self::ANNOTATION_NAMESPACE) !== false)
{
$count++;
}
}
switch($count)
{
//0 annotations, just ignore
case 0:
return;
//1 Annotation, it can't be index.
case 1:
if($this->getAnnotationIndex(self::INDEX) < 0)
{
//It's not index, return.
return;
}
throw new Exception("@Index cannot be the only annotation on {$this->name} in {$this->property->getDeclaringClass()->getName()}.");
//2 Annotations, they have to be index and property.
case 2:
if( ($this->getAnnotationIndex(self::PROPERTY) >= 0) && ($this->getAnnotationIndex(self::INDEX) >= 0))
{
//They are index and property, return
return;
}
break;
}
//It didn't fall into any of the categories, must be invalid
throw new Exception("Invalid annotation combination on {$this->name} in {$this->property->getDeclaringClass()->getName()}.");
} | Validates the annotation combination on a property.
@throws Exception If the combination is invalid in some way. | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Property.php#L285-L330 |
lrezek/Arachnid | src/LRezek/Arachnid/Meta/Property.php | Property.getAnnotationIndex | private function getAnnotationIndex($name)
{
for($i = 0; $i < count($this->annotations); $i++)
{
if($this->annotations[$i] instanceof $name)
{
return $i;
}
}
return -1;
} | php | private function getAnnotationIndex($name)
{
for($i = 0; $i < count($this->annotations); $i++)
{
if($this->annotations[$i] instanceof $name)
{
return $i;
}
}
return -1;
} | Gets the index of a annotation with the value specified, or -1 if it's not in the annotations array.
@param String $name The annotation class.
@return int The index of the annotation in the annotations array(). | https://github.com/lrezek/Arachnid/blob/fbfc2c6f9d1dbfeef6f677813c12c570d5ea750a/src/LRezek/Arachnid/Meta/Property.php#L338-L349 |
phOnion/framework | src/Http/RequestHandler/RequestHandler.php | RequestHandler.handle | public function handle(Message\ServerRequestInterface $request): Message\ResponseInterface
{
if ($this->middleware->valid()) {
$middleware = $this->middleware->current();
assert($middleware instanceof MiddlewareInterface, new \TypeError('Invalid middleware type'));
$this->middleware->next();
return $middleware->process($request, $this);
}
if (null === $this->response) {
throw new \RuntimeException('No base response provided');
}
return $this->response;
} | php | public function handle(Message\ServerRequestInterface $request): Message\ResponseInterface
{
if ($this->middleware->valid()) {
$middleware = $this->middleware->current();
assert($middleware instanceof MiddlewareInterface, new \TypeError('Invalid middleware type'));
$this->middleware->next();
return $middleware->process($request, $this);
}
if (null === $this->response) {
throw new \RuntimeException('No base response provided');
}
return $this->response;
} | @param Message\ServerRequestInterface $request
@throws \RuntimeException If asked to return the response template, but the template is empty
@return Message\ResponseInterface | https://github.com/phOnion/framework/blob/eb2d99cc65d3b39faecbfd49b602fb2c62349d05/src/Http/RequestHandler/RequestHandler.php#L35-L50 |
PhoxPHP/Glider | src/Model/Uses/Record.php | Record.save | public function save(Model $relatedModel=null) : Model
{
$currentModel = $this;
$key = $currentModel->primaryKey();
if ($relatedModel instanceof Model) {
// Does it have a relatedModel? If no error is thrown till we get here,
// then the relationship was successfully initialized.
$parentModelForeignKey = $this->relationKeys['parent_model_foreign_key'];
$parentModelKeyValue = $this->relationKeys['parent_model_foreign_key_value'];
$currentModel = $relatedModel;
$currentModel->$parentModelForeignKey = $parentModelKeyValue;
$key = $currentModel->primaryKey();
}
// If id property exists, update instead.
if ($currentModel->$key) {
$currentModel->update(
$currentModel->$key,
$key,
$currentModel->getAssociatedTable(),
$currentModel->getSoftProperties()
);
return $currentModel;
}
$record = $currentModel->queryBuilder()->insert(
$currentModel->getAssociatedTable(), // name of model table
$currentModel->getSoftProperties() // model soft properties
);
// assign new property $id amd add to soft properties
$currentModel->id = $record->insertId();
return $currentModel;
} | php | public function save(Model $relatedModel=null) : Model
{
$currentModel = $this;
$key = $currentModel->primaryKey();
if ($relatedModel instanceof Model) {
// Does it have a relatedModel? If no error is thrown till we get here,
// then the relationship was successfully initialized.
$parentModelForeignKey = $this->relationKeys['parent_model_foreign_key'];
$parentModelKeyValue = $this->relationKeys['parent_model_foreign_key_value'];
$currentModel = $relatedModel;
$currentModel->$parentModelForeignKey = $parentModelKeyValue;
$key = $currentModel->primaryKey();
}
// If id property exists, update instead.
if ($currentModel->$key) {
$currentModel->update(
$currentModel->$key,
$key,
$currentModel->getAssociatedTable(),
$currentModel->getSoftProperties()
);
return $currentModel;
}
$record = $currentModel->queryBuilder()->insert(
$currentModel->getAssociatedTable(), // name of model table
$currentModel->getSoftProperties() // model soft properties
);
// assign new property $id amd add to soft properties
$currentModel->id = $record->insertId();
return $currentModel;
} | Saves data into the model table in the database. This method also updates the data
if an id property is present. If an id is present, a check is made to see if a row
with the given id exists or not.
This method accepts an argument of $relatedModel. If a model is passed here, the related model
will be saved.
@param $relatedModel <Object>
@access public
@return <Object> <Kit\Glider\Model\Model> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Uses/Record.php#L43-L82 |
PhoxPHP/Glider | src/Model/Uses/Record.php | Record.delete | public function delete() : Model
{
$builder = $this->queryBuilder();
if (isset($this->softProperties[$this->key])) {
$builder->where(
$this->key, $this->softProperties[$this->key]
);
}
$builder->delete($this->getAssociatedTable());
return $this;
} | php | public function delete() : Model
{
$builder = $this->queryBuilder();
if (isset($this->softProperties[$this->key])) {
$builder->where(
$this->key, $this->softProperties[$this->key]
);
}
$builder->delete($this->getAssociatedTable());
return $this;
} | Deletes/removes a record from the database table.
@access public
@return <Object> <Kit\Glider\Model\Model> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Uses/Record.php#L90-L103 |
PhoxPHP/Glider | src/Model/Uses/Record.php | Record.update | protected function update($keyValue=null, String $key, String $table, Array $properties=[])
{
if (isset($properties[$key])) {
unset($properties[$key]);
}
$this->queryBuilder()->where(
$key, $keyValue
)->update($table, $properties);
} | php | protected function update($keyValue=null, String $key, String $table, Array $properties=[])
{
if (isset($properties[$key])) {
unset($properties[$key]);
}
$this->queryBuilder()->where(
$key, $keyValue
)->update($table, $properties);
} | Updates an existing record in the database table.
@param $keyValue <Mixed>
@param $key <String>
@param $table <String>
@param $properties <Array>
@access protected
@return <void> | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Model/Uses/Record.php#L115-L125 |
xmmedia/XMFlashBundle | SymfonyFlashHandler.php | SymfonyFlashHandler.add | public function add($type, $message, array $params = [])
{
$this->session->getFlashBag()->add(
$type,
$this->trans($message, $params)
);
return $this;
} | php | public function add($type, $message, array $params = [])
{
$this->session->getFlashBag()->add(
$type,
$this->trans($message, $params)
);
return $this;
} | {@inheritdoc} | https://github.com/xmmedia/XMFlashBundle/blob/ddd1fc1dd10347dca7cf8febf7eca00e14d66006/SymfonyFlashHandler.php#L22-L30 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Section/Section.php | Section.serialize | public function serialize()
{
return serialize(array(
$this->key,
$this->diap,
$this->type,
$this->languages
));
} | php | public function serialize()
{
return serialize(array(
$this->key,
$this->diap,
$this->type,
$this->languages
));
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Section/Section.php#L176-L184 |
ZhukV/LanguageDetector | src/Ideea/LanguageDetector/Section/Section.php | Section.unserialize | public function unserialize($serialized)
{
list (
$this->key,
$this->diap,
$this->type,
$this->languages
) = unserialize($serialized);
} | php | public function unserialize($serialized)
{
list (
$this->key,
$this->diap,
$this->type,
$this->languages
) = unserialize($serialized);
} | {@inheritDoc} | https://github.com/ZhukV/LanguageDetector/blob/e5138f4c789e899801e098ce1e719337b015af7c/src/Ideea/LanguageDetector/Section/Section.php#L189-L197 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Globaljs/GlobalJs.php | GlobalJs.add | public function add($index, $data = null, $toAdmin = false)
{
if (!$this->has($index))
{
$this->data = Arr::add($this->data, $index, $data);
$this->metas = Arr::add($this->metas, $this->firstIndex($index), ['admin' => $toAdmin]);
}
return $this;
} | php | public function add($index, $data = null, $toAdmin = false)
{
if (!$this->has($index))
{
$this->data = Arr::add($this->data, $index, $data);
$this->metas = Arr::add($this->metas, $this->firstIndex($index), ['admin' => $toAdmin]);
}
return $this;
} | Append new data
@param string $index Unique identifier
@param null $data
@param bool $toAdmin If show on admin environment
@return $this | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Globaljs/GlobalJs.php#L49-L59 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Globaljs/GlobalJs.php | GlobalJs.remove | public function remove($index)
{
if ($this->has($index))
{
Arr::forget($this->data, $index);
Arr::forget($this->metas, $this->firstIndex($index));
}
return $this;
} | php | public function remove($index)
{
if ($this->has($index))
{
Arr::forget($this->data, $index);
Arr::forget($this->metas, $this->firstIndex($index));
}
return $this;
} | Remove index
@param $index
@return $this | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Globaljs/GlobalJs.php#L87-L96 |
bruno-barros/w.eloquent-framework | src/weloquent/Core/Globaljs/GlobalJs.php | GlobalJs.toJson | public function toJson($admin = false)
{
$data = $this->prepareDataToJson($admin);
if (count($data) == 0)
{
return '{}';
}
return json_encode($data);
} | php | public function toJson($admin = false)
{
$data = $this->prepareDataToJson($admin);
if (count($data) == 0)
{
return '{}';
}
return json_encode($data);
} | Return the data as JSON
@param bool $admin
@return string|void | https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Core/Globaljs/GlobalJs.php#L128-L138 |
hummer2k/ConLayout | src/Layout/Layout.php | Layout.load | public function load()
{
if (false === $this->isLoaded) {
$this->getEventManager()->trigger(
__FUNCTION__ . '.pre',
$this,
[]
);
$this->generate();
$this->injectBlocks();
$this->isLoaded = true;
$this->getEventManager()->trigger(
__FUNCTION__ . '.post',
$this,
[]
);
}
return $this;
} | php | public function load()
{
if (false === $this->isLoaded) {
$this->getEventManager()->trigger(
__FUNCTION__ . '.pre',
$this,
[]
);
$this->generate();
$this->injectBlocks();
$this->isLoaded = true;
$this->getEventManager()->trigger(
__FUNCTION__ . '.post',
$this,
[]
);
}
return $this;
} | inject blocks into the root view model
@return LayoutInterface | https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Layout/Layout.php#L97-L117 |
hummer2k/ConLayout | src/Layout/Layout.php | Layout.isAllowed | private function isAllowed($blockId, ModelInterface $block)
{
$result = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'block_id' => $blockId,
'block' => $block
]
);
if ($result->stopped()) {
return $result->last();
}
return true;
} | php | private function isAllowed($blockId, ModelInterface $block)
{
$result = $this->getEventManager()->trigger(
__FUNCTION__,
$this,
[
'block_id' => $blockId,
'block' => $block
]
);
if ($result->stopped()) {
return $result->last();
}
return true;
} | Determines whether a block should be allowed given certain parameters
@param string $blockId
@param ModelInterface $block
@return bool | https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Layout/Layout.php#L175-L189 |
hummer2k/ConLayout | src/Layout/Layout.php | Layout.addBlock | public function addBlock($blockId, ModelInterface $block)
{
$this->blockPool->add($blockId, $block);
return $this;
} | php | public function addBlock($blockId, ModelInterface $block)
{
$this->blockPool->add($blockId, $block);
return $this;
} | adds a block to the registry
@param string $blockId
@param ModelInterface $block
@return LayoutInterface | https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Layout/Layout.php#L198-L202 |
hummer2k/ConLayout | src/Layout/Layout.php | Layout.getCaptureTo | protected function getCaptureTo(ModelInterface $block)
{
$captureTo = $block->captureTo();
if ($parent = $block->getOption('parent')) {
$captureTo = explode(self::CAPTURE_TO_DELIMITER, $captureTo);
return [
$parent,
end($captureTo)
];
}
if (false !== strpos($captureTo, self::CAPTURE_TO_DELIMITER)) {
return explode(self::CAPTURE_TO_DELIMITER, $captureTo);
}
return [
self::BLOCK_ID_ROOT,
$captureTo
];
} | php | protected function getCaptureTo(ModelInterface $block)
{
$captureTo = $block->captureTo();
if ($parent = $block->getOption('parent')) {
$captureTo = explode(self::CAPTURE_TO_DELIMITER, $captureTo);
return [
$parent,
end($captureTo)
];
}
if (false !== strpos($captureTo, self::CAPTURE_TO_DELIMITER)) {
return explode(self::CAPTURE_TO_DELIMITER, $captureTo);
}
return [
self::BLOCK_ID_ROOT,
$captureTo
];
} | retrieve parent and capture_to as array, e.g.: [ 'layout', 'content' ]
so we are able to list() block_id and capture_to values
@param ModelInterface $block
@return array | https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Layout/Layout.php#L223-L240 |
LIN3S/CMSKernel | src/LIN3S/CMSKernel/Infrastructure/Symfony/Bundle/DependencyInjection/Compiler/ClassMapTemplateFactoryPass.php | ClassMapTemplateFactoryPass.process | public function process(ContainerBuilder $container)
{
$config = $container->getParameter('lin3s_cms_kernel.config');
if (!isset($config['templates']) || !isset($config['templates']['class_map'])) {
return;
}
foreach ($config['templates']['class_map'] as $entity => $templates) {
$container->setDefinition(
'lin3s_cms_kernel.' . $entity . '.template_factory',
(new Definition(ClassMapTemplateFactory::class))
)->addArgument($templates);
}
} | php | public function process(ContainerBuilder $container)
{
$config = $container->getParameter('lin3s_cms_kernel.config');
if (!isset($config['templates']) || !isset($config['templates']['class_map'])) {
return;
}
foreach ($config['templates']['class_map'] as $entity => $templates) {
$container->setDefinition(
'lin3s_cms_kernel.' . $entity . '.template_factory',
(new Definition(ClassMapTemplateFactory::class))
)->addArgument($templates);
}
} | {@inheritdoc} | https://github.com/LIN3S/CMSKernel/blob/71b5fc1930cd60d6eac1a9816df34af4654f9a7e/src/LIN3S/CMSKernel/Infrastructure/Symfony/Bundle/DependencyInjection/Compiler/ClassMapTemplateFactoryPass.php#L27-L41 |
oliwierptak/Everon1 | src/Everon/Domain/Repository.php | Repository.prepareDataForEntity | protected function prepareDataForEntity(array $data)
{
/**
* @var \Everon\DataMapper\Interfaces\Schema\Column $Column
*/
foreach ($this->getMapper()->getTable()->getColumns() as $name => $Column) {
if (array_key_exists($name, $data) === false) {
if ($Column->isPk()) {
$data[$name] = null;
}
else if ($Column->isNullable() === false) {
throw new Exception\Domain('Missing Entity data: "%s" for "%s"', [$name, $this->getMapper()->getTable()->getName()]);
}
$data[$name] = null;
}
$data[$name] = $Column->getColumnDataForEntity($data[$name]);
}
return $data;
} | php | protected function prepareDataForEntity(array $data)
{
/**
* @var \Everon\DataMapper\Interfaces\Schema\Column $Column
*/
foreach ($this->getMapper()->getTable()->getColumns() as $name => $Column) {
if (array_key_exists($name, $data) === false) {
if ($Column->isPk()) {
$data[$name] = null;
}
else if ($Column->isNullable() === false) {
throw new Exception\Domain('Missing Entity data: "%s" for "%s"', [$name, $this->getMapper()->getTable()->getName()]);
}
$data[$name] = null;
}
$data[$name] = $Column->getColumnDataForEntity($data[$name]);
}
return $data;
} | Makes sure data defined in the Entity is in proper format and all keys are set
@param array $data
@return array
@throws \Everon\Exception\Domain | https://github.com/oliwierptak/Everon1/blob/ac93793d1fa517a8394db5f00062f1925dc218a3/src/Everon/Domain/Repository.php#L62-L83 |
rujiali/acquia-site-factory-cli | src/AppBundle/Commands/SendNotificationCommand.php | SendNotificationCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$scope = $input->getArgument('scope');
$event = $input->getArgument('event');
$nid = $input->getArgument('nid');
$theme = $input->getArgument('theme');
$timestimp = $input->getArgument('timestamp');
$uid = $input->getArgument('uid');
$message = $this->connectorThemes->sendNotification($scope, $event, $nid, $theme, $timestimp, $uid);
$output->writeln($message);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$scope = $input->getArgument('scope');
$event = $input->getArgument('event');
$nid = $input->getArgument('nid');
$theme = $input->getArgument('theme');
$timestimp = $input->getArgument('timestamp');
$uid = $input->getArgument('uid');
$message = $this->connectorThemes->sendNotification($scope, $event, $nid, $theme, $timestimp, $uid);
$output->writeln($message);
} | {@inheritdoc} | https://github.com/rujiali/acquia-site-factory-cli/blob/c9dbb9dfd71408adff0ea26db94678a61c584df6/src/AppBundle/Commands/SendNotificationCommand.php#L52-L62 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/SubMenuStrategy.php | SubMenuStrategy.show | public function show(ReadBlockInterface $block)
{
$nodes = $this->getNodes($block);
if (!is_null($nodes)) {
return $this->render(
'OpenOrchestraDisplayBundle:Block/Menu:tree.html.twig',
array(
'tree' => $nodes,
'id' => $block->getId(),
'class' => $block->getStyle(),
)
);
}
throw new NodeNotFoundException($block->getAttribute('nodeName'));
} | php | public function show(ReadBlockInterface $block)
{
$nodes = $this->getNodes($block);
if (!is_null($nodes)) {
return $this->render(
'OpenOrchestraDisplayBundle:Block/Menu:tree.html.twig',
array(
'tree' => $nodes,
'id' => $block->getId(),
'class' => $block->getStyle(),
)
);
}
throw new NodeNotFoundException($block->getAttribute('nodeName'));
} | Perform the show action for a block
@param ReadBlockInterface $block
@return Response
@throws NodeNotFoundException | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/SubMenuStrategy.php#L78-L94 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/SubMenuStrategy.php | SubMenuStrategy.getNodes | protected function getNodes(ReadBlockInterface $block)
{
$nodes = null;
$nodeName = $block->getAttribute('nodeName');
$siteId = $this->currentSiteManager->getSiteId();
if (!is_null($nodeName)) {
$nodes = $this->nodeRepository->getSubMenu($nodeName, $block->getAttribute('nbLevel'), $this->request->getLocale(), $siteId);
$nodes = $this->getGrantedNodes($nodes);
}
return $nodes;
} | php | protected function getNodes(ReadBlockInterface $block)
{
$nodes = null;
$nodeName = $block->getAttribute('nodeName');
$siteId = $this->currentSiteManager->getSiteId();
if (!is_null($nodeName)) {
$nodes = $this->nodeRepository->getSubMenu($nodeName, $block->getAttribute('nbLevel'), $this->request->getLocale(), $siteId);
$nodes = $this->getGrantedNodes($nodes);
}
return $nodes;
} | Get nodes to display
@param ReadBlockInterface $block
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/SubMenuStrategy.php#L103-L115 |
open-orchestra/open-orchestra-display-bundle | DisplayBundle/DisplayBlock/Strategies/SubMenuStrategy.php | SubMenuStrategy.getCacheTags | public function getCacheTags(ReadBlockInterface $block)
{
$tags = array();
$nodes = $this->getNodes($block);
$siteId = $this->currentSiteManager->getSiteId();
$tags[] = $this->tagManager->formatMenuTag($siteId);
if ($nodes) {
foreach ($nodes as $node) {
$tags[] = $this->tagManager->formatNodeIdTag($node->getNodeId());
}
}
return $tags;
} | php | public function getCacheTags(ReadBlockInterface $block)
{
$tags = array();
$nodes = $this->getNodes($block);
$siteId = $this->currentSiteManager->getSiteId();
$tags[] = $this->tagManager->formatMenuTag($siteId);
if ($nodes) {
foreach ($nodes as $node) {
$tags[] = $this->tagManager->formatNodeIdTag($node->getNodeId());
}
}
return $tags;
} | Return block specific cache tags
@param ReadBlockInterface $block
@return array | https://github.com/open-orchestra/open-orchestra-display-bundle/blob/0e59e8686dac2d8408b57b63b975b4e5a1aa9472/DisplayBundle/DisplayBlock/Strategies/SubMenuStrategy.php#L124-L139 |
newup/core | src/Providers/GeneratorAnalyzerServiceProvider.php | GeneratorAnalyzerServiceProvider.register | public function register()
{
foreach ($this->singletonClassMap as $abstract => $concrete)
{
$this->app->singleton($abstract, function() use ($concrete)
{
return $this->app->make($concrete);
});
}
} | php | public function register()
{
foreach ($this->singletonClassMap as $abstract => $concrete)
{
$this->app->singleton($abstract, function() use ($concrete)
{
return $this->app->make($concrete);
});
}
} | Register the service provider.
@return void | https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Providers/GeneratorAnalyzerServiceProvider.php#L24-L33 |
cothema/cmsbe | src/model/Service/PagePin.php | PagePin.unpinIt | public function unpinIt()
{
$pinnedDao = $this->em->getRepository(Pinned::class);
$pinned = $pinnedDao->findBy(['user' => $this->presenter->user->id, 'page' => $this->presenter->getAction(true)]);
foreach ($pinned as $pinnedOne) {
$this->em->remove($pinnedOne);
}
$this->em->flush();
} | php | public function unpinIt()
{
$pinnedDao = $this->em->getRepository(Pinned::class);
$pinned = $pinnedDao->findBy(['user' => $this->presenter->user->id, 'page' => $this->presenter->getAction(true)]);
foreach ($pinned as $pinnedOne) {
$this->em->remove($pinnedOne);
}
$this->em->flush();
} | return void | https://github.com/cothema/cmsbe/blob/a5e162d421f6c52382d658891ee5b01e7bc6c7db/src/model/Service/PagePin.php#L61-L71 |
theloopyewe/ravelry-api.php | src/RavelryApi/ServiceClient.php | ServiceClient.defaultCommandFactory | public static function defaultCommandFactory(Description $description)
{
return function (
$name,
array $args = [],
GuzzleClientInterface $client
) use ($description) {
$operation = null;
if ($description->hasOperation($name)) {
$operation = $description->getOperation($name);
} else {
$name = ucfirst($name);
if ($description->hasOperation($name)) {
$operation = $description->getOperation($name);
}
}
if (!$operation) {
return null;
}
// this is the only line which is patched
$args += ($operation->getData('defaults') ?: []);
return new Command($operation, $args, clone $client->getEmitter());
};
} | php | public static function defaultCommandFactory(Description $description)
{
return function (
$name,
array $args = [],
GuzzleClientInterface $client
) use ($description) {
$operation = null;
if ($description->hasOperation($name)) {
$operation = $description->getOperation($name);
} else {
$name = ucfirst($name);
if ($description->hasOperation($name)) {
$operation = $description->getOperation($name);
}
}
if (!$operation) {
return null;
}
// this is the only line which is patched
$args += ($operation->getData('defaults') ?: []);
return new Command($operation, $args, clone $client->getEmitter());
};
} | We're overriding this to support operation-specific requestion options.
Currently this is for disabling `auth` on specific operations. | https://github.com/theloopyewe/ravelry-api.php/blob/4dacae056e15cf5fd4e236b79843d0736db1e885/src/RavelryApi/ServiceClient.php#L20-L48 |
theloopyewe/ravelry-api.php | src/RavelryApi/ServiceClient.php | ServiceClient.processConfig | protected function processConfig(array $config)
{
$config['command_factory'] = self::defaultCommandFactory($this->getDescription());
// we'll add our own patched processor after this
parent::processConfig(
array_merge(
$config,
[
'process' => false,
]
)
);
if (!isset($config['process']) || $config['process'] === true) {
$this->getEmitter()->attach(
new ProcessResponse(
isset($config['debug']) ? $config['debug'] : false,
isset($config['response_locations']) ? $config['response_locations'] : []
)
);
}
} | php | protected function processConfig(array $config)
{
$config['command_factory'] = self::defaultCommandFactory($this->getDescription());
// we'll add our own patched processor after this
parent::processConfig(
array_merge(
$config,
[
'process' => false,
]
)
);
if (!isset($config['process']) || $config['process'] === true) {
$this->getEmitter()->attach(
new ProcessResponse(
isset($config['debug']) ? $config['debug'] : false,
isset($config['response_locations']) ? $config['response_locations'] : []
)
);
}
} | We're overriding this to use our command factory from above and to use
custom objects for API results. | https://github.com/theloopyewe/ravelry-api.php/blob/4dacae056e15cf5fd4e236b79843d0736db1e885/src/RavelryApi/ServiceClient.php#L54-L76 |
tekkla/core-data | Core/Data/Connectors/Db/Structure/Table/Column/Columnlist.php | Columnlist.getColumn | public function getColumn(string $name)
{
if (!isset($this->fields[$name])) {
Throw new ColumnException(sprintf('A field named "%s" does not exist in this table', $name));
}
return $this->fields[$name];
} | php | public function getColumn(string $name)
{
if (!isset($this->fields[$name])) {
Throw new ColumnException(sprintf('A field named "%s" does not exist in this table', $name));
}
return $this->fields[$name];
} | (non-PHPdoc)
@see \Core\Data\Connectors\Db\Structure\Table\ColumnlistInterface::getColumn() | https://github.com/tekkla/core-data/blob/b751cdf40abb82a7ea1f48f5ae51354ac12ce394/Core/Data/Connectors/Db/Structure/Table/Column/Columnlist.php#L48-L55 |
cyberspectrum/i18n-contao | src/Mapping/Terminal42ChangeLanguage/ArticleContentMap.php | ArticleContentMap.buildMap | private function buildMap(): void
{
// Loop over all articles in target language.
foreach ($this->articleMap->targetIds() as $targetId) {
$mainId = $this->articleMap->getMainFromTarget($targetId);
$sourceId = $this->articleMap->getSourceIdFor($targetId);
// Now fetch all content elements for source and target.
$targetElements = $this->database->getContentByPidFrom($targetId, 'tl_article');
$sourceElements = $this->database->getContentByPidFrom($sourceId, 'tl_article');
$mainElements = $this->database->getContentByPidFrom($mainId, 'tl_article');
$this->mapElements($targetElements, $mainElements, $this->targetMap, $this->targetMapInverse);
$this->mapElements($sourceElements, $mainElements, $this->sourceMap, $this->sourceMapInverse);
$this->combineSourceAndTargetMaps();
}
} | php | private function buildMap(): void
{
// Loop over all articles in target language.
foreach ($this->articleMap->targetIds() as $targetId) {
$mainId = $this->articleMap->getMainFromTarget($targetId);
$sourceId = $this->articleMap->getSourceIdFor($targetId);
// Now fetch all content elements for source and target.
$targetElements = $this->database->getContentByPidFrom($targetId, 'tl_article');
$sourceElements = $this->database->getContentByPidFrom($sourceId, 'tl_article');
$mainElements = $this->database->getContentByPidFrom($mainId, 'tl_article');
$this->mapElements($targetElements, $mainElements, $this->targetMap, $this->targetMapInverse);
$this->mapElements($sourceElements, $mainElements, $this->sourceMap, $this->sourceMapInverse);
$this->combineSourceAndTargetMaps();
}
} | Build the map.
@return void | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/ArticleContentMap.php#L63-L79 |
cyberspectrum/i18n-contao | src/Mapping/Terminal42ChangeLanguage/ArticleContentMap.php | ArticleContentMap.mapElements | private function mapElements(array $elements, array $mainElements, array &$map, array &$inverse): void
{
foreach ($elements as $index => $element) {
$elementId = (int) $element['id'];
if (!array_key_exists($index, $mainElements)) {
$this->logger->warning(
'Content element {id} has no mapping in main. Element skipped.',
[
'id' => $elementId,
'msg_type' => 'article_content_no_main',
]
);
continue;
}
$mainElement = $mainElements[$index];
$mainId = (int) $mainElement['id'];
if ($element['type'] !== $mainElement['type']) {
$this->logger->warning(
'Content element {id} has different type as element in main. Element skipped.',
[
'id' => $elementId,
'mainId' => $mainId,
'msg_type' => 'article_content_type_mismatch'
]
);
continue;
}
$map[$elementId] = $mainId;
$inverse[$mainId] = $elementId;
}
} | php | private function mapElements(array $elements, array $mainElements, array &$map, array &$inverse): void
{
foreach ($elements as $index => $element) {
$elementId = (int) $element['id'];
if (!array_key_exists($index, $mainElements)) {
$this->logger->warning(
'Content element {id} has no mapping in main. Element skipped.',
[
'id' => $elementId,
'msg_type' => 'article_content_no_main',
]
);
continue;
}
$mainElement = $mainElements[$index];
$mainId = (int) $mainElement['id'];
if ($element['type'] !== $mainElement['type']) {
$this->logger->warning(
'Content element {id} has different type as element in main. Element skipped.',
[
'id' => $elementId,
'mainId' => $mainId,
'msg_type' => 'article_content_type_mismatch'
]
);
continue;
}
$map[$elementId] = $mainId;
$inverse[$mainId] = $elementId;
}
} | Map the passed elements.
@param array $elements The elements to map.
@param array $mainElements The main elements.
@param array $map The map to store elements to.
@param array $inverse The inverse map.
@return void | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Mapping/Terminal42ChangeLanguage/ArticleContentMap.php#L91-L123 |
aryelgois/medools-router | src/Controller.php | Controller.authenticate | public function authenticate(string $auth)
{
if ($this->router === null) {
return;
}
try {
$response = $this->router->authenticate($auth, 'Basic');
if (!($response instanceof Response)) {
$response = new Response;
$response->status = HttpResponse::HTTP_NO_CONTENT;
}
$response->output();
} catch (RouterException $e) {
$e->getResponse()->output();
}
} | php | public function authenticate(string $auth)
{
if ($this->router === null) {
return;
}
try {
$response = $this->router->authenticate($auth, 'Basic');
if (!($response instanceof Response)) {
$response = new Response;
$response->status = HttpResponse::HTTP_NO_CONTENT;
}
$response->output();
} catch (RouterException $e) {
$e->getResponse()->output();
}
} | Authenticates a Basic Authorization Header
When successful, a JWT is sent. It must be used for Bearer Authentication
with other routes
If the authentication is disabled, a 204 response is sent
@param string $auth Request Authorization Header | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Controller.php#L72-L88 |
aryelgois/medools-router | src/Controller.php | Controller.run | public function run(
string $method,
string $uri,
array $headers,
string $body
) {
if ($this->router === null) {
return;
}
try {
$response = $this->router->run($method, $uri, $headers, $body);
if ($response !== null) {
$response->output();
}
} catch (RouterException $e) {
$e->getResponse()->output();
}
} | php | public function run(
string $method,
string $uri,
array $headers,
string $body
) {
if ($this->router === null) {
return;
}
try {
$response = $this->router->run($method, $uri, $headers, $body);
if ($response !== null) {
$response->output();
}
} catch (RouterException $e) {
$e->getResponse()->output();
}
} | Runs the Router and outputs the Response
@param string $method Requested HTTP method
@param string $uri Requested URI
@param array $headers Request Headers
@param string $body Request Body | https://github.com/aryelgois/medools-router/blob/5d755f53b8099952d60cf15a0eb209af5fa3ca8a/src/Controller.php#L98-L116 |
as3io/modlr | src/Metadata/MixinMetadata.php | MixinMetadata.validateRelationship | protected function validateRelationship(RelationshipMetadata $relationship)
{
if (true === $this->hasAttribute($relationship->getKey())) {
throw MetadataException::fieldKeyInUse('relationship', 'attribute', $relationship->getKey(), $this->name);
}
if (true === $this->hasEmbed($relationship->getKey())) {
throw MetadataException::fieldKeyInUse('relationship', 'embed', $relationship->getKey(), $this->name);
}
} | php | protected function validateRelationship(RelationshipMetadata $relationship)
{
if (true === $this->hasAttribute($relationship->getKey())) {
throw MetadataException::fieldKeyInUse('relationship', 'attribute', $relationship->getKey(), $this->name);
}
if (true === $this->hasEmbed($relationship->getKey())) {
throw MetadataException::fieldKeyInUse('relationship', 'embed', $relationship->getKey(), $this->name);
}
} | {@inheritdoc} | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/MixinMetadata.php#L115-L123 |
acacha/forge-publish | src/Console/Commands/PublishAssignment.php | PublishAssignment.handle | public function handle()
{
$this->abortCommandExecution();
$this->existingAssignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
if ($this->existingAssignment) $this->error('An assignment with id : ' . $this->existingAssignment . ' already exists! Updating...' );
$this->assignmentName = $this->argument('name') ? $this->argument('name') : $this->askName();
$this->repository_uri = $this->argument('repository_uri') ? $this->argument('repository_uri') : $this->askRepositoryUri();
$this->repository_type = $this->argument('repository_type') ? $this->argument('repository_type') : $this->askRepositoryType();
$this->forge_site = $this->argument('forge_site') ? $this->argument('forge_site') : $this->askForgeSite();
$this->forge_server = $this->argument('forge_server') ? $this->argument('forge_server') : $this->askForgeServer();
if (! $this->existingAssignment) {
$this->createAssignment();
$this->info('Assignment created ok!');
} else {
$this->call('publish:update_assignment', [
'assignment' => $this->existingAssignment,
'name' => $this->assignmentName,
'repository_uri' => $this->repository_uri,
'repository_type' => $this->repository_type,
'forge_site' => $this->forge_site,
'forge_server' => $this->forge_server,
]);
}
$this->call('publish:assignment_groups');
$this->call('publish:assignment_users');
} | php | public function handle()
{
$this->abortCommandExecution();
$this->existingAssignment = fp_env('ACACHA_FORGE_ASSIGNMENT');
if ($this->existingAssignment) $this->error('An assignment with id : ' . $this->existingAssignment . ' already exists! Updating...' );
$this->assignmentName = $this->argument('name') ? $this->argument('name') : $this->askName();
$this->repository_uri = $this->argument('repository_uri') ? $this->argument('repository_uri') : $this->askRepositoryUri();
$this->repository_type = $this->argument('repository_type') ? $this->argument('repository_type') : $this->askRepositoryType();
$this->forge_site = $this->argument('forge_site') ? $this->argument('forge_site') : $this->askForgeSite();
$this->forge_server = $this->argument('forge_server') ? $this->argument('forge_server') : $this->askForgeServer();
if (! $this->existingAssignment) {
$this->createAssignment();
$this->info('Assignment created ok!');
} else {
$this->call('publish:update_assignment', [
'assignment' => $this->existingAssignment,
'name' => $this->assignmentName,
'repository_uri' => $this->repository_uri,
'repository_type' => $this->repository_type,
'forge_site' => $this->forge_site,
'forge_server' => $this->forge_server,
]);
}
$this->call('publish:assignment_groups');
$this->call('publish:assignment_users');
} | Execute the console command. | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignment.php#L102-L132 |
acacha/forge-publish | src/Console/Commands/PublishAssignment.php | PublishAssignment.createAssignment | protected function createAssignment()
{
$url = config('forge-publish.url') . config('forge-publish.store_assignment_uri');
try {
$response = $this->http->post($url, [
'form_params' => [
'name' => $this->assignmentName,
'repository_uri' => $this->repository_uri,
'repository_type' => $this->repository_type,
'forge_site' => $this->forge_site,
'forge_server' => $this->forge_server
],
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]);
} catch (\Exception $e) {
$this->error('And error occurs connecting to the api url: ' . $url);
$this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
return;
}
$assignment = json_decode((string) $response->getBody());
$this->addValueToEnv('ACACHA_FORGE_ASSIGNMENT', $assignment->id);
return $assignment;
} | php | protected function createAssignment()
{
$url = config('forge-publish.url') . config('forge-publish.store_assignment_uri');
try {
$response = $this->http->post($url, [
'form_params' => [
'name' => $this->assignmentName,
'repository_uri' => $this->repository_uri,
'repository_type' => $this->repository_type,
'forge_site' => $this->forge_site,
'forge_server' => $this->forge_server
],
'headers' => [
'X-Requested-With' => 'XMLHttpRequest',
'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN')
]
]);
} catch (\Exception $e) {
$this->error('And error occurs connecting to the api url: ' . $url);
$this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase());
return;
}
$assignment = json_decode((string) $response->getBody());
$this->addValueToEnv('ACACHA_FORGE_ASSIGNMENT', $assignment->id);
return $assignment;
} | Create assignment.
@return array|mixed | https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishAssignment.php#L139-L164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.