repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.setBotExtrasRequest
protected function setBotExtrasRequest(): self { $request_extras = [ // None at the moment... ]; // For request extras, just pass the single param value to the Request method. foreach ($request_extras as $param_key => $method) { $param = $this->params->getBotParam($param_key); if (null !== $param) { Request::$method($param); } } // Special cases. $limiter_enabled = $this->params->getBotParam('limiter.enabled'); if ($limiter_enabled !== null) { $limiter_options = $this->params->getBotParam('limiter.options', []); Request::setLimiter($limiter_enabled, $limiter_options); } return $this; }
php
protected function setBotExtrasRequest(): self { $request_extras = [ // None at the moment... ]; // For request extras, just pass the single param value to the Request method. foreach ($request_extras as $param_key => $method) { $param = $this->params->getBotParam($param_key); if (null !== $param) { Request::$method($param); } } // Special cases. $limiter_enabled = $this->params->getBotParam('limiter.enabled'); if ($limiter_enabled !== null) { $limiter_options = $this->params->getBotParam('limiter.options', []); Request::setLimiter($limiter_enabled, $limiter_options); } return $this; }
[ "protected", "function", "setBotExtrasRequest", "(", ")", ":", "self", "{", "$", "request_extras", "=", "[", "// None at the moment...", "]", ";", "// For request extras, just pass the single param value to the Request method.", "foreach", "(", "$", "request_extras", "as", ...
Set extra bot parameters for Request class. @return \TelegramBot\TelegramBotManager\BotManager @throws \Longman\TelegramBot\Exception\TelegramException
[ "Set", "extra", "bot", "parameters", "for", "Request", "class", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L324-L345
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.handleRequest
public function handleRequest(): self { if ($this->params->getBotParam('webhook.url')) { return $this->handleWebhook(); } if ($loop_time = $this->getLoopTime()) { return $this->handleGetUpdatesLoop($loop_time, $this->getLoopInterval()); } return $this->handleGetUpdates(); }
php
public function handleRequest(): self { if ($this->params->getBotParam('webhook.url')) { return $this->handleWebhook(); } if ($loop_time = $this->getLoopTime()) { return $this->handleGetUpdatesLoop($loop_time, $this->getLoopInterval()); } return $this->handleGetUpdates(); }
[ "public", "function", "handleRequest", "(", ")", ":", "self", "{", "if", "(", "$", "this", "->", "params", "->", "getBotParam", "(", "'webhook.url'", ")", ")", "{", "return", "$", "this", "->", "handleWebhook", "(", ")", ";", "}", "if", "(", "$", "lo...
Handle the request, which calls either the Webhook or getUpdates method respectively. @return \TelegramBot\TelegramBotManager\BotManager @throws \Longman\TelegramBot\Exception\TelegramException
[ "Handle", "the", "request", "which", "calls", "either", "the", "Webhook", "or", "getUpdates", "method", "respectively", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L353-L364
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.handleCron
public function handleCron(): self { $groups = explode(',', $this->params->getScriptParam('g', 'default')); $commands = []; foreach ($groups as $group) { $commands[] = $this->params->getBotParam('cron.groups.' . $group, []); } $this->telegram->runCommands(array_merge(...$commands)); return $this; }
php
public function handleCron(): self { $groups = explode(',', $this->params->getScriptParam('g', 'default')); $commands = []; foreach ($groups as $group) { $commands[] = $this->params->getBotParam('cron.groups.' . $group, []); } $this->telegram->runCommands(array_merge(...$commands)); return $this; }
[ "public", "function", "handleCron", "(", ")", ":", "self", "{", "$", "groups", "=", "explode", "(", "','", ",", "$", "this", "->", "params", "->", "getScriptParam", "(", "'g'", ",", "'default'", ")", ")", ";", "$", "commands", "=", "[", "]", ";", "...
Handle cron. @return \TelegramBot\TelegramBotManager\BotManager @throws \Longman\TelegramBot\Exception\TelegramException
[ "Handle", "cron", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L372-L383
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.getLoopTime
public function getLoopTime(): int { $loop_time = $this->params->getScriptParam('l'); if (null === $loop_time) { return 0; } if (\is_string($loop_time) && '' === trim($loop_time)) { return 604800; // Default to 7 days. } return max(0, (int) $loop_time); }
php
public function getLoopTime(): int { $loop_time = $this->params->getScriptParam('l'); if (null === $loop_time) { return 0; } if (\is_string($loop_time) && '' === trim($loop_time)) { return 604800; // Default to 7 days. } return max(0, (int) $loop_time); }
[ "public", "function", "getLoopTime", "(", ")", ":", "int", "{", "$", "loop_time", "=", "$", "this", "->", "params", "->", "getScriptParam", "(", "'l'", ")", ";", "if", "(", "null", "===", "$", "loop_time", ")", "{", "return", "0", ";", "}", "if", "...
Get the number of seconds the script should loop. @return int
[ "Get", "the", "number", "of", "seconds", "the", "script", "should", "loop", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L390-L403
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.getLoopInterval
public function getLoopInterval(): int { $interval_time = $this->params->getScriptParam('i'); if (null === $interval_time || (\is_string($interval_time) && '' === trim($interval_time))) { return 2; } // Minimum interval is 1 second. return max(1, (int) $interval_time); }
php
public function getLoopInterval(): int { $interval_time = $this->params->getScriptParam('i'); if (null === $interval_time || (\is_string($interval_time) && '' === trim($interval_time))) { return 2; } // Minimum interval is 1 second. return max(1, (int) $interval_time); }
[ "public", "function", "getLoopInterval", "(", ")", ":", "int", "{", "$", "interval_time", "=", "$", "this", "->", "params", "->", "getScriptParam", "(", "'i'", ")", ";", "if", "(", "null", "===", "$", "interval_time", "||", "(", "\\", "is_string", "(", ...
Get the number of seconds the script should wait after each getUpdates request. @return int
[ "Get", "the", "number", "of", "seconds", "the", "script", "should", "wait", "after", "each", "getUpdates", "request", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L410-L420
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.handleGetUpdatesLoop
public function handleGetUpdatesLoop(int $loop_time_in_seconds, int $loop_interval_in_seconds = 2): self { // Remember the time we started this loop. $now = time(); $this->handleOutput('Looping getUpdates until ' . date('Y-m-d H:i:s', $now + $loop_time_in_seconds) . PHP_EOL); while ($now > time() - $loop_time_in_seconds) { $this->handleGetUpdates(); // Chill a bit. sleep($loop_interval_in_seconds); } return $this; }
php
public function handleGetUpdatesLoop(int $loop_time_in_seconds, int $loop_interval_in_seconds = 2): self { // Remember the time we started this loop. $now = time(); $this->handleOutput('Looping getUpdates until ' . date('Y-m-d H:i:s', $now + $loop_time_in_seconds) . PHP_EOL); while ($now > time() - $loop_time_in_seconds) { $this->handleGetUpdates(); // Chill a bit. sleep($loop_interval_in_seconds); } return $this; }
[ "public", "function", "handleGetUpdatesLoop", "(", "int", "$", "loop_time_in_seconds", ",", "int", "$", "loop_interval_in_seconds", "=", "2", ")", ":", "self", "{", "// Remember the time we started this loop.", "$", "now", "=", "time", "(", ")", ";", "$", "this", ...
Loop the getUpdates method for the passed amount of seconds. @param int $loop_time_in_seconds @param int $loop_interval_in_seconds @return \TelegramBot\TelegramBotManager\BotManager @throws \Longman\TelegramBot\Exception\TelegramException
[ "Loop", "the", "getUpdates", "method", "for", "the", "passed", "amount", "of", "seconds", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L431-L446
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.handleGetUpdates
public function handleGetUpdates(): self { $get_updates_response = $this->telegram->handleGetUpdates(); // Check if the user has set a custom callback for handling the response. if ($this->custom_get_updates_callback !== null) { $this->handleOutput(\call_user_func($this->custom_get_updates_callback, $get_updates_response)); } else { $this->handleOutput($this->defaultGetUpdatesCallback($get_updates_response)); } return $this; }
php
public function handleGetUpdates(): self { $get_updates_response = $this->telegram->handleGetUpdates(); // Check if the user has set a custom callback for handling the response. if ($this->custom_get_updates_callback !== null) { $this->handleOutput(\call_user_func($this->custom_get_updates_callback, $get_updates_response)); } else { $this->handleOutput($this->defaultGetUpdatesCallback($get_updates_response)); } return $this; }
[ "public", "function", "handleGetUpdates", "(", ")", ":", "self", "{", "$", "get_updates_response", "=", "$", "this", "->", "telegram", "->", "handleGetUpdates", "(", ")", ";", "// Check if the user has set a custom callback for handling the response.", "if", "(", "$", ...
Handle the updates using the getUpdates method. @return \TelegramBot\TelegramBotManager\BotManager @throws \Longman\TelegramBot\Exception\TelegramException
[ "Handle", "the", "updates", "using", "the", "getUpdates", "method", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L467-L479
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.defaultGetUpdatesCallback
protected function defaultGetUpdatesCallback($get_updates_response): string { if (!$get_updates_response->isOk()) { return sprintf( '%s - Failed to fetch updates' . PHP_EOL . '%s', date('Y-m-d H:i:s'), $get_updates_response->printError(true) ); } /** @var Entities\Update[] $results */ $results = array_filter((array) $get_updates_response->getResult()); $output = sprintf( '%s - Updates processed: %d' . PHP_EOL, date('Y-m-d H:i:s'), count($results) ); foreach ($results as $result) { $chat_id = 0; $text = '<n/a>'; $update_content = $result->getUpdateContent(); if ($update_content instanceof Entities\Message) { $chat_id = $update_content->getChat()->getId(); $text = sprintf('<%s>', $update_content->getType()); } elseif ($update_content instanceof Entities\InlineQuery || $update_content instanceof Entities\ChosenInlineResult ) { $chat_id = $update_content->getFrom()->getId(); $text = sprintf('<query> %s', $update_content->getQuery()); } $output .= sprintf( '%d: %s' . PHP_EOL, $chat_id, preg_replace('/\s+/', ' ', trim($text)) ); } return $output; }
php
protected function defaultGetUpdatesCallback($get_updates_response): string { if (!$get_updates_response->isOk()) { return sprintf( '%s - Failed to fetch updates' . PHP_EOL . '%s', date('Y-m-d H:i:s'), $get_updates_response->printError(true) ); } /** @var Entities\Update[] $results */ $results = array_filter((array) $get_updates_response->getResult()); $output = sprintf( '%s - Updates processed: %d' . PHP_EOL, date('Y-m-d H:i:s'), count($results) ); foreach ($results as $result) { $chat_id = 0; $text = '<n/a>'; $update_content = $result->getUpdateContent(); if ($update_content instanceof Entities\Message) { $chat_id = $update_content->getChat()->getId(); $text = sprintf('<%s>', $update_content->getType()); } elseif ($update_content instanceof Entities\InlineQuery || $update_content instanceof Entities\ChosenInlineResult ) { $chat_id = $update_content->getFrom()->getId(); $text = sprintf('<query> %s', $update_content->getQuery()); } $output .= sprintf( '%d: %s' . PHP_EOL, $chat_id, preg_replace('/\s+/', ' ', trim($text)) ); } return $output; }
[ "protected", "function", "defaultGetUpdatesCallback", "(", "$", "get_updates_response", ")", ":", "string", "{", "if", "(", "!", "$", "get_updates_response", "->", "isOk", "(", ")", ")", "{", "return", "sprintf", "(", "'%s - Failed to fetch updates'", ".", "PHP_EO...
Return the default output for getUpdates handling. @param Entities\ServerResponse $get_updates_response @return string
[ "Return", "the", "default", "output", "for", "getUpdates", "handling", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L488-L530
train
php-telegram-bot/telegram-bot-manager
src/BotManager.php
BotManager.isValidRequest
public function isValidRequest(): bool { // If we're running from CLI, requests are always valid, unless we're running the tests. if ((!self::inTest() && 'cli' === PHP_SAPI) || false === $this->params->getBotParam('validate_request')) { return true; } $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'] as $key) { if (filter_var($_SERVER[$key] ?? null, FILTER_VALIDATE_IP)) { $ip = $_SERVER[$key]; break; } } return Ip::match($ip, array_merge( [self::TELEGRAM_IP_RANGE], (array) $this->params->getBotParam('valid_ips', []) )); }
php
public function isValidRequest(): bool { // If we're running from CLI, requests are always valid, unless we're running the tests. if ((!self::inTest() && 'cli' === PHP_SAPI) || false === $this->params->getBotParam('validate_request')) { return true; } $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'; foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR'] as $key) { if (filter_var($_SERVER[$key] ?? null, FILTER_VALIDATE_IP)) { $ip = $_SERVER[$key]; break; } } return Ip::match($ip, array_merge( [self::TELEGRAM_IP_RANGE], (array) $this->params->getBotParam('valid_ips', []) )); }
[ "public", "function", "isValidRequest", "(", ")", ":", "bool", "{", "// If we're running from CLI, requests are always valid, unless we're running the tests.", "if", "(", "(", "!", "self", "::", "inTest", "(", ")", "&&", "'cli'", "===", "PHP_SAPI", ")", "||", "false",...
Check if this is a valid request coming from a Telegram API IP address. @link https://core.telegram.org/bots/webhooks#the-short-version @return bool
[ "Check", "if", "this", "is", "a", "valid", "request", "coming", "from", "a", "Telegram", "API", "IP", "address", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/BotManager.php#L565-L584
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.validateAndSetBotParams
private function validateAndSetBotParams(array $params): self { $this->validateAndSetBotParamsVital($params); $this->validateAndSetBotParamsSpecial($params); $this->validateAndSetBotParamsExtra($params); return $this; }
php
private function validateAndSetBotParams(array $params): self { $this->validateAndSetBotParamsVital($params); $this->validateAndSetBotParamsSpecial($params); $this->validateAndSetBotParamsExtra($params); return $this; }
[ "private", "function", "validateAndSetBotParams", "(", "array", "$", "params", ")", ":", "self", "{", "$", "this", "->", "validateAndSetBotParamsVital", "(", "$", "params", ")", ";", "$", "this", "->", "validateAndSetBotParamsSpecial", "(", "$", "params", ")", ...
Validate and set up the vital and extra params. @param array $params @return \TelegramBot\TelegramBotManager\Params @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
[ "Validate", "and", "set", "up", "the", "vital", "and", "extra", "params", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L118-L125
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.validateAndSetBotParamsVital
private function validateAndSetBotParamsVital(array $params) { foreach (self::$valid_vital_bot_params as $vital_key) { if (!array_key_exists($vital_key, $params)) { throw new InvalidParamsException('Some vital info is missing: ' . $vital_key); } $this->bot_params[$vital_key] = $params[$vital_key]; } }
php
private function validateAndSetBotParamsVital(array $params) { foreach (self::$valid_vital_bot_params as $vital_key) { if (!array_key_exists($vital_key, $params)) { throw new InvalidParamsException('Some vital info is missing: ' . $vital_key); } $this->bot_params[$vital_key] = $params[$vital_key]; } }
[ "private", "function", "validateAndSetBotParamsVital", "(", "array", "$", "params", ")", "{", "foreach", "(", "self", "::", "$", "valid_vital_bot_params", "as", "$", "vital_key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "vital_key", ",", "$", ...
Set all vital params. @param array $params @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
[ "Set", "all", "vital", "params", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L134-L143
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.validateAndSetBotParamsSpecial
private function validateAndSetBotParamsSpecial(array $params) { // Special case, where secret MUST be defined if we have a webhook. if (($params['webhook']['url'] ?? null) && !($params['secret'] ?? null)) { // This does not apply when using CLI, but make sure it gets tested for! if ('cli' !== PHP_SAPI || BotManager::inTest()) { throw new InvalidParamsException('Some vital info is missing: secret'); } } }
php
private function validateAndSetBotParamsSpecial(array $params) { // Special case, where secret MUST be defined if we have a webhook. if (($params['webhook']['url'] ?? null) && !($params['secret'] ?? null)) { // This does not apply when using CLI, but make sure it gets tested for! if ('cli' !== PHP_SAPI || BotManager::inTest()) { throw new InvalidParamsException('Some vital info is missing: secret'); } } }
[ "private", "function", "validateAndSetBotParamsSpecial", "(", "array", "$", "params", ")", "{", "// Special case, where secret MUST be defined if we have a webhook.", "if", "(", "(", "$", "params", "[", "'webhook'", "]", "[", "'url'", "]", "??", "null", ")", "&&", "...
Special case parameters. @param array $params @throws \TelegramBot\TelegramBotManager\Exception\InvalidParamsException
[ "Special", "case", "parameters", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L152-L161
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.validateAndSetBotParamsExtra
private function validateAndSetBotParamsExtra(array $params) { foreach (self::$valid_extra_bot_params as $extra_key) { if (!array_key_exists($extra_key, $params)) { continue; } $this->bot_params[$extra_key] = $params[$extra_key]; } }
php
private function validateAndSetBotParamsExtra(array $params) { foreach (self::$valid_extra_bot_params as $extra_key) { if (!array_key_exists($extra_key, $params)) { continue; } $this->bot_params[$extra_key] = $params[$extra_key]; } }
[ "private", "function", "validateAndSetBotParamsExtra", "(", "array", "$", "params", ")", "{", "foreach", "(", "self", "::", "$", "valid_extra_bot_params", "as", "$", "extra_key", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "extra_key", ",", "$", ...
Set all extra params. @param array $params
[ "Set", "all", "extra", "params", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L168-L177
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.setScriptParams
private function setScriptParams() { $this->script_params = $_GET; // If we're not running from CLI, script parameters are already set from $_GET. if ('cli' !== PHP_SAPI) { return; } // We don't need the first arg (the file name). $args = \array_slice($_SERVER['argv'], 1); /** @var array $args */ foreach ($args as $arg) { @list($key, $val) = explode('=', $arg); isset($key, $val) && $this->script_params[$key] = $val; } }
php
private function setScriptParams() { $this->script_params = $_GET; // If we're not running from CLI, script parameters are already set from $_GET. if ('cli' !== PHP_SAPI) { return; } // We don't need the first arg (the file name). $args = \array_slice($_SERVER['argv'], 1); /** @var array $args */ foreach ($args as $arg) { @list($key, $val) = explode('=', $arg); isset($key, $val) && $this->script_params[$key] = $val; } }
[ "private", "function", "setScriptParams", "(", ")", "{", "$", "this", "->", "script_params", "=", "$", "_GET", ";", "// If we're not running from CLI, script parameters are already set from $_GET.", "if", "(", "'cli'", "!==", "PHP_SAPI", ")", "{", "return", ";", "}", ...
Set script parameters from query string or CLI.
[ "Set", "script", "parameters", "from", "query", "string", "or", "CLI", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L198-L215
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.validateScriptParams
private function validateScriptParams() { $this->script_params = array_intersect_key( $this->script_params, array_fill_keys(self::$valid_script_params, null) ); }
php
private function validateScriptParams() { $this->script_params = array_intersect_key( $this->script_params, array_fill_keys(self::$valid_script_params, null) ); }
[ "private", "function", "validateScriptParams", "(", ")", "{", "$", "this", "->", "script_params", "=", "array_intersect_key", "(", "$", "this", "->", "script_params", ",", "array_fill_keys", "(", "self", "::", "$", "valid_script_params", ",", "null", ")", ")", ...
Keep only valid script parameters.
[ "Keep", "only", "valid", "script", "parameters", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L220-L226
train
php-telegram-bot/telegram-bot-manager
src/Params.php
Params.getBotParam
public function getBotParam(string $param, $default = null) { $param_path = explode('.', $param); $value = $this->bot_params[array_shift($param_path)] ?? null; foreach ($param_path as $sub_param_key) { $value = $value[$sub_param_key] ?? null; if (null === $value) { break; } } return $value ?? $default; }
php
public function getBotParam(string $param, $default = null) { $param_path = explode('.', $param); $value = $this->bot_params[array_shift($param_path)] ?? null; foreach ($param_path as $sub_param_key) { $value = $value[$sub_param_key] ?? null; if (null === $value) { break; } } return $value ?? $default; }
[ "public", "function", "getBotParam", "(", "string", "$", "param", ",", "$", "default", "=", "null", ")", "{", "$", "param_path", "=", "explode", "(", "'.'", ",", "$", "param", ")", ";", "$", "value", "=", "$", "this", "->", "bot_params", "[", "array_...
Get a specific bot param, allowing array-dot notation. @param string $param @param mixed $default @return mixed
[ "Get", "a", "specific", "bot", "param", "allowing", "array", "-", "dot", "notation", "." ]
62333217bdd00fe140ca33ef5a45c16139bc675a
https://github.com/php-telegram-bot/telegram-bot-manager/blob/62333217bdd00fe140ca33ef5a45c16139bc675a/src/Params.php#L236-L249
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Admin/MessageAdmin.php
MessageAdmin.filteredOnTranslations
public function filteredOnTranslations($queryBuilder, $alias, $field, $value) { if (!$value['value']) { return false; } $queryBuilder->leftJoin(sprintf('%s.translations', $alias), 't'); $queryBuilder->andWhere( $queryBuilder->expr()->orX( $queryBuilder->expr()->like('o.message', ':tr'), $queryBuilder->expr()->like('t.translation', ':tr') ) ); $queryBuilder->setParameter('tr', '%' . $value['value'] . '%'); return true; }
php
public function filteredOnTranslations($queryBuilder, $alias, $field, $value) { if (!$value['value']) { return false; } $queryBuilder->leftJoin(sprintf('%s.translations', $alias), 't'); $queryBuilder->andWhere( $queryBuilder->expr()->orX( $queryBuilder->expr()->like('o.message', ':tr'), $queryBuilder->expr()->like('t.translation', ':tr') ) ); $queryBuilder->setParameter('tr', '%' . $value['value'] . '%'); return true; }
[ "public", "function", "filteredOnTranslations", "(", "$", "queryBuilder", ",", "$", "alias", ",", "$", "field", ",", "$", "value", ")", "{", "if", "(", "!", "$", "value", "[", "'value'", "]", ")", "{", "return", "false", ";", "}", "$", "queryBuilder", ...
Custom search handler Changes the filter behaviour to also search in the message_translation table @param \Doctrine\ORM\QueryBuilder $queryBuilder @param string $alias @param string $field @param array $value @return bool
[ "Custom", "search", "handler" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Admin/MessageAdmin.php#L130-L148
train
duncan3dc/object-intruder
src/Intruder.php
Intruder.getReflection
private function getReflection(): \ReflectionClass { if ($this->_intruderReflection === null) { $this->_intruderReflection = new \ReflectionClass($this->_intruderInstance); } return $this->_intruderReflection; }
php
private function getReflection(): \ReflectionClass { if ($this->_intruderReflection === null) { $this->_intruderReflection = new \ReflectionClass($this->_intruderInstance); } return $this->_intruderReflection; }
[ "private", "function", "getReflection", "(", ")", ":", "\\", "ReflectionClass", "{", "if", "(", "$", "this", "->", "_intruderReflection", "===", "null", ")", "{", "$", "this", "->", "_intruderReflection", "=", "new", "\\", "ReflectionClass", "(", "$", "this"...
Get a reflection class of the object we are wrapping. @return \ReflectionClass
[ "Get", "a", "reflection", "class", "of", "the", "object", "we", "are", "wrapping", "." ]
40388a680eac9d4558e56df990c177555ba59ed8
https://github.com/duncan3dc/object-intruder/blob/40388a680eac9d4558e56df990c177555ba59ed8/src/Intruder.php#L45-L52
train
duncan3dc/object-intruder
src/Intruder.php
Intruder.getProperty
private function getProperty(string $name): \ReflectionProperty { $class = $this->getReflection(); # See if the literal class has this property if ($class->hasProperty($name)) { return $class->getProperty($name); } # If not this class then check its parents $parent = $class; while (true) { $parent = $parent->getParentClass(); if (!$parent) { break; } if ($parent->hasProperty($name)) { return $parent->getProperty($name); } } # We didn't find the property, but use this to give a sensible error return $class->getProperty($name); }
php
private function getProperty(string $name): \ReflectionProperty { $class = $this->getReflection(); # See if the literal class has this property if ($class->hasProperty($name)) { return $class->getProperty($name); } # If not this class then check its parents $parent = $class; while (true) { $parent = $parent->getParentClass(); if (!$parent) { break; } if ($parent->hasProperty($name)) { return $parent->getProperty($name); } } # We didn't find the property, but use this to give a sensible error return $class->getProperty($name); }
[ "private", "function", "getProperty", "(", "string", "$", "name", ")", ":", "\\", "ReflectionProperty", "{", "$", "class", "=", "$", "this", "->", "getReflection", "(", ")", ";", "# See if the literal class has this property", "if", "(", "$", "class", "->", "h...
Go hunting for a property up the class hierarchy. @param string $name The name of the property we're looking for @return \ReflectionProperty
[ "Go", "hunting", "for", "a", "property", "up", "the", "class", "hierarchy", "." ]
40388a680eac9d4558e56df990c177555ba59ed8
https://github.com/duncan3dc/object-intruder/blob/40388a680eac9d4558e56df990c177555ba59ed8/src/Intruder.php#L62-L86
train
duncan3dc/object-intruder
src/Intruder.php
Intruder._call
public function _call(string $name, &...$arguments) { $method = $this->getReflection()->getMethod($name); $method->setAccessible(true); return $method->invokeArgs($this->getInstance(), $arguments); }
php
public function _call(string $name, &...$arguments) { $method = $this->getReflection()->getMethod($name); $method->setAccessible(true); return $method->invokeArgs($this->getInstance(), $arguments); }
[ "public", "function", "_call", "(", "string", "$", "name", ",", "&", "...", "$", "arguments", ")", "{", "$", "method", "=", "$", "this", "->", "getReflection", "(", ")", "->", "getMethod", "(", "$", "name", ")", ";", "$", "method", "->", "setAccessib...
Allow methods with references to be called. @param string $name The name of the method to call @param array<int, mixed> ...$arguments Any parameters the method accepts @return mixed
[ "Allow", "methods", "with", "references", "to", "be", "called", "." ]
40388a680eac9d4558e56df990c177555ba59ed8
https://github.com/duncan3dc/object-intruder/blob/40388a680eac9d4558e56df990c177555ba59ed8/src/Intruder.php#L142-L148
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Entity/Message.php
Message.hasTranslation
public function hasTranslation($locale) { foreach ($this->translations as $translation) { if ($locale == $translation->locale) { return $translation; } } return false; }
php
public function hasTranslation($locale) { foreach ($this->translations as $translation) { if ($locale == $translation->locale) { return $translation; } } return false; }
[ "public", "function", "hasTranslation", "(", "$", "locale", ")", "{", "foreach", "(", "$", "this", "->", "translations", "as", "$", "translation", ")", "{", "if", "(", "$", "locale", "==", "$", "translation", "->", "locale", ")", "{", "return", "$", "t...
Checks if the translation for the specified locale exists. @param string $locale @return bool
[ "Checks", "if", "the", "translation", "for", "the", "specified", "locale", "exists", "." ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Entity/Message.php#L100-L108
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Entity/Message.php
Message.addMissingTranslations
public function addMissingTranslations($locales) { foreach ($locales as $localeCode) { if (!$this->hasTranslation($localeCode)) { $this->addTranslations(new MessageTranslation($localeCode, $this->getMessage())); } } foreach ($this->translations as $translation) { $translation->setMessage($this); } }
php
public function addMissingTranslations($locales) { foreach ($locales as $localeCode) { if (!$this->hasTranslation($localeCode)) { $this->addTranslations(new MessageTranslation($localeCode, $this->getMessage())); } } foreach ($this->translations as $translation) { $translation->setMessage($this); } }
[ "public", "function", "addMissingTranslations", "(", "$", "locales", ")", "{", "foreach", "(", "$", "locales", "as", "$", "localeCode", ")", "{", "if", "(", "!", "$", "this", "->", "hasTranslation", "(", "$", "localeCode", ")", ")", "{", "$", "this", "...
Adds missing translations @param array $locales @return void
[ "Adds", "missing", "translations" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Entity/Message.php#L117-L128
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Subscriber/FlushCatalogueCacheSubscriber.php
FlushCatalogueCacheSubscriber.onFlush
public function onFlush($args) { if (!$this->isDirty) { /** @var $em \Doctrine\ORM\EntityManager */ $em = $args->getEntityManager(); /** @var $uow \Doctrine\ORM\UnitOfWork */ $uow = $em->getUnitOfWork(); $array = array( $uow->getScheduledEntityUpdates(), $uow->getScheduledEntityDeletions(), $uow->getScheduledEntityInsertions(), $uow->getScheduledCollectionUpdates(), $uow->getScheduledCollectionDeletions(), $uow->getScheduledCollectionDeletions(), $uow->getScheduledCollectionUpdates() ); foreach ($array as $obj) { foreach ($obj as $element) { if ($element instanceof Entity\Message || $element instanceof Entity\MessageTranslation ) { $this->isDirty = true; break 2; } } } } $this->flushCache(); }
php
public function onFlush($args) { if (!$this->isDirty) { /** @var $em \Doctrine\ORM\EntityManager */ $em = $args->getEntityManager(); /** @var $uow \Doctrine\ORM\UnitOfWork */ $uow = $em->getUnitOfWork(); $array = array( $uow->getScheduledEntityUpdates(), $uow->getScheduledEntityDeletions(), $uow->getScheduledEntityInsertions(), $uow->getScheduledCollectionUpdates(), $uow->getScheduledCollectionDeletions(), $uow->getScheduledCollectionDeletions(), $uow->getScheduledCollectionUpdates() ); foreach ($array as $obj) { foreach ($obj as $element) { if ($element instanceof Entity\Message || $element instanceof Entity\MessageTranslation ) { $this->isDirty = true; break 2; } } } } $this->flushCache(); }
[ "public", "function", "onFlush", "(", "$", "args", ")", "{", "if", "(", "!", "$", "this", "->", "isDirty", ")", "{", "/** @var $em \\Doctrine\\ORM\\EntityManager */", "$", "em", "=", "$", "args", "->", "getEntityManager", "(", ")", ";", "/** @var $uow \\Doctri...
Listens to the flush event and checks if any of the configured entities was inserted, updated or deleted. If so, invokes the helper to @param mixed $args @return void
[ "Listens", "to", "the", "flush", "event", "and", "checks", "if", "any", "of", "the", "configured", "entities", "was", "inserted", "updated", "or", "deleted", ".", "If", "so", "invokes", "the", "helper", "to" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Subscriber/FlushCatalogueCacheSubscriber.php#L54-L86
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Manager/MessageManager.php
MessageManager.getOverwriteValue
protected function getOverwriteValue($state, $overwrites) { if (is_array($overwrites) && array_key_exists($state, $overwrites)) { return $overwrites[$state]; } return false; }
php
protected function getOverwriteValue($state, $overwrites) { if (is_array($overwrites) && array_key_exists($state, $overwrites)) { return $overwrites[$state]; } return false; }
[ "protected", "function", "getOverwriteValue", "(", "$", "state", ",", "$", "overwrites", ")", "{", "if", "(", "is_array", "(", "$", "overwrites", ")", "&&", "array_key_exists", "(", "$", "state", ",", "$", "overwrites", ")", ")", "{", "return", "$", "ove...
Helper function for more readable check @param string $state @param mixed $overwrites @return bool
[ "Helper", "function", "for", "more", "readable", "check" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Manager/MessageManager.php#L245-L251
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Manager/MessageManager.php
MessageManager.check
public function check(TranslatorInterface $translator, $kernelRoot, $fix = false) { $issues = array(); /** @var Message[] $messages */ $messages = $this->getRepository()->findAll(); foreach ($messages as $message) { foreach ($message->getTranslations() as $translation) { $translator->setLocale($translation->locale); $translated = $translator->trans($message->message, array(), $message->domain); $translationFile = 'Resources/translations/' . $message->domain . '.' . $translation->locale . '.db'; if (!is_file($kernelRoot . '/' . $translationFile)) { if ($fix === true) { touch($kernelRoot . '/' . $translationFile); $msg = 'Translation file app/' . $translationFile . ' created'; } else { $msg = 'Translation file app/' . $translationFile . ' is missing. This probably causes some messages not to load'; } if (!in_array($msg, $issues)) { $issues[]= $msg; } } if ($translated != $translation->translation) { $issues[]= sprintf( "Message '%s' from domain '%s' in locale '%s' translates as '%s', but '%s' expected", $message->message, $message->domain, $translation->locale, $translated, $translation->translation ); } } } return $issues; }
php
public function check(TranslatorInterface $translator, $kernelRoot, $fix = false) { $issues = array(); /** @var Message[] $messages */ $messages = $this->getRepository()->findAll(); foreach ($messages as $message) { foreach ($message->getTranslations() as $translation) { $translator->setLocale($translation->locale); $translated = $translator->trans($message->message, array(), $message->domain); $translationFile = 'Resources/translations/' . $message->domain . '.' . $translation->locale . '.db'; if (!is_file($kernelRoot . '/' . $translationFile)) { if ($fix === true) { touch($kernelRoot . '/' . $translationFile); $msg = 'Translation file app/' . $translationFile . ' created'; } else { $msg = 'Translation file app/' . $translationFile . ' is missing. This probably causes some messages not to load'; } if (!in_array($msg, $issues)) { $issues[]= $msg; } } if ($translated != $translation->translation) { $issues[]= sprintf( "Message '%s' from domain '%s' in locale '%s' translates as '%s', but '%s' expected", $message->message, $message->domain, $translation->locale, $translated, $translation->translation ); } } } return $issues; }
[ "public", "function", "check", "(", "TranslatorInterface", "$", "translator", ",", "$", "kernelRoot", ",", "$", "fix", "=", "false", ")", "{", "$", "issues", "=", "array", "(", ")", ";", "/** @var Message[] $messages */", "$", "messages", "=", "$", "this", ...
Does some sanity checks @param TranslatorInterface $translator @param string $kernelRoot @param bool $fix @return array
[ "Does", "some", "sanity", "checks" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Manager/MessageManager.php#L272-L308
train
DarvinStudio/darvin-utils
Composer/ScriptHandler.php
ScriptHandler.exportAssetsVersion
public static function exportAssetsVersion() { $process = new Process('git log -n 1'); if (0 !== $process->run()) { return; } $output = $process->getOutput(); if (empty($output)) { return; } putenv(self::ENV_ASSETS_VERSION.'='.md5($output)); }
php
public static function exportAssetsVersion() { $process = new Process('git log -n 1'); if (0 !== $process->run()) { return; } $output = $process->getOutput(); if (empty($output)) { return; } putenv(self::ENV_ASSETS_VERSION.'='.md5($output)); }
[ "public", "static", "function", "exportAssetsVersion", "(", ")", "{", "$", "process", "=", "new", "Process", "(", "'git log -n 1'", ")", ";", "if", "(", "0", "!==", "$", "process", "->", "run", "(", ")", ")", "{", "return", ";", "}", "$", "output", "...
Exports assets version environment variable
[ "Exports", "assets", "version", "environment", "variable" ]
9bdf101cd2fbd5d5f58300a4155bbd4c105ed649
https://github.com/DarvinStudio/darvin-utils/blob/9bdf101cd2fbd5d5f58300a4155bbd4c105ed649/Composer/ScriptHandler.php#L25-L40
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Entity/MessageRepository.php
MessageRepository.getTranslations
public function getTranslations($locale, $domain) { $conn = $this->getEntityManager()->getConnection(); $stmt = $conn->executeQuery( 'SELECT m.message, t.translation FROM message m JOIN message_translation t ON (t.message_id = m.id AND t.locale = ? ) WHERE m.domain = ?', [$locale, $domain] ); while ($row = $stmt->fetch()) { yield $row['message'] => $row['translation']; } }
php
public function getTranslations($locale, $domain) { $conn = $this->getEntityManager()->getConnection(); $stmt = $conn->executeQuery( 'SELECT m.message, t.translation FROM message m JOIN message_translation t ON (t.message_id = m.id AND t.locale = ? ) WHERE m.domain = ?', [$locale, $domain] ); while ($row = $stmt->fetch()) { yield $row['message'] => $row['translation']; } }
[ "public", "function", "getTranslations", "(", "$", "locale", ",", "$", "domain", ")", "{", "$", "conn", "=", "$", "this", "->", "getEntityManager", "(", ")", "->", "getConnection", "(", ")", ";", "$", "stmt", "=", "$", "conn", "->", "executeQuery", "("...
Returns all translations for the specified domain @param string $locale @param string $domain @return \Generator
[ "Returns", "all", "translations", "for", "the", "specified", "domain" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Entity/MessageRepository.php#L24-L34
train
zicht/messages-bundle
src/Zicht/Bundle/MessagesBundle/Entity/MessageRepository.php
MessageRepository.getDomains
public function getDomains() { $q = $this ->createQueryBuilder('m') ->select('m.domain') ->distinct() ->orderBy('m.domain'); $ret = array(); foreach ($q->getQuery()->execute() as $result) { $ret[$result['domain']] = $result['domain']; } return $ret; }
php
public function getDomains() { $q = $this ->createQueryBuilder('m') ->select('m.domain') ->distinct() ->orderBy('m.domain'); $ret = array(); foreach ($q->getQuery()->execute() as $result) { $ret[$result['domain']] = $result['domain']; } return $ret; }
[ "public", "function", "getDomains", "(", ")", "{", "$", "q", "=", "$", "this", "->", "createQueryBuilder", "(", "'m'", ")", "->", "select", "(", "'m.domain'", ")", "->", "distinct", "(", ")", "->", "orderBy", "(", "'m.domain'", ")", ";", "$", "ret", ...
Returns all domains that are defined in the database @return array
[ "Returns", "all", "domains", "that", "are", "defined", "in", "the", "database" ]
779797b5bd263e0619bba88ec29ef77ec49be52d
https://github.com/zicht/messages-bundle/blob/779797b5bd263e0619bba88ec29ef77ec49be52d/src/Zicht/Bundle/MessagesBundle/Entity/MessageRepository.php#L41-L54
train
starweb/starlit-utils
src/Arr.php
Arr.anyIn
public static function anyIn($anyValue, array $array): bool { if (is_array($anyValue)) { return (bool) array_intersect($anyValue, $array); } return in_array($anyValue, $array); }
php
public static function anyIn($anyValue, array $array): bool { if (is_array($anyValue)) { return (bool) array_intersect($anyValue, $array); } return in_array($anyValue, $array); }
[ "public", "static", "function", "anyIn", "(", "$", "anyValue", ",", "array", "$", "array", ")", ":", "bool", "{", "if", "(", "is_array", "(", "$", "anyValue", ")", ")", "{", "return", "(", "bool", ")", "array_intersect", "(", "$", "anyValue", ",", "$...
If any of the provided values is in an array. This is a convenient function for constructs like in_array('val1', $a) || in_array('val2, $a) etc. @param array|string $anyValue Array of needles (will try any for a match) @param array $array Haystack array @return bool
[ "If", "any", "of", "the", "provided", "values", "is", "in", "an", "array", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Arr.php#L22-L29
train
starweb/starlit-utils
src/Arr.php
Arr.allIn
public static function allIn($allValues, array $array): bool { if (is_array($allValues)) { if (empty($allValues)) { return false; } foreach ($allValues as $value) { if (!in_array($value, $array)) { return false; } } // A match was found for all values if we got here return true; } return in_array($allValues, $array); }
php
public static function allIn($allValues, array $array): bool { if (is_array($allValues)) { if (empty($allValues)) { return false; } foreach ($allValues as $value) { if (!in_array($value, $array)) { return false; } } // A match was found for all values if we got here return true; } return in_array($allValues, $array); }
[ "public", "static", "function", "allIn", "(", "$", "allValues", ",", "array", "$", "array", ")", ":", "bool", "{", "if", "(", "is_array", "(", "$", "allValues", ")", ")", "{", "if", "(", "empty", "(", "$", "allValues", ")", ")", "{", "return", "fal...
If all of the provided values is in an array. This is a convenient function for constructs like in_array('val1', $a) && in_array('val2, $a) etc. @param array|mixed $allValues Array of needles (will try all for a match) @param array $array Haystack array @return bool
[ "If", "all", "of", "the", "provided", "values", "is", "in", "an", "array", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Arr.php#L40-L58
train
starweb/starlit-utils
src/Arr.php
Arr.objectsMethodValues
public static function objectsMethodValues(array $objectArray, string $methodName): array { $methodValues = []; foreach ($objectArray as $object) { $methodValues[] = $object->$methodName(); } return $methodValues; }
php
public static function objectsMethodValues(array $objectArray, string $methodName): array { $methodValues = []; foreach ($objectArray as $object) { $methodValues[] = $object->$methodName(); } return $methodValues; }
[ "public", "static", "function", "objectsMethodValues", "(", "array", "$", "objectArray", ",", "string", "$", "methodName", ")", ":", "array", "{", "$", "methodValues", "=", "[", "]", ";", "foreach", "(", "$", "objectArray", "as", "$", "object", ")", "{", ...
Collect values from method calls from an array of objects. @param array $objectArray @param string $methodName @return array
[ "Collect", "values", "from", "method", "calls", "from", "an", "array", "of", "objects", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Arr.php#L131-L140
train
starweb/starlit-utils
src/Arr.php
Arr.valuesWithType
public static function valuesWithType(array $inputArray, string $type): array { $newArray = []; foreach ($inputArray as $key => $value) { if (is_scalar($value)) { $newValue = $value; settype($newValue, $type); $newArray[$key] = $newValue; } } return $newArray; }
php
public static function valuesWithType(array $inputArray, string $type): array { $newArray = []; foreach ($inputArray as $key => $value) { if (is_scalar($value)) { $newValue = $value; settype($newValue, $type); $newArray[$key] = $newValue; } } return $newArray; }
[ "public", "static", "function", "valuesWithType", "(", "array", "$", "inputArray", ",", "string", "$", "type", ")", ":", "array", "{", "$", "newArray", "=", "[", "]", ";", "foreach", "(", "$", "inputArray", "as", "$", "key", "=>", "$", "value", ")", ...
Get a new array with all scalar values cast to type. @param array $inputArray @param string $type @return array
[ "Get", "a", "new", "array", "with", "all", "scalar", "values", "cast", "to", "type", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Arr.php#L149-L161
train
starweb/starlit-utils
src/Arr.php
Arr.replaceExisting
public static function replaceExisting(array $array1, array $array2, bool $recursive = false): array { foreach ($array1 as $key => $value) { if (array_key_exists($key, $array2)) { $value2 = $array2[$key]; if ($recursive && is_array($value)) { $value2 = self::replaceExisting($value, $value2, $recursive); } $array1[$key] = $value2; } } return $array1; }
php
public static function replaceExisting(array $array1, array $array2, bool $recursive = false): array { foreach ($array1 as $key => $value) { if (array_key_exists($key, $array2)) { $value2 = $array2[$key]; if ($recursive && is_array($value)) { $value2 = self::replaceExisting($value, $value2, $recursive); } $array1[$key] = $value2; } } return $array1; }
[ "public", "static", "function", "replaceExisting", "(", "array", "$", "array1", ",", "array", "$", "array2", ",", "bool", "$", "recursive", "=", "false", ")", ":", "array", "{", "foreach", "(", "$", "array1", "as", "$", "key", "=>", "$", "value", ")", ...
Replaces values in array1 with values from array2 comparing keys and discarding keys that doesn't exist in array1. @param array $array1 @param array $array2 @param bool $recursive @return array
[ "Replaces", "values", "in", "array1", "with", "values", "from", "array2", "comparing", "keys", "and", "discarding", "keys", "that", "doesn", "t", "exist", "in", "array1", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Arr.php#L172-L185
train
starweb/starlit-utils
src/Arr.php
Arr.sortByArray
public static function sortByArray(array $sortArray, array $mapArray): array { $sortedArray = []; foreach ((array) $mapArray as $id) { if (array_key_exists($id, $sortArray)) { $sortedArray[] = $sortArray[$id]; } } return $sortedArray; }
php
public static function sortByArray(array $sortArray, array $mapArray): array { $sortedArray = []; foreach ((array) $mapArray as $id) { if (array_key_exists($id, $sortArray)) { $sortedArray[] = $sortArray[$id]; } } return $sortedArray; }
[ "public", "static", "function", "sortByArray", "(", "array", "$", "sortArray", ",", "array", "$", "mapArray", ")", ":", "array", "{", "$", "sortedArray", "=", "[", "]", ";", "foreach", "(", "(", "array", ")", "$", "mapArray", "as", "$", "id", ")", "{...
Sort by array. @param array $sortArray @param array $mapArray @return array
[ "Sort", "by", "array", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Arr.php#L194-L204
train
gocom/rah_cache
src/Rah/Cache.php
Rah_Cache.controller
public function controller($atts) { extract(lAtts(array( 'ignore' => 0, ), $atts)); if ($ignore) { $this->request->file = null; } }
php
public function controller($atts) { extract(lAtts(array( 'ignore' => 0, ), $atts)); if ($ignore) { $this->request->file = null; } }
[ "public", "function", "controller", "(", "$", "atts", ")", "{", "extract", "(", "lAtts", "(", "array", "(", "'ignore'", "=>", "0", ",", ")", ",", "$", "atts", ")", ")", ";", "if", "(", "$", "ignore", ")", "{", "$", "this", "->", "request", "->", ...
A tag to control caching on a page basis. @param array $atts @return string
[ "A", "tag", "to", "control", "caching", "on", "a", "page", "basis", "." ]
a7b98a265d57d76339b7f9f4beacdccaa2be33e8
https://github.com/gocom/rah_cache/blob/a7b98a265d57d76339b7f9f4beacdccaa2be33e8/src/Rah/Cache.php#L72-L81
train
gocom/rah_cache
src/Rah/Cache.php
Rah_Cache.getHeaders
protected function getHeaders() { if (function_exists('headers_list') && $headers = headers_list()) { foreach ((array) $headers as $header) { if (strpos($header, ':')) { $header = explode(':', strtolower($header), 2); $this->headers[trim($header[0])] = trim($header[1]); } } } }
php
protected function getHeaders() { if (function_exists('headers_list') && $headers = headers_list()) { foreach ((array) $headers as $header) { if (strpos($header, ':')) { $header = explode(':', strtolower($header), 2); $this->headers[trim($header[0])] = trim($header[1]); } } } }
[ "protected", "function", "getHeaders", "(", ")", "{", "if", "(", "function_exists", "(", "'headers_list'", ")", "&&", "$", "headers", "=", "headers_list", "(", ")", ")", "{", "foreach", "(", "(", "array", ")", "$", "headers", "as", "$", "header", ")", ...
Gets sent response headers.
[ "Gets", "sent", "response", "headers", "." ]
a7b98a265d57d76339b7f9f4beacdccaa2be33e8
https://github.com/gocom/rah_cache/blob/a7b98a265d57d76339b7f9f4beacdccaa2be33e8/src/Rah/Cache.php#L87-L97
train
gocom/rah_cache
src/Rah/Cache.php
Rah_Cache.store
public function store() { if (empty($this->request->file) || get_pref('production_status') != 'live') { return; } foreach ($this->config->skipPaths as $path) { if (strpos($this->request->uri, $path) === 0) { return; } } $this->getHeaders(); if (isset($this->headers['content-type']) && strpos($this->headers['content-type'], 'text/html') === false ) { return; } $page = ob_get_contents(); if (($r = callback_event('rah_cache.store', '', 0, array( 'contents' => $page, 'headers' => $this->headers, ))) !== '') { $page = $r; } if (!$page) { return; } file_put_contents($this->request->file, $page); $size = strlen($page); $crc = crc32($page); $data = gzcompress($page, 6); $data = substr($data, 0, strlen($data)-4); $data = "\x1f\x8b\x08\x00\x00\x00\x00\x00".$data; $data .= pack('V', $crc); $data .= pack('V', $size); file_put_contents($this->request->file.'.gz', $data); callback_event('rah_cache.created'); }
php
public function store() { if (empty($this->request->file) || get_pref('production_status') != 'live') { return; } foreach ($this->config->skipPaths as $path) { if (strpos($this->request->uri, $path) === 0) { return; } } $this->getHeaders(); if (isset($this->headers['content-type']) && strpos($this->headers['content-type'], 'text/html') === false ) { return; } $page = ob_get_contents(); if (($r = callback_event('rah_cache.store', '', 0, array( 'contents' => $page, 'headers' => $this->headers, ))) !== '') { $page = $r; } if (!$page) { return; } file_put_contents($this->request->file, $page); $size = strlen($page); $crc = crc32($page); $data = gzcompress($page, 6); $data = substr($data, 0, strlen($data)-4); $data = "\x1f\x8b\x08\x00\x00\x00\x00\x00".$data; $data .= pack('V', $crc); $data .= pack('V', $size); file_put_contents($this->request->file.'.gz', $data); callback_event('rah_cache.created'); }
[ "public", "function", "store", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "request", "->", "file", ")", "||", "get_pref", "(", "'production_status'", ")", "!=", "'live'", ")", "{", "return", ";", "}", "foreach", "(", "$", "this", "->"...
Writes the page to the cache directory.
[ "Writes", "the", "page", "to", "the", "cache", "directory", "." ]
a7b98a265d57d76339b7f9f4beacdccaa2be33e8
https://github.com/gocom/rah_cache/blob/a7b98a265d57d76339b7f9f4beacdccaa2be33e8/src/Rah/Cache.php#L102-L147
train
gocom/rah_cache
src/Rah/Cache.php
Rah_Cache.updateLastmod
public function updateLastmod() { if ($this->config->directory) { $lastmod = $this->config->directory . '/_lastmod.rah'; if (!is_file($lastmod) || file_get_contents($lastmod) !== get_pref('lastmod', false, true)) { file_put_contents($lastmod, get_pref('lastmod', '', true)); } } }
php
public function updateLastmod() { if ($this->config->directory) { $lastmod = $this->config->directory . '/_lastmod.rah'; if (!is_file($lastmod) || file_get_contents($lastmod) !== get_pref('lastmod', false, true)) { file_put_contents($lastmod, get_pref('lastmod', '', true)); } } }
[ "public", "function", "updateLastmod", "(", ")", "{", "if", "(", "$", "this", "->", "config", "->", "directory", ")", "{", "$", "lastmod", "=", "$", "this", "->", "config", "->", "directory", ".", "'/_lastmod.rah'", ";", "if", "(", "!", "is_file", "(",...
Update last modification timestamp.
[ "Update", "last", "modification", "timestamp", "." ]
a7b98a265d57d76339b7f9f4beacdccaa2be33e8
https://github.com/gocom/rah_cache/blob/a7b98a265d57d76339b7f9f4beacdccaa2be33e8/src/Rah/Cache.php#L152-L161
train
gocom/rah_cache
src/Rah/Cache/Handler.php
Rah_Cache_Handler.encoding
public function encoding() { if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) || headers_sent()) { return false; } $accept_encoding = $_SERVER['HTTP_ACCEPT_ENCODING']; if (strpos($accept_encoding, 'x-gzip') !== false) { return 'x-gzip'; } if (strpos($accept_encoding, 'gzip') !== false) { return 'gzip'; } return false; }
php
public function encoding() { if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) || headers_sent()) { return false; } $accept_encoding = $_SERVER['HTTP_ACCEPT_ENCODING']; if (strpos($accept_encoding, 'x-gzip') !== false) { return 'x-gzip'; } if (strpos($accept_encoding, 'gzip') !== false) { return 'gzip'; } return false; }
[ "public", "function", "encoding", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "_SERVER", "[", "'HTTP_ACCEPT_ENCODING'", "]", ")", "||", "headers_sent", "(", ")", ")", "{", "return", "false", ";", "}", "$", "accept_encoding", "=", "$", "_SERVER", ...
Check accepted encoding headers. @return bool
[ "Check", "accepted", "encoding", "headers", "." ]
a7b98a265d57d76339b7f9f4beacdccaa2be33e8
https://github.com/gocom/rah_cache/blob/a7b98a265d57d76339b7f9f4beacdccaa2be33e8/src/Rah/Cache/Handler.php#L119-L136
train
starweb/starlit-utils
src/Str.php
Str.random
public static function random(int $charCount, string $characters = 'abcdefghijklmnopqrstuvqxyz0123456789'): string { $randomString = ''; for ($i = 0; $i < $charCount; $i++) { $pos = mt_rand(0, strlen($characters) - 1); $randomString .= $characters[$pos]; } return $randomString; }
php
public static function random(int $charCount, string $characters = 'abcdefghijklmnopqrstuvqxyz0123456789'): string { $randomString = ''; for ($i = 0; $i < $charCount; $i++) { $pos = mt_rand(0, strlen($characters) - 1); $randomString .= $characters[$pos]; } return $randomString; }
[ "public", "static", "function", "random", "(", "int", "$", "charCount", ",", "string", "$", "characters", "=", "'abcdefghijklmnopqrstuvqxyz0123456789'", ")", ":", "string", "{", "$", "randomString", "=", "''", ";", "for", "(", "$", "i", "=", "0", ";", "$",...
Get a random string generated from provided values. @param int $charCount @param string $characters @return string
[ "Get", "a", "random", "string", "generated", "from", "provided", "values", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Str.php#L62-L71
train
starweb/starlit-utils
src/Str.php
Str.truncate
public static function truncate(string $string, int $maxLength, string $indicator = '...'): string { if (mb_strlen($string) > $maxLength) { $string = mb_substr($string, 0, $maxLength - mb_strlen($indicator)) . $indicator; } return $string; }
php
public static function truncate(string $string, int $maxLength, string $indicator = '...'): string { if (mb_strlen($string) > $maxLength) { $string = mb_substr($string, 0, $maxLength - mb_strlen($indicator)) . $indicator; } return $string; }
[ "public", "static", "function", "truncate", "(", "string", "$", "string", ",", "int", "$", "maxLength", ",", "string", "$", "indicator", "=", "'...'", ")", ":", "string", "{", "if", "(", "mb_strlen", "(", "$", "string", ")", ">", "$", "maxLength", ")",...
Get shortened string. @param string $string @param int $maxLength @param string $indicator @return string
[ "Get", "shortened", "string", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Str.php#L81-L88
train
starweb/starlit-utils
src/Str.php
Str.endsWith
public static function endsWith(string $string, string $search): bool { return (substr($string, -strlen($search)) === $search); }
php
public static function endsWith(string $string, string $search): bool { return (substr($string, -strlen($search)) === $search); }
[ "public", "static", "function", "endsWith", "(", "string", "$", "string", ",", "string", "$", "search", ")", ":", "bool", "{", "return", "(", "substr", "(", "$", "string", ",", "-", "strlen", "(", "$", "search", ")", ")", "===", "$", "search", ")", ...
Check if a string ends with another substring. @param string $string @param string $search @return bool
[ "Check", "if", "a", "string", "ends", "with", "another", "substring", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Str.php#L109-L112
train
starweb/starlit-utils
src/Str.php
Str.stripLeft
public static function stripLeft(string $string, string $strip): string { if (self::startsWith($string, $strip)) { return substr($string, strlen($strip)); } return $string; }
php
public static function stripLeft(string $string, string $strip): string { if (self::startsWith($string, $strip)) { return substr($string, strlen($strip)); } return $string; }
[ "public", "static", "function", "stripLeft", "(", "string", "$", "string", ",", "string", "$", "strip", ")", ":", "string", "{", "if", "(", "self", "::", "startsWith", "(", "$", "string", ",", "$", "strip", ")", ")", "{", "return", "substr", "(", "$"...
Remove left part of string and return the new string. @param string $string @param string $strip @return string
[ "Remove", "left", "part", "of", "string", "and", "return", "the", "new", "string", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Str.php#L121-L128
train
starweb/starlit-utils
src/Str.php
Str.stripRight
public static function stripRight(string $string, string $strip): string { if (self::endsWith($string, $strip)) { return substr($string, 0, -strlen($strip)); } return $string; }
php
public static function stripRight(string $string, string $strip): string { if (self::endsWith($string, $strip)) { return substr($string, 0, -strlen($strip)); } return $string; }
[ "public", "static", "function", "stripRight", "(", "string", "$", "string", ",", "string", "$", "strip", ")", ":", "string", "{", "if", "(", "self", "::", "endsWith", "(", "$", "string", ",", "$", "strip", ")", ")", "{", "return", "substr", "(", "$",...
Remove right part of string and return the new string. @param string $string @param string $strip @return string
[ "Remove", "right", "part", "of", "string", "and", "return", "the", "new", "string", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Str.php#L137-L144
train
starweb/starlit-utils
src/Str.php
Str.toNumber
public static function toNumber(string $string, bool $allowDecimal = false, bool $allowNegative = false): string { $string = trim($string); $decimalPart = ''; if (($firstPos = strpos($string, '.')) !== false) { $integerPart = substr($string, 0, $firstPos); if ($allowDecimal) { $rawDecimalPart = substr($string, $firstPos); $filteredDecimalPart = rtrim(preg_replace('/[^0-9]/', '', $rawDecimalPart), '0'); if (!empty($filteredDecimalPart)) { $decimalPart = '.' . $filteredDecimalPart; } } } else { $integerPart = $string; } $integerPart = ltrim(preg_replace('/[^0-9]/', '', $integerPart), '0'); $integerPart = $integerPart ?: '0'; $minusSign = ''; if (strpos($string, '-') === 0) { if (!$allowNegative) { return '0'; } elseif (!($integerPart === '0' && empty($decimalPart))) { $minusSign = '-'; } } $number = $minusSign . $integerPart . $decimalPart; return $number; }
php
public static function toNumber(string $string, bool $allowDecimal = false, bool $allowNegative = false): string { $string = trim($string); $decimalPart = ''; if (($firstPos = strpos($string, '.')) !== false) { $integerPart = substr($string, 0, $firstPos); if ($allowDecimal) { $rawDecimalPart = substr($string, $firstPos); $filteredDecimalPart = rtrim(preg_replace('/[^0-9]/', '', $rawDecimalPart), '0'); if (!empty($filteredDecimalPart)) { $decimalPart = '.' . $filteredDecimalPart; } } } else { $integerPart = $string; } $integerPart = ltrim(preg_replace('/[^0-9]/', '', $integerPart), '0'); $integerPart = $integerPart ?: '0'; $minusSign = ''; if (strpos($string, '-') === 0) { if (!$allowNegative) { return '0'; } elseif (!($integerPart === '0' && empty($decimalPart))) { $minusSign = '-'; } } $number = $minusSign . $integerPart . $decimalPart; return $number; }
[ "public", "static", "function", "toNumber", "(", "string", "$", "string", ",", "bool", "$", "allowDecimal", "=", "false", ",", "bool", "$", "allowNegative", "=", "false", ")", ":", "string", "{", "$", "string", "=", "trim", "(", "$", "string", ")", ";"...
Filter out all non numeric characters and return a clean numeric string. @param string $string @param bool $allowDecimal @param bool $allowNegative @return string
[ "Filter", "out", "all", "non", "numeric", "characters", "and", "return", "a", "clean", "numeric", "string", "." ]
01e9220e8821d5b454707bfd39d24c12c08979f2
https://github.com/starweb/starlit-utils/blob/01e9220e8821d5b454707bfd39d24c12c08979f2/src/Str.php#L190-L223
train
PhpGt/Build
src/Build.php
Build.check
public function check(array &$errors = null):int { $count = 0; foreach($this->taskList as $pathMatch => $task) { $absolutePathMatch = implode(DIRECTORY_SEPARATOR, [ getcwd(), $pathMatch, ]); $fileList = Glob::glob($absolutePathMatch); if(!empty($fileList)) { $task->check($errors); } $count ++; } return $count; }
php
public function check(array &$errors = null):int { $count = 0; foreach($this->taskList as $pathMatch => $task) { $absolutePathMatch = implode(DIRECTORY_SEPARATOR, [ getcwd(), $pathMatch, ]); $fileList = Glob::glob($absolutePathMatch); if(!empty($fileList)) { $task->check($errors); } $count ++; } return $count; }
[ "public", "function", "check", "(", "array", "&", "$", "errors", "=", "null", ")", ":", "int", "{", "$", "count", "=", "0", ";", "foreach", "(", "$", "this", "->", "taskList", "as", "$", "pathMatch", "=>", "$", "task", ")", "{", "$", "absolutePathM...
For each task, ensure all requirements are met.
[ "For", "each", "task", "ensure", "all", "requirements", "are", "met", "." ]
9ed467dd99c85c7017afe3ee7419f18290d73bb4
https://github.com/PhpGt/Build/blob/9ed467dd99c85c7017afe3ee7419f18290d73bb4/src/Build.php#L22-L39
train
PhpGt/Build
src/Build.php
Build.build
public function build(array &$errors = null):array { $updatedTasks = []; foreach($this->taskList as $pathMatch => $task) { if($task->build($errors)) { $updatedTasks []= $task; } } return $updatedTasks; }
php
public function build(array &$errors = null):array { $updatedTasks = []; foreach($this->taskList as $pathMatch => $task) { if($task->build($errors)) { $updatedTasks []= $task; } } return $updatedTasks; }
[ "public", "function", "build", "(", "array", "&", "$", "errors", "=", "null", ")", ":", "array", "{", "$", "updatedTasks", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "taskList", "as", "$", "pathMatch", "=>", "$", "task", ")", "{", "if",...
Executes the commands associated with each build task. @return Task[] List of tasks built (some may not need building due to having no changes).
[ "Executes", "the", "commands", "associated", "with", "each", "build", "task", "." ]
9ed467dd99c85c7017afe3ee7419f18290d73bb4
https://github.com/PhpGt/Build/blob/9ed467dd99c85c7017afe3ee7419f18290d73bb4/src/Build.php#L46-L55
train
heyday/silverstripe-colorpalette
src/fields/GroupedColorPaletteField.php
GroupedColorPaletteField.performReadonlyTransformation
public function performReadonlyTransformation() { // Source and values are DataObject sets. $field = $this->castedCopy(GroupedColorPaletteField_Readonly::class); $field->setSource($this->getSource()); $field->setReadonly(true); return $field; }
php
public function performReadonlyTransformation() { // Source and values are DataObject sets. $field = $this->castedCopy(GroupedColorPaletteField_Readonly::class); $field->setSource($this->getSource()); $field->setReadonly(true); return $field; }
[ "public", "function", "performReadonlyTransformation", "(", ")", "{", "// Source and values are DataObject sets.", "$", "field", "=", "$", "this", "->", "castedCopy", "(", "GroupedColorPaletteField_Readonly", "::", "class", ")", ";", "$", "field", "->", "setSource", "...
Gets a readonly version of the field @return GroupedColorPaletteField_Readonly
[ "Gets", "a", "readonly", "version", "of", "the", "field" ]
1a10ecce6bff9db78e124b310316aab17e368b2f
https://github.com/heyday/silverstripe-colorpalette/blob/1a10ecce6bff9db78e124b310316aab17e368b2f/src/fields/GroupedColorPaletteField.php#L94-L102
train
heyday/silverstripe-colorpalette
src/fields/GroupedColorPaletteField_Readonly.php
GroupedColorPaletteField_Readonly.getSelectedGroup
public function getSelectedGroup() { $source = $this->getSource(); if ($source) { foreach ($source as $groupName => $values) { if (is_array($values)) { if (array_key_exists($this->value, $values)) { return $groupName; } } else { throw new InvalidArgumentException('To use GroupedColorPaletteField you need to pass in an array of array\'s'); } } } }
php
public function getSelectedGroup() { $source = $this->getSource(); if ($source) { foreach ($source as $groupName => $values) { if (is_array($values)) { if (array_key_exists($this->value, $values)) { return $groupName; } } else { throw new InvalidArgumentException('To use GroupedColorPaletteField you need to pass in an array of array\'s'); } } } }
[ "public", "function", "getSelectedGroup", "(", ")", "{", "$", "source", "=", "$", "this", "->", "getSource", "(", ")", ";", "if", "(", "$", "source", ")", "{", "foreach", "(", "$", "source", "as", "$", "groupName", "=>", "$", "values", ")", "{", "i...
Gets the label of the group that the color appears in @return string
[ "Gets", "the", "label", "of", "the", "group", "that", "the", "color", "appears", "in" ]
1a10ecce6bff9db78e124b310316aab17e368b2f
https://github.com/heyday/silverstripe-colorpalette/blob/1a10ecce6bff9db78e124b310316aab17e368b2f/src/fields/GroupedColorPaletteField_Readonly.php#L28-L43
train
appstract/laravel-multisite
src/MultisiteServiceProvider.php
MultisiteServiceProvider.registerComposers
protected function registerComposers() { View::composer( '*', \Appstract\Multisite\Composers\CurrentSiteComposer::class ); View::composer( Config::get('multisite.views.overwriteable'), \Appstract\Multisite\Composers\OverwriteViewComposer::class ); }
php
protected function registerComposers() { View::composer( '*', \Appstract\Multisite\Composers\CurrentSiteComposer::class ); View::composer( Config::get('multisite.views.overwriteable'), \Appstract\Multisite\Composers\OverwriteViewComposer::class ); }
[ "protected", "function", "registerComposers", "(", ")", "{", "View", "::", "composer", "(", "'*'", ",", "\\", "Appstract", "\\", "Multisite", "\\", "Composers", "\\", "CurrentSiteComposer", "::", "class", ")", ";", "View", "::", "composer", "(", "Config", ":...
Register view composers. @return void
[ "Register", "view", "composers", "." ]
a371aae503ae3508bec5c1b9fd196958277b6073
https://github.com/appstract/laravel-multisite/blob/a371aae503ae3508bec5c1b9fd196958277b6073/src/MultisiteServiceProvider.php#L69-L80
train
appstract/laravel-multisite
src/Composers/OverwriteViewComposer.php
OverwriteViewComposer.getNewPath
protected function getNewPath() { return $this->getAbsolutesitesFolder().DIRECTORY_SEPARATOR.$this->currentSite->slug.DIRECTORY_SEPARATOR.$this->currentPath; }
php
protected function getNewPath() { return $this->getAbsolutesitesFolder().DIRECTORY_SEPARATOR.$this->currentSite->slug.DIRECTORY_SEPARATOR.$this->currentPath; }
[ "protected", "function", "getNewPath", "(", ")", "{", "return", "$", "this", "->", "getAbsolutesitesFolder", "(", ")", ".", "DIRECTORY_SEPARATOR", ".", "$", "this", "->", "currentSite", "->", "slug", ".", "DIRECTORY_SEPARATOR", ".", "$", "this", "->", "current...
Get the new path. @return string
[ "Get", "the", "new", "path", "." ]
a371aae503ae3508bec5c1b9fd196958277b6073
https://github.com/appstract/laravel-multisite/blob/a371aae503ae3508bec5c1b9fd196958277b6073/src/Composers/OverwriteViewComposer.php#L61-L64
train
appstract/laravel-multisite
src/Composers/OverwriteViewComposer.php
OverwriteViewComposer.getNewView
protected function getNewView() { if ($this->currentSite) { return str_replace( ['.blade.php'], [''], $this->sitesFolder.'.'.$this->currentSite->slug.'.'.$this->currentPath ); } return $this->currentPath; }
php
protected function getNewView() { if ($this->currentSite) { return str_replace( ['.blade.php'], [''], $this->sitesFolder.'.'.$this->currentSite->slug.'.'.$this->currentPath ); } return $this->currentPath; }
[ "protected", "function", "getNewView", "(", ")", "{", "if", "(", "$", "this", "->", "currentSite", ")", "{", "return", "str_replace", "(", "[", "'.blade.php'", "]", ",", "[", "''", "]", ",", "$", "this", "->", "sitesFolder", ".", "'.'", ".", "$", "th...
Get the new view. @return string
[ "Get", "the", "new", "view", "." ]
a371aae503ae3508bec5c1b9fd196958277b6073
https://github.com/appstract/laravel-multisite/blob/a371aae503ae3508bec5c1b9fd196958277b6073/src/Composers/OverwriteViewComposer.php#L71-L82
train
mike182uk/cart
src/CartItem.php
CartItem.getId
public function getId() { // keys to ignore in the hashing process $ignoreKeys = ['quantity']; // data to use for the hashing process $hashData = $this->data; foreach ($ignoreKeys as $key) { unset($hashData[$key]); } $hash = sha1(serialize($hashData)); return $hash; }
php
public function getId() { // keys to ignore in the hashing process $ignoreKeys = ['quantity']; // data to use for the hashing process $hashData = $this->data; foreach ($ignoreKeys as $key) { unset($hashData[$key]); } $hash = sha1(serialize($hashData)); return $hash; }
[ "public", "function", "getId", "(", ")", "{", "// keys to ignore in the hashing process", "$", "ignoreKeys", "=", "[", "'quantity'", "]", ";", "// data to use for the hashing process", "$", "hashData", "=", "$", "this", "->", "data", ";", "foreach", "(", "$", "ign...
Get the cart item id. @return string
[ "Get", "the", "cart", "item", "id", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/CartItem.php#L45-L59
train
mike182uk/cart
src/CartItem.php
CartItem.set
public function set($key, $value) { switch ($key) { case 'quantity': $this->setCheckTypeInteger($value, $key); break; case 'price': case 'tax': $this->setCheckIsNumeric($value, $key); $value = (float) $value; } $this->data[$key] = $value; return $this->getId(); }
php
public function set($key, $value) { switch ($key) { case 'quantity': $this->setCheckTypeInteger($value, $key); break; case 'price': case 'tax': $this->setCheckIsNumeric($value, $key); $value = (float) $value; } $this->data[$key] = $value; return $this->getId(); }
[ "public", "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "switch", "(", "$", "key", ")", "{", "case", "'quantity'", ":", "$", "this", "->", "setCheckTypeInteger", "(", "$", "value", ",", "$", "key", ")", ";", "break", ";", "case",...
Set a piece of data on the cart item. @param string $key @param mixed $value @return string
[ "Set", "a", "piece", "of", "data", "on", "the", "cart", "item", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/CartItem.php#L86-L102
train
mike182uk/cart
src/Cart.php
Cart.remove
public function remove($itemId) { $items = &$this->items; foreach ($items as $position => $item) { if ($itemId === $item->id) { unset($items[$position]); } } }
php
public function remove($itemId) { $items = &$this->items; foreach ($items as $position => $item) { if ($itemId === $item->id) { unset($items[$position]); } } }
[ "public", "function", "remove", "(", "$", "itemId", ")", "{", "$", "items", "=", "&", "$", "this", "->", "items", ";", "foreach", "(", "$", "items", "as", "$", "position", "=>", "$", "item", ")", "{", "if", "(", "$", "itemId", "===", "$", "item",...
Remove an item from the cart. @param string $itemId
[ "Remove", "an", "item", "from", "the", "cart", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L96-L105
train
mike182uk/cart
src/Cart.php
Cart.update
public function update($itemId, $key, $value) { $item = $this->find($itemId); if (!$item) { throw new \InvalidArgumentException(sprintf('Item [%s] does not exist in cart.', $itemId)); } $item->$key = $value; return $item->id; }
php
public function update($itemId, $key, $value) { $item = $this->find($itemId); if (!$item) { throw new \InvalidArgumentException(sprintf('Item [%s] does not exist in cart.', $itemId)); } $item->$key = $value; return $item->id; }
[ "public", "function", "update", "(", "$", "itemId", ",", "$", "key", ",", "$", "value", ")", "{", "$", "item", "=", "$", "this", "->", "find", "(", "$", "itemId", ")", ";", "if", "(", "!", "$", "item", ")", "{", "throw", "new", "\\", "InvalidAr...
Update an item in the cart. @param string $itemId @param string $key @param mixed $value @return string @throws \InvalidArgumentException
[ "Update", "an", "item", "in", "the", "cart", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L118-L129
train
mike182uk/cart
src/Cart.php
Cart.find
public function find($itemId) { foreach ($this->items as $item) { if ($itemId === $item->id) { return $item; } } return; }
php
public function find($itemId) { foreach ($this->items as $item) { if ($itemId === $item->id) { return $item; } } return; }
[ "public", "function", "find", "(", "$", "itemId", ")", "{", "foreach", "(", "$", "this", "->", "items", "as", "$", "item", ")", "{", "if", "(", "$", "itemId", "===", "$", "item", "->", "id", ")", "{", "return", "$", "item", ";", "}", "}", "retu...
Find an item in the cart. @param string $itemId @return CartItem|null
[ "Find", "an", "item", "in", "the", "cart", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L162-L171
train
mike182uk/cart
src/Cart.php
Cart.total
public function total() { return (float) array_sum( array_map(function (CartItem $item) { return $item->getTotalPrice(); }, $this->items) ); }
php
public function total() { return (float) array_sum( array_map(function (CartItem $item) { return $item->getTotalPrice(); }, $this->items) ); }
[ "public", "function", "total", "(", ")", "{", "return", "(", "float", ")", "array_sum", "(", "array_map", "(", "function", "(", "CartItem", "$", "item", ")", "{", "return", "$", "item", "->", "getTotalPrice", "(", ")", ";", "}", ",", "$", "this", "->...
Get the cart total including tax. @return float
[ "Get", "the", "cart", "total", "including", "tax", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L202-L209
train
mike182uk/cart
src/Cart.php
Cart.totalExcludingTax
public function totalExcludingTax() { return (float) array_sum( array_map(function (CartItem $item) { return $item->getTotalPriceExcludingTax(); }, $this->items) ); }
php
public function totalExcludingTax() { return (float) array_sum( array_map(function (CartItem $item) { return $item->getTotalPriceExcludingTax(); }, $this->items) ); }
[ "public", "function", "totalExcludingTax", "(", ")", "{", "return", "(", "float", ")", "array_sum", "(", "array_map", "(", "function", "(", "CartItem", "$", "item", ")", "{", "return", "$", "item", "->", "getTotalPriceExcludingTax", "(", ")", ";", "}", ","...
Get the cart total excluding tax. @return float
[ "Get", "the", "cart", "total", "excluding", "tax", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L216-L223
train
mike182uk/cart
src/Cart.php
Cart.tax
public function tax() { return (float) array_sum( array_map(function (CartItem $item) { return $item->getTotalTax(); }, $this->items) ); }
php
public function tax() { return (float) array_sum( array_map(function (CartItem $item) { return $item->getTotalTax(); }, $this->items) ); }
[ "public", "function", "tax", "(", ")", "{", "return", "(", "float", ")", "array_sum", "(", "array_map", "(", "function", "(", "CartItem", "$", "item", ")", "{", "return", "$", "item", "->", "getTotalTax", "(", ")", ";", "}", ",", "$", "this", "->", ...
Get the cart tax. @return float
[ "Get", "the", "cart", "tax", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L230-L237
train
mike182uk/cart
src/Cart.php
Cart.save
public function save() { $data = serialize($this->toArray()); $this->store->put($this->id, $data); }
php
public function save() { $data = serialize($this->toArray()); $this->store->put($this->id, $data); }
[ "public", "function", "save", "(", ")", "{", "$", "data", "=", "serialize", "(", "$", "this", "->", "toArray", "(", ")", ")", ";", "$", "this", "->", "store", "->", "put", "(", "$", "this", "->", "id", ",", "$", "data", ")", ";", "}" ]
Save the cart state.
[ "Save", "the", "cart", "state", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L252-L257
train
mike182uk/cart
src/Cart.php
Cart.restore
public function restore() { $state = $this->store->get($this->id); if ($state == '') { return; } $data = @unserialize($state); // suppress unserializable error $this->restoreCheckType($data); $this->restoreCheckContents($data); $this->restoreCheckContentsType($data); $this->id = $data['id']; $this->items = []; foreach ($data['items'] as $itemArr) { $this->items[] = new CartItem($itemArr); } }
php
public function restore() { $state = $this->store->get($this->id); if ($state == '') { return; } $data = @unserialize($state); // suppress unserializable error $this->restoreCheckType($data); $this->restoreCheckContents($data); $this->restoreCheckContentsType($data); $this->id = $data['id']; $this->items = []; foreach ($data['items'] as $itemArr) { $this->items[] = new CartItem($itemArr); } }
[ "public", "function", "restore", "(", ")", "{", "$", "state", "=", "$", "this", "->", "store", "->", "get", "(", "$", "this", "->", "id", ")", ";", "if", "(", "$", "state", "==", "''", ")", "{", "return", ";", "}", "$", "data", "=", "@", "uns...
Restore the cart from its saved state. @throws CartRestoreException
[ "Restore", "the", "cart", "from", "its", "saved", "state", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L264-L284
train
mike182uk/cart
src/Cart.php
Cart.toArray
public function toArray() { return [ 'id' => $this->id, 'items' => array_map(function (CartItem $item) { return $item->toArray(); }, $this->items), ]; }
php
public function toArray() { return [ 'id' => $this->id, 'items' => array_map(function (CartItem $item) { return $item->toArray(); }, $this->items), ]; }
[ "public", "function", "toArray", "(", ")", "{", "return", "[", "'id'", "=>", "$", "this", "->", "id", ",", "'items'", "=>", "array_map", "(", "function", "(", "CartItem", "$", "item", ")", "{", "return", "$", "item", "->", "toArray", "(", ")", ";", ...
Export the cart as an array. @return array
[ "Export", "the", "cart", "as", "an", "array", "." ]
88dadd4b419826336b9a60296264c085d969f77a
https://github.com/mike182uk/cart/blob/88dadd4b419826336b9a60296264c085d969f77a/src/Cart.php#L337-L345
train
izniburak/php-router
src/Router/RouterRequest.php
RouterRequest.validMethod
public static function validMethod($data, $method) { $valid = false; if (strstr($data, '|')) { foreach (explode('|', $data) as $value) { $valid = self::checkMethods($value, $method); if ($valid) { break; } } } else { $valid = self::checkMethods($data, $method); } return $valid; }
php
public static function validMethod($data, $method) { $valid = false; if (strstr($data, '|')) { foreach (explode('|', $data) as $value) { $valid = self::checkMethods($value, $method); if ($valid) { break; } } } else { $valid = self::checkMethods($data, $method); } return $valid; }
[ "public", "static", "function", "validMethod", "(", "$", "data", ",", "$", "method", ")", "{", "$", "valid", "=", "false", ";", "if", "(", "strstr", "(", "$", "data", ",", "'|'", ")", ")", "{", "foreach", "(", "explode", "(", "'|'", ",", "$", "da...
Request method validation @param string $data @param string $method @return bool
[ "Request", "method", "validation" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router/RouterRequest.php#L28-L43
train
izniburak/php-router
src/Router/RouterRequest.php
RouterRequest.checkMethods
protected static function checkMethods($value, $method) { $valid = false; if ($value === 'AJAX' && self::isAjax() && $value === $method) { $valid = true; } elseif ($value === 'AJAXP' && self::isAjax() && $method === 'POST') { $valid = true; } elseif (in_array($value, explode('|', self::$validMethods)) && ($value === $method || $value === 'ANY')) { $valid = true; } return $valid; }
php
protected static function checkMethods($value, $method) { $valid = false; if ($value === 'AJAX' && self::isAjax() && $value === $method) { $valid = true; } elseif ($value === 'AJAXP' && self::isAjax() && $method === 'POST') { $valid = true; } elseif (in_array($value, explode('|', self::$validMethods)) && ($value === $method || $value === 'ANY')) { $valid = true; } return $valid; }
[ "protected", "static", "function", "checkMethods", "(", "$", "value", ",", "$", "method", ")", "{", "$", "valid", "=", "false", ";", "if", "(", "$", "value", "===", "'AJAX'", "&&", "self", "::", "isAjax", "(", ")", "&&", "$", "value", "===", "$", "...
check method valid @param string $value @param string $method @return bool
[ "check", "method", "valid" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router/RouterRequest.php#L53-L65
train
izniburak/php-router
src/Router/RouterCommand.php
RouterCommand.beforeAfter
public function beforeAfter($command, $path = '', $namespace = '') { if (! is_null($command)) { if (is_array($command)) { foreach ($command as $key => $value) { $this->beforeAfter($value, $path, $namespace); } } elseif (is_string($command)) { $controller = $this->resolveClass($command, $path, $namespace); if (method_exists($controller, 'handle')) { return call_user_func([$controller, 'handle']); } return $this->exception('handle() method is not found in <b>'.$command.'</b> class.'); } } return; }
php
public function beforeAfter($command, $path = '', $namespace = '') { if (! is_null($command)) { if (is_array($command)) { foreach ($command as $key => $value) { $this->beforeAfter($value, $path, $namespace); } } elseif (is_string($command)) { $controller = $this->resolveClass($command, $path, $namespace); if (method_exists($controller, 'handle')) { return call_user_func([$controller, 'handle']); } return $this->exception('handle() method is not found in <b>'.$command.'</b> class.'); } } return; }
[ "public", "function", "beforeAfter", "(", "$", "command", ",", "$", "path", "=", "''", ",", "$", "namespace", "=", "''", ")", "{", "if", "(", "!", "is_null", "(", "$", "command", ")", ")", "{", "if", "(", "is_array", "(", "$", "command", ")", ")"...
Run Route Middlewares @param $command @param $path @param $namespace @return mixed|void @throws
[ "Run", "Route", "Middlewares" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router/RouterCommand.php#L56-L74
train
izniburak/php-router
src/Router/RouterCommand.php
RouterCommand.resolveClass
protected function resolveClass($class, $path, $namespace) { $file = realpath(rtrim($path, '/') . '/' . $class . '.php'); if (! file_exists($file)) { return $this->exception($class . ' class is not found. Please, check file.'); } require_once($file); $class = $namespace . str_replace('/', '\\', $class); return new $class(); }
php
protected function resolveClass($class, $path, $namespace) { $file = realpath(rtrim($path, '/') . '/' . $class . '.php'); if (! file_exists($file)) { return $this->exception($class . ' class is not found. Please, check file.'); } require_once($file); $class = $namespace . str_replace('/', '\\', $class); return new $class(); }
[ "protected", "function", "resolveClass", "(", "$", "class", ",", "$", "path", ",", "$", "namespace", ")", "{", "$", "file", "=", "realpath", "(", "rtrim", "(", "$", "path", ",", "'/'", ")", ".", "'/'", ".", "$", "class", ".", "'.php'", ")", ";", ...
Resolve Controller or Middleware class. @param $class @param $path @param $namespace @return object @throws
[ "Resolve", "Controller", "or", "Middleware", "class", "." ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router/RouterCommand.php#L124-L135
train
izniburak/php-router
src/Router.php
Router.setPaths
protected function setPaths($params) { if (isset($params['paths']) && $paths = $params['paths']) { $this->paths['controllers'] = isset($paths['controllers']) ? trim($paths['controllers'], '/') : $this->paths['controllers']; $this->paths['middlewares'] = isset($paths['middlewares']) ? trim($paths['middlewares'], '/') : $this->paths['middlewares']; } if (isset($params['namespaces']) && $namespaces = $params['namespaces']) { $this->namespaces['controllers'] = isset($namespaces['controllers']) ? trim($namespaces['controllers'], '\\') . '\\' : ''; $this->namespaces['middlewares'] = isset($namespaces['middlewares']) ? trim($namespaces['middlewares'], '\\') . '\\' : ''; } if (isset($params['base_folder'])) { $this->baseFolder = rtrim($params['base_folder'], '/'); } if (isset($params['main_method'])) { $this->mainMethod = $params['main_method']; } if (isset($params['cache'])) { $this->cacheFile = $params['cache']; } else { $this->cacheFile = realpath(__DIR__ . '/../cache.php'); } }
php
protected function setPaths($params) { if (isset($params['paths']) && $paths = $params['paths']) { $this->paths['controllers'] = isset($paths['controllers']) ? trim($paths['controllers'], '/') : $this->paths['controllers']; $this->paths['middlewares'] = isset($paths['middlewares']) ? trim($paths['middlewares'], '/') : $this->paths['middlewares']; } if (isset($params['namespaces']) && $namespaces = $params['namespaces']) { $this->namespaces['controllers'] = isset($namespaces['controllers']) ? trim($namespaces['controllers'], '\\') . '\\' : ''; $this->namespaces['middlewares'] = isset($namespaces['middlewares']) ? trim($namespaces['middlewares'], '\\') . '\\' : ''; } if (isset($params['base_folder'])) { $this->baseFolder = rtrim($params['base_folder'], '/'); } if (isset($params['main_method'])) { $this->mainMethod = $params['main_method']; } if (isset($params['cache'])) { $this->cacheFile = $params['cache']; } else { $this->cacheFile = realpath(__DIR__ . '/../cache.php'); } }
[ "protected", "function", "setPaths", "(", "$", "params", ")", "{", "if", "(", "isset", "(", "$", "params", "[", "'paths'", "]", ")", "&&", "$", "paths", "=", "$", "params", "[", "'paths'", "]", ")", "{", "$", "this", "->", "paths", "[", "'controlle...
Set paths and namespaces for Controllers and Middlewares. @param array $params @return void
[ "Set", "paths", "and", "namespaces", "for", "Controllers", "and", "Middlewares", "." ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L117-L156
train
izniburak/php-router
src/Router.php
Router.add
public function add($methods, $route, $settings, $callback = null) { if($this->cacheLoaded) { return true; } if (is_null($callback)) { $callback = $settings; $settings = null; } if (strstr($methods, '|')) { foreach (array_unique(explode('|', $methods)) as $method) { if ($method != '') { call_user_func_array([$this, strtolower($method)], [$route, $settings, $callback]); } } } else { call_user_func_array([$this, strtolower($methods)], [$route, $settings, $callback]); } return true; }
php
public function add($methods, $route, $settings, $callback = null) { if($this->cacheLoaded) { return true; } if (is_null($callback)) { $callback = $settings; $settings = null; } if (strstr($methods, '|')) { foreach (array_unique(explode('|', $methods)) as $method) { if ($method != '') { call_user_func_array([$this, strtolower($method)], [$route, $settings, $callback]); } } } else { call_user_func_array([$this, strtolower($methods)], [$route, $settings, $callback]); } return true; }
[ "public", "function", "add", "(", "$", "methods", ",", "$", "route", ",", "$", "settings", ",", "$", "callback", "=", "null", ")", "{", "if", "(", "$", "this", "->", "cacheLoaded", ")", "{", "return", "true", ";", "}", "if", "(", "is_null", "(", ...
Add new route method one or more http methods. @param string $methods @param string $route @param array|string|closure $settings @param string|closure $callback @return bool
[ "Add", "new", "route", "method", "one", "or", "more", "http", "methods", "." ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L229-L251
train
izniburak/php-router
src/Router.php
Router.pattern
public function pattern($pattern, $attr = null) { if (is_array($pattern)) { foreach ($pattern as $key => $value) { if (! in_array('{' . $key . '}', array_keys($this->patterns))) { $this->patterns['{' . $key . '}'] = '(' . $value . ')'; } else { return $this->exception($key . ' pattern cannot be changed.'); } } } else { if (! in_array('{' . $pattern . '}', array_keys($this->patterns))) { $this->patterns['{' . $pattern . '}'] = '(' . $attr . ')'; } else { return $this->exception($pattern . ' pattern cannot be changed.'); } } return true; }
php
public function pattern($pattern, $attr = null) { if (is_array($pattern)) { foreach ($pattern as $key => $value) { if (! in_array('{' . $key . '}', array_keys($this->patterns))) { $this->patterns['{' . $key . '}'] = '(' . $value . ')'; } else { return $this->exception($key . ' pattern cannot be changed.'); } } } else { if (! in_array('{' . $pattern . '}', array_keys($this->patterns))) { $this->patterns['{' . $pattern . '}'] = '(' . $attr . ')'; } else { return $this->exception($pattern . ' pattern cannot be changed.'); } } return true; }
[ "public", "function", "pattern", "(", "$", "pattern", ",", "$", "attr", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "pattern", ")", ")", "{", "foreach", "(", "$", "pattern", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", ...
Add new route rules pattern; String or Array @param string|array $pattern @param null|string $attr @return mixed @throws
[ "Add", "new", "route", "rules", "pattern", ";", "String", "or", "Array" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L262-L281
train
izniburak/php-router
src/Router.php
Router.controller
public function controller($route, $settings, $controller = null) { if($this->cacheLoaded) { return true; } if (is_null($controller)) { $controller = $settings; $settings = []; } $controller = str_replace(['\\', '.'], '/', $controller); $controllerFile = realpath( rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php' ); if (! file_exists($controllerFile)) { return $this->exception($controller . ' class is not found!'); } if (! class_exists($controller)) { require $controllerFile; } $controller = str_replace('/', '\\', $controller); $classMethods = get_class_methods($this->namespaces['controllers'] . $controller); if ($classMethods) { foreach ($classMethods as $methodName) { if(!strstr($methodName, '__')) { $method = "any"; foreach(explode('|', RouterRequest::$validMethods) as $m) { if(stripos($methodName, strtolower($m), 0) === 0) { $method = strtolower($m); break; } } $methodVar = lcfirst(str_replace($method, '', $methodName)); $r = new ReflectionMethod($this->namespaces['controllers'] . $controller, $methodName); $reqiredParam = $r->getNumberOfRequiredParameters(); $totalParam = $r->getNumberOfParameters(); $value = ($methodVar === $this->mainMethod ? $route : $route.'/'.$methodVar); $this->{$method}( ($value.str_repeat('/{a}', $reqiredParam).str_repeat('/{a?}', $totalParam-$reqiredParam)), $settings, ($controller . '@' . $methodName) ); } } unset($r); } return true; }
php
public function controller($route, $settings, $controller = null) { if($this->cacheLoaded) { return true; } if (is_null($controller)) { $controller = $settings; $settings = []; } $controller = str_replace(['\\', '.'], '/', $controller); $controllerFile = realpath( rtrim($this->paths['controllers'], '/') . '/' . $controller . '.php' ); if (! file_exists($controllerFile)) { return $this->exception($controller . ' class is not found!'); } if (! class_exists($controller)) { require $controllerFile; } $controller = str_replace('/', '\\', $controller); $classMethods = get_class_methods($this->namespaces['controllers'] . $controller); if ($classMethods) { foreach ($classMethods as $methodName) { if(!strstr($methodName, '__')) { $method = "any"; foreach(explode('|', RouterRequest::$validMethods) as $m) { if(stripos($methodName, strtolower($m), 0) === 0) { $method = strtolower($m); break; } } $methodVar = lcfirst(str_replace($method, '', $methodName)); $r = new ReflectionMethod($this->namespaces['controllers'] . $controller, $methodName); $reqiredParam = $r->getNumberOfRequiredParameters(); $totalParam = $r->getNumberOfParameters(); $value = ($methodVar === $this->mainMethod ? $route : $route.'/'.$methodVar); $this->{$method}( ($value.str_repeat('/{a}', $reqiredParam).str_repeat('/{a?}', $totalParam-$reqiredParam)), $settings, ($controller . '@' . $methodName) ); } } unset($r); } return true; }
[ "public", "function", "controller", "(", "$", "route", ",", "$", "settings", ",", "$", "controller", "=", "null", ")", "{", "if", "(", "$", "this", "->", "cacheLoaded", ")", "{", "return", "true", ";", "}", "if", "(", "is_null", "(", "$", "controller...
Added route from methods of Controller file. @param string $route @param string|array $settings @param null|string $controller @return mixed @throws
[ "Added", "route", "from", "methods", "of", "Controller", "file", "." ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L454-L508
train
izniburak/php-router
src/Router.php
Router.addRoute
private function addRoute($uri, $method, $callback, $settings) { $groupItem = count($this->groups) - 1; $group = ''; if ($groupItem > -1) { foreach ($this->groups as $key => $value) { $group .= $value['route']; } } $page = dirname($_SERVER['PHP_SELF']); $page = $page === '/' ? '' : $page; if (strstr($page, 'index.php')) { $data = implode('/', explode('/', $page)); $page = str_replace($data, '', $page); } $route = $page . $group . '/' . trim($uri, '/'); $route = rtrim($route, '/'); if ($route === $page) { $route .= '/'; } $data = [ 'route' => str_replace('//', '/', $route), 'method' => strtoupper($method), 'callback' => $callback, 'name' => (isset($settings['name']) ? $settings['name'] : null ), 'before' => (isset($settings['before']) ? $settings['before'] : null ), 'after' => (isset($settings['after']) ? $settings['after'] : null ), 'group' => ($groupItem === -1) ? null : $this->groups[$groupItem] ]; array_push($this->routes, $data); }
php
private function addRoute($uri, $method, $callback, $settings) { $groupItem = count($this->groups) - 1; $group = ''; if ($groupItem > -1) { foreach ($this->groups as $key => $value) { $group .= $value['route']; } } $page = dirname($_SERVER['PHP_SELF']); $page = $page === '/' ? '' : $page; if (strstr($page, 'index.php')) { $data = implode('/', explode('/', $page)); $page = str_replace($data, '', $page); } $route = $page . $group . '/' . trim($uri, '/'); $route = rtrim($route, '/'); if ($route === $page) { $route .= '/'; } $data = [ 'route' => str_replace('//', '/', $route), 'method' => strtoupper($method), 'callback' => $callback, 'name' => (isset($settings['name']) ? $settings['name'] : null ), 'before' => (isset($settings['before']) ? $settings['before'] : null ), 'after' => (isset($settings['after']) ? $settings['after'] : null ), 'group' => ($groupItem === -1) ? null : $this->groups[$groupItem] ]; array_push($this->routes, $data); }
[ "private", "function", "addRoute", "(", "$", "uri", ",", "$", "method", ",", "$", "callback", ",", "$", "settings", ")", "{", "$", "groupItem", "=", "count", "(", "$", "this", "->", "groups", ")", "-", "1", ";", "$", "group", "=", "''", ";", "if"...
Add new Route and it's settings @param $uri @param $method @param $callback @param $settings @return void
[ "Add", "new", "Route", "and", "it", "s", "settings" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L532-L574
train
izniburak/php-router
src/Router.php
Router.runRouteMiddleware
public function runRouteMiddleware($middleware, $type) { $middlewarePath = $this->baseFolder . '/' . $this->paths['middlewares']; $middlewareNs = $this->namespaces['middlewares']; if ($type == 'before') { if (! is_null($middleware['group'])) { $this->routerCommand()->beforeAfter( $middleware['group'][$type], $middlewarePath, $middlewareNs ); } $this->routerCommand()->beforeAfter( $middleware[$type], $middlewarePath, $middlewareNs ); } else { $this->routerCommand()->beforeAfter( $middleware[$type], $middlewarePath, $middlewareNs ); if (! is_null($middleware['group'])) { $this->routerCommand()->beforeAfter( $middleware['group'][$type], $middlewarePath, $middlewareNs ); } } }
php
public function runRouteMiddleware($middleware, $type) { $middlewarePath = $this->baseFolder . '/' . $this->paths['middlewares']; $middlewareNs = $this->namespaces['middlewares']; if ($type == 'before') { if (! is_null($middleware['group'])) { $this->routerCommand()->beforeAfter( $middleware['group'][$type], $middlewarePath, $middlewareNs ); } $this->routerCommand()->beforeAfter( $middleware[$type], $middlewarePath, $middlewareNs ); } else { $this->routerCommand()->beforeAfter( $middleware[$type], $middlewarePath, $middlewareNs ); if (! is_null($middleware['group'])) { $this->routerCommand()->beforeAfter( $middleware['group'][$type], $middlewarePath, $middlewareNs ); } } }
[ "public", "function", "runRouteMiddleware", "(", "$", "middleware", ",", "$", "type", ")", "{", "$", "middlewarePath", "=", "$", "this", "->", "baseFolder", ".", "'/'", ".", "$", "this", "->", "paths", "[", "'middlewares'", "]", ";", "$", "middlewareNs", ...
Detect Routes Middleware; before or after @param $middleware @param $type @return void
[ "Detect", "Routes", "Middleware", ";", "before", "or", "after" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L601-L624
train
izniburak/php-router
src/Router.php
Router.cache
public function cache() { foreach($this->getRoutes() as $key => $r) { if (!is_string($r['callback'])) { throw new Exception(sprintf('Routes cannot contain a Closure/Function callback while caching.')); } } $cacheContent = '<?php return '.var_export($this->getRoutes(), true).';' . PHP_EOL; if (false === file_put_contents($this->cacheFile, $cacheContent)) { throw new Exception(sprintf('Routes cache file could not be written.')); } return true; }
php
public function cache() { foreach($this->getRoutes() as $key => $r) { if (!is_string($r['callback'])) { throw new Exception(sprintf('Routes cannot contain a Closure/Function callback while caching.')); } } $cacheContent = '<?php return '.var_export($this->getRoutes(), true).';' . PHP_EOL; if (false === file_put_contents($this->cacheFile, $cacheContent)) { throw new Exception(sprintf('Routes cache file could not be written.')); } return true; }
[ "public", "function", "cache", "(", ")", "{", "foreach", "(", "$", "this", "->", "getRoutes", "(", ")", "as", "$", "key", "=>", "$", "r", ")", "{", "if", "(", "!", "is_string", "(", "$", "r", "[", "'callback'", "]", ")", ")", "{", "throw", "new...
Cache all routes @return bool @throws Exception
[ "Cache", "all", "routes" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L688-L702
train
izniburak/php-router
src/Router.php
Router.loadCache
protected function loadCache() { if (file_exists($this->cacheFile)) { $this->routes = require $this->cacheFile; $this->cacheLoaded = true; return true; } return false; }
php
protected function loadCache() { if (file_exists($this->cacheFile)) { $this->routes = require $this->cacheFile; $this->cacheLoaded = true; return true; } return false; }
[ "protected", "function", "loadCache", "(", ")", "{", "if", "(", "file_exists", "(", "$", "this", "->", "cacheFile", ")", ")", "{", "$", "this", "->", "routes", "=", "require", "$", "this", "->", "cacheFile", ";", "$", "this", "->", "cacheLoaded", "=", ...
Load Cache file @return bool
[ "Load", "Cache", "file" ]
cc75420df6c0c889123aa0051cbab446c7d79e07
https://github.com/izniburak/php-router/blob/cc75420df6c0c889123aa0051cbab446c7d79e07/src/Router.php#L709-L718
train
Litecms/Block
src/Block.php
Block.count
public function count($module) { if (User::hasRole('user')) { $this->block->pushCriteria(new \Litecms\Block\Repositories\Criteria\BlockUserCriteria()); } if ($module == 'block') { return $this->block ->scopeQuery(function ($query) { return $query; }) ->count(); } if ($module == 'category') { return $this->category ->scopeQuery(function ($query) { return $query; })->count(); } if ($module == 'public') { return $this->block ->pushCriteria(new \Litecms\Block\Repositories\Criteria\BlockPublicCriteria()) ->scopeQuery(function ($query) { return $query; })->count(); } }
php
public function count($module) { if (User::hasRole('user')) { $this->block->pushCriteria(new \Litecms\Block\Repositories\Criteria\BlockUserCriteria()); } if ($module == 'block') { return $this->block ->scopeQuery(function ($query) { return $query; }) ->count(); } if ($module == 'category') { return $this->category ->scopeQuery(function ($query) { return $query; })->count(); } if ($module == 'public') { return $this->block ->pushCriteria(new \Litecms\Block\Repositories\Criteria\BlockPublicCriteria()) ->scopeQuery(function ($query) { return $query; })->count(); } }
[ "public", "function", "count", "(", "$", "module", ")", "{", "if", "(", "User", "::", "hasRole", "(", "'user'", ")", ")", "{", "$", "this", "->", "block", "->", "pushCriteria", "(", "new", "\\", "Litecms", "\\", "Block", "\\", "Repositories", "\\", "...
Returns count of blog or category. @param array $filter @return int
[ "Returns", "count", "of", "blog", "or", "category", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Block.php#L34-L64
train
Litecms/Block
src/Block.php
Block.selectCategories
public function selectCategories() { $temp = []; $category = $this->category->scopeQuery(function ($query) { return $query->whereStatus('Show')->orderBy('name', 'ASC'); })->all(); foreach ($category as $key => $value) { $temp[$value->id] = ucfirst($value->name); } return $temp; }
php
public function selectCategories() { $temp = []; $category = $this->category->scopeQuery(function ($query) { return $query->whereStatus('Show')->orderBy('name', 'ASC'); })->all(); foreach ($category as $key => $value) { $temp[$value->id] = ucfirst($value->name); } return $temp; }
[ "public", "function", "selectCategories", "(", ")", "{", "$", "temp", "=", "[", "]", ";", "$", "category", "=", "$", "this", "->", "category", "->", "scopeQuery", "(", "function", "(", "$", "query", ")", "{", "return", "$", "query", "->", "whereStatus"...
take block category @return array
[ "take", "block", "category" ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Block.php#L71-L83
train
Litecms/Block
src/Block.php
Block.display
public function display($category) { $view = (View::exists("block::{$category}")) ? "block::{$category}" : "block::default"; $category = $this->category ->scopeQuery(function ($query) use ($category) { return $query->with('blocks')->whereSlug($category); })->first(); $blocks = $category->blocks; return view($view, compact('blocks', 'category'))->render(); }
php
public function display($category) { $view = (View::exists("block::{$category}")) ? "block::{$category}" : "block::default"; $category = $this->category ->scopeQuery(function ($query) use ($category) { return $query->with('blocks')->whereSlug($category); })->first(); $blocks = $category->blocks; return view($view, compact('blocks', 'category'))->render(); }
[ "public", "function", "display", "(", "$", "category", ")", "{", "$", "view", "=", "(", "View", "::", "exists", "(", "\"block::{$category}\"", ")", ")", "?", "\"block::{$category}\"", ":", "\"block::default\"", ";", "$", "category", "=", "$", "this", "->", ...
take latest blocks for public side @param type $count @param type|string $view @return type
[ "take", "latest", "blocks", "for", "public", "side" ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Block.php#L92-L104
train
Litecms/Block
src/Http/Controllers/CategoryResourceController.php
CategoryResourceController.show
public function show(CategoryRequest $request, Category $category) { if ($category->exists) { $view = 'block::admin.category.show'; } else { $view = 'block::admin.category.new'; } return $this->response->setMetaTitle(trans('app.view') . ' ' . trans('block::category.name')) ->data(compact('category')) ->view($view) ->output(); }
php
public function show(CategoryRequest $request, Category $category) { if ($category->exists) { $view = 'block::admin.category.show'; } else { $view = 'block::admin.category.new'; } return $this->response->setMetaTitle(trans('app.view') . ' ' . trans('block::category.name')) ->data(compact('category')) ->view($view) ->output(); }
[ "public", "function", "show", "(", "CategoryRequest", "$", "request", ",", "Category", "$", "category", ")", "{", "if", "(", "$", "category", "->", "exists", ")", "{", "$", "view", "=", "'block::admin.category.show'", ";", "}", "else", "{", "$", "view", ...
Display category. @param Request $request @param Model $category @return Response
[ "Display", "category", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/CategoryResourceController.php#L66-L79
train
Litecms/Block
src/Policies/CategoryPolicy.php
CategoryPolicy.view
public function view(User $user, Category $category) { if ($user->canDo('block.category.view') && $user->isAdmin()) { return true; } return $user->id == $category->user_id; }
php
public function view(User $user, Category $category) { if ($user->canDo('block.category.view') && $user->isAdmin()) { return true; } return $user->id == $category->user_id; }
[ "public", "function", "view", "(", "User", "$", "user", ",", "Category", "$", "category", ")", "{", "if", "(", "$", "user", "->", "canDo", "(", "'block.category.view'", ")", "&&", "$", "user", "->", "isAdmin", "(", ")", ")", "{", "return", "true", ";...
Determine if the given user can view the category. @param User $user @param Category $category @return bool
[ "Determine", "if", "the", "given", "user", "can", "view", "the", "category", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Policies/CategoryPolicy.php#L21-L29
train
Litecms/Block
src/Http/Controllers/BlockResourceController.php
BlockResourceController.index
public function index(BlockRequest $request) { if ($this->response->typeIs('json')) { $pageLimit = $request->input('pageLimit'); $data = $this->repository ->setPresenter(\Litecms\Block\Repositories\Presenter\BlockListPresenter::class) ->getDataTable($pageLimit); return $this->response ->data($data) ->output(); } $blocks = $this->repository->paginate(); return $this->response->setMetaTitle(trans('block::block.names')) ->view('block::admin.block.index') ->data(compact('blocks')) ->output(); }
php
public function index(BlockRequest $request) { if ($this->response->typeIs('json')) { $pageLimit = $request->input('pageLimit'); $data = $this->repository ->setPresenter(\Litecms\Block\Repositories\Presenter\BlockListPresenter::class) ->getDataTable($pageLimit); return $this->response ->data($data) ->output(); } $blocks = $this->repository->paginate(); return $this->response->setMetaTitle(trans('block::block.names')) ->view('block::admin.block.index') ->data(compact('blocks')) ->output(); }
[ "public", "function", "index", "(", "BlockRequest", "$", "request", ")", "{", "if", "(", "$", "this", "->", "response", "->", "typeIs", "(", "'json'", ")", ")", "{", "$", "pageLimit", "=", "$", "request", "->", "input", "(", "'pageLimit'", ")", ";", ...
Display a list of block. @return Response
[ "Display", "a", "list", "of", "block", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/BlockResourceController.php#L37-L56
train
Litecms/Block
src/Http/Controllers/BlockResourceController.php
BlockResourceController.show
public function show(BlockRequest $request, Block $block) { if ($block->exists) { $view = 'block::admin.block.show'; } else { $view = 'block::admin.block.new'; } return $this->response->setMetaTitle(trans('app.view') . ' ' . trans('block::block.name')) ->data(compact('block')) ->view($view) ->output(); }
php
public function show(BlockRequest $request, Block $block) { if ($block->exists) { $view = 'block::admin.block.show'; } else { $view = 'block::admin.block.new'; } return $this->response->setMetaTitle(trans('app.view') . ' ' . trans('block::block.name')) ->data(compact('block')) ->view($view) ->output(); }
[ "public", "function", "show", "(", "BlockRequest", "$", "request", ",", "Block", "$", "block", ")", "{", "if", "(", "$", "block", "->", "exists", ")", "{", "$", "view", "=", "'block::admin.block.show'", ";", "}", "else", "{", "$", "view", "=", "'block:...
Display block. @param Request $request @param Model $block @return Response
[ "Display", "block", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/BlockResourceController.php#L66-L79
train
Litecms/Block
src/Http/Controllers/BlockResourceController.php
BlockResourceController.create
public function create(BlockRequest $request) { $block = $this->repository->newInstance([]); return $this->response->setMetaTitle(trans('app.new') . ' ' . trans('block::block.name')) ->view('block::admin.block.create') ->data(compact('block')) ->output(); }
php
public function create(BlockRequest $request) { $block = $this->repository->newInstance([]); return $this->response->setMetaTitle(trans('app.new') . ' ' . trans('block::block.name')) ->view('block::admin.block.create') ->data(compact('block')) ->output(); }
[ "public", "function", "create", "(", "BlockRequest", "$", "request", ")", "{", "$", "block", "=", "$", "this", "->", "repository", "->", "newInstance", "(", "[", "]", ")", ";", "return", "$", "this", "->", "response", "->", "setMetaTitle", "(", "trans", ...
Show the form for creating a new block. @param Request $request @return Response
[ "Show", "the", "form", "for", "creating", "a", "new", "block", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/BlockResourceController.php#L88-L96
train
Litecms/Block
src/Http/Controllers/BlockResourceController.php
BlockResourceController.edit
public function edit(BlockRequest $request, Block $block) { return $this->response->setMetaTitle(trans('app.edit') . ' ' . trans('block::block.name')) ->view('block::admin.block.edit') ->data(compact('block')) ->output(); }
php
public function edit(BlockRequest $request, Block $block) { return $this->response->setMetaTitle(trans('app.edit') . ' ' . trans('block::block.name')) ->view('block::admin.block.edit') ->data(compact('block')) ->output(); }
[ "public", "function", "edit", "(", "BlockRequest", "$", "request", ",", "Block", "$", "block", ")", "{", "return", "$", "this", "->", "response", "->", "setMetaTitle", "(", "trans", "(", "'app.edit'", ")", ".", "' '", ".", "trans", "(", "'block::block.name...
Show block for editing. @param Request $request @param Model $block @return Response
[ "Show", "block", "for", "editing", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/BlockResourceController.php#L136-L142
train
Litecms/Block
src/Http/Controllers/BlockResourceController.php
BlockResourceController.update
public function update(BlockRequest $request, Block $block) { try { $attributes = $request->all(); $block->update($attributes); return $this->response->message(trans('messages.success.updated', ['Module' => trans('block::block.name')])) ->code(204) ->status('success') ->url(guard_url('block/block/' . $block->getRouteKey())) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('block/block/' . $block->getRouteKey())) ->redirect(); } }
php
public function update(BlockRequest $request, Block $block) { try { $attributes = $request->all(); $block->update($attributes); return $this->response->message(trans('messages.success.updated', ['Module' => trans('block::block.name')])) ->code(204) ->status('success') ->url(guard_url('block/block/' . $block->getRouteKey())) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('block/block/' . $block->getRouteKey())) ->redirect(); } }
[ "public", "function", "update", "(", "BlockRequest", "$", "request", ",", "Block", "$", "block", ")", "{", "try", "{", "$", "attributes", "=", "$", "request", "->", "all", "(", ")", ";", "$", "block", "->", "update", "(", "$", "attributes", ")", ";",...
Update the block. @param Request $request @param Model $block @return Response
[ "Update", "the", "block", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/BlockResourceController.php#L152-L171
train
Litecms/Block
src/Http/Controllers/BlockResourceController.php
BlockResourceController.destroy
public function destroy(BlockRequest $request, Block $block) { try { $block->delete(); return $this->response->message(trans('messages.success.deleted', ['Module' => trans('block::block.name')])) ->code(202) ->status('success') ->url(guard_url('block/block')) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('block/block/' . $block->getRouteKey())) ->redirect(); } }
php
public function destroy(BlockRequest $request, Block $block) { try { $block->delete(); return $this->response->message(trans('messages.success.deleted', ['Module' => trans('block::block.name')])) ->code(202) ->status('success') ->url(guard_url('block/block')) ->redirect(); } catch (Exception $e) { return $this->response->message($e->getMessage()) ->code(400) ->status('error') ->url(guard_url('block/block/' . $block->getRouteKey())) ->redirect(); } }
[ "public", "function", "destroy", "(", "BlockRequest", "$", "request", ",", "Block", "$", "block", ")", "{", "try", "{", "$", "block", "->", "delete", "(", ")", ";", "return", "$", "this", "->", "response", "->", "message", "(", "trans", "(", "'messages...
Remove the block. @param Model $block @return Response
[ "Remove", "the", "block", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Http/Controllers/BlockResourceController.php#L180-L200
train
Litecms/Block
src/Policies/BlockPolicy.php
BlockPolicy.update
public function update(User $user, Block $block) { if ($user->canDo('block.block.update') && $user->isAdmin()) { return true; } return $user->id == $block->user_id; }
php
public function update(User $user, Block $block) { if ($user->canDo('block.block.update') && $user->isAdmin()) { return true; } return $user->id == $block->user_id; }
[ "public", "function", "update", "(", "User", "$", "user", ",", "Block", "$", "block", ")", "{", "if", "(", "$", "user", "->", "canDo", "(", "'block.block.update'", ")", "&&", "$", "user", "->", "isAdmin", "(", ")", ")", "{", "return", "true", ";", ...
Determine if the given user can update the given block. @param User $user @param Block $block @return bool
[ "Determine", "if", "the", "given", "user", "can", "update", "the", "given", "block", "." ]
79b6abff0180a2fabeb3574e883972ddd44daaa6
https://github.com/Litecms/Block/blob/79b6abff0180a2fabeb3574e883972ddd44daaa6/src/Policies/BlockPolicy.php#L52-L60
train
spatie/7to5
src/NodeVisitors/AnonymousClassReplacer.php
AnonymousClassReplacer.getAnonymousClassHookIndex
protected function getAnonymousClassHookIndex(array $statements) { $hookIndex = false; foreach ($statements as $index => $statement) { if (!$statement instanceof Declare_ && !$statement instanceof Use_ && !$statement instanceof Namespace_) { $hookIndex = $index; } } if ($hookIndex === false) { throw InvalidPhpCode::noValidLocationFoundToInsertClasses(); } return $hookIndex; }
php
protected function getAnonymousClassHookIndex(array $statements) { $hookIndex = false; foreach ($statements as $index => $statement) { if (!$statement instanceof Declare_ && !$statement instanceof Use_ && !$statement instanceof Namespace_) { $hookIndex = $index; } } if ($hookIndex === false) { throw InvalidPhpCode::noValidLocationFoundToInsertClasses(); } return $hookIndex; }
[ "protected", "function", "getAnonymousClassHookIndex", "(", "array", "$", "statements", ")", "{", "$", "hookIndex", "=", "false", ";", "foreach", "(", "$", "statements", "as", "$", "index", "=>", "$", "statement", ")", "{", "if", "(", "!", "$", "statement"...
Find the index of the first statement that is not a declare, use or namespace statement. @param array $statements @return int @throws \Spatie\Php7to5\Exceptions\InvalidPhpCode
[ "Find", "the", "index", "of", "the", "first", "statement", "that", "is", "not", "a", "declare", "use", "or", "namespace", "statement", "." ]
64d1e12570eb3e4ce4976245ba48e881383b5580
https://github.com/spatie/7to5/blob/64d1e12570eb3e4ce4976245ba48e881383b5580/src/NodeVisitors/AnonymousClassReplacer.php#L79-L96
train
rairlie/laravel-locking-session
src/Rairlie/LockingSession/LockingSessionServiceProvider.php
LockingSessionServiceProvider.register
public function register() { $this->registerSessionManager(); $this->registerSessionDriver(); $this->app->singleton('Illuminate\Session\Middleware\StartSession', function ($app) { return new Middleware\StartSession($app->make('session')); }); }
php
public function register() { $this->registerSessionManager(); $this->registerSessionDriver(); $this->app->singleton('Illuminate\Session\Middleware\StartSession', function ($app) { return new Middleware\StartSession($app->make('session')); }); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "registerSessionManager", "(", ")", ";", "$", "this", "->", "registerSessionDriver", "(", ")", ";", "$", "this", "->", "app", "->", "singleton", "(", "'Illuminate\\Session\\Middleware\\StartSess...
Override so we return our own Middleware\StartSession @return void
[ "Override", "so", "we", "return", "our", "own", "Middleware", "\\", "StartSession" ]
93a623a7eacbcab6ef29b4f036ec35d7383d7395
https://github.com/rairlie/laravel-locking-session/blob/93a623a7eacbcab6ef29b4f036ec35d7383d7395/src/Rairlie/LockingSession/LockingSessionServiceProvider.php#L14-L23
train
rairlie/laravel-locking-session
src/Rairlie/LockingSession/Lock.php
Lock.acquire
public function acquire() { if ($this->lockfp) { $this->log("acquire - existing lock"); return; } $this->openLockFile(); $this->log("acquire - try lock"); flock($this->lockfp, LOCK_EX); $this->log("acquire - got lock"); }
php
public function acquire() { if ($this->lockfp) { $this->log("acquire - existing lock"); return; } $this->openLockFile(); $this->log("acquire - try lock"); flock($this->lockfp, LOCK_EX); $this->log("acquire - got lock"); }
[ "public", "function", "acquire", "(", ")", "{", "if", "(", "$", "this", "->", "lockfp", ")", "{", "$", "this", "->", "log", "(", "\"acquire - existing lock\"", ")", ";", "return", ";", "}", "$", "this", "->", "openLockFile", "(", ")", ";", "$", "this...
Acquire an exclusive lock. Will block if locked by another process.
[ "Acquire", "an", "exclusive", "lock", ".", "Will", "block", "if", "locked", "by", "another", "process", "." ]
93a623a7eacbcab6ef29b4f036ec35d7383d7395
https://github.com/rairlie/laravel-locking-session/blob/93a623a7eacbcab6ef29b4f036ec35d7383d7395/src/Rairlie/LockingSession/Lock.php#L46-L57
train
rairlie/laravel-locking-session
src/Rairlie/LockingSession/Lock.php
Lock.release
public function release() { if (!$this->lockfp) { throw new UnderflowException("No lock to release"); } $this->log("release"); flock($this->lockfp, LOCK_UN); $this->closeLockFile(); }
php
public function release() { if (!$this->lockfp) { throw new UnderflowException("No lock to release"); } $this->log("release"); flock($this->lockfp, LOCK_UN); $this->closeLockFile(); }
[ "public", "function", "release", "(", ")", "{", "if", "(", "!", "$", "this", "->", "lockfp", ")", "{", "throw", "new", "UnderflowException", "(", "\"No lock to release\"", ")", ";", "}", "$", "this", "->", "log", "(", "\"release\"", ")", ";", "flock", ...
Release an acquired lock
[ "Release", "an", "acquired", "lock" ]
93a623a7eacbcab6ef29b4f036ec35d7383d7395
https://github.com/rairlie/laravel-locking-session/blob/93a623a7eacbcab6ef29b4f036ec35d7383d7395/src/Rairlie/LockingSession/Lock.php#L62-L71
train
rairlie/laravel-locking-session
src/Rairlie/LockingSession/Lock.php
Lock.openLockFile
protected function openLockFile() { if (!is_dir(dirname($this->lockfilePath))) { // Suppress warning on mkdir - may be created by another process @mkdir(dirname($this->lockfilePath), 0744, true); } $this->lockfp = fopen($this->lockfilePath, 'w+'); }
php
protected function openLockFile() { if (!is_dir(dirname($this->lockfilePath))) { // Suppress warning on mkdir - may be created by another process @mkdir(dirname($this->lockfilePath), 0744, true); } $this->lockfp = fopen($this->lockfilePath, 'w+'); }
[ "protected", "function", "openLockFile", "(", ")", "{", "if", "(", "!", "is_dir", "(", "dirname", "(", "$", "this", "->", "lockfilePath", ")", ")", ")", "{", "// Suppress warning on mkdir - may be created by another process", "@", "mkdir", "(", "dirname", "(", "...
Open the lock file on disk, creating it if it doesn't exist
[ "Open", "the", "lock", "file", "on", "disk", "creating", "it", "if", "it", "doesn", "t", "exist" ]
93a623a7eacbcab6ef29b4f036ec35d7383d7395
https://github.com/rairlie/laravel-locking-session/blob/93a623a7eacbcab6ef29b4f036ec35d7383d7395/src/Rairlie/LockingSession/Lock.php#L95-L102
train
rairlie/laravel-locking-session
src/Rairlie/LockingSession/Lock.php
Lock.log
protected function log($message) { $this->debug && Log::info($this->lockfilePath . ' ' . getmypid() . ' ' . $message); }
php
protected function log($message) { $this->debug && Log::info($this->lockfilePath . ' ' . getmypid() . ' ' . $message); }
[ "protected", "function", "log", "(", "$", "message", ")", "{", "$", "this", "->", "debug", "&&", "Log", "::", "info", "(", "$", "this", "->", "lockfilePath", ".", "' '", ".", "getmypid", "(", ")", ".", "' '", ".", "$", "message", ")", ";", "}" ]
Log a debug diagnostic message, if enabled
[ "Log", "a", "debug", "diagnostic", "message", "if", "enabled" ]
93a623a7eacbcab6ef29b4f036ec35d7383d7395
https://github.com/rairlie/laravel-locking-session/blob/93a623a7eacbcab6ef29b4f036ec35d7383d7395/src/Rairlie/LockingSession/Lock.php#L118-L121
train
LUSHDigital/microservice-core
src/Pagination/Response.php
Response.snakeFormat
public function snakeFormat() { $snake = new \stdClass; $rawValues = get_object_vars($this); foreach ($rawValues as $property => $value){ $snake->{Str::snake($property)} = $value; } return $snake; }
php
public function snakeFormat() { $snake = new \stdClass; $rawValues = get_object_vars($this); foreach ($rawValues as $property => $value){ $snake->{Str::snake($property)} = $value; } return $snake; }
[ "public", "function", "snakeFormat", "(", ")", "{", "$", "snake", "=", "new", "\\", "stdClass", ";", "$", "rawValues", "=", "get_object_vars", "(", "$", "this", ")", ";", "foreach", "(", "$", "rawValues", "as", "$", "property", "=>", "$", "value", ")",...
Format the response object with snake case properties. @return \stdClass
[ "Format", "the", "response", "object", "with", "snake", "case", "properties", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Pagination/Response.php#L209-L219
train
LUSHDigital/microservice-core
src/Helpers/MicroServiceHelper.php
MicroServiceHelper.jsonResponseFormatter
public static function jsonResponseFormatter($type, $data, $code = 200, $status = Status::OK, $message = '') { // Validate the arguments. if ($status == Status::OK && empty($type)) { throw new Exception('Cannot prepare response. No type specified'); } else { $type = preg_replace('/[^A-Za-z]/si', '_', strtolower($type)); } // Ensure the data is in an array. if (is_object($data)) { $data = [(array) $data]; } // Prepare the response object. $response = new stdClass(); $response->status = $status; $response->code = $code; $response->message = $message; // Return data in an array. if (!empty($data)) { $response->data = new stdClass(); $response->data->{$type} = $data; } elseif (!empty($type)) { // Return an empty array even if there are no data. $response->data = new stdClass(); $response->data->{$type} = []; } return $response; }
php
public static function jsonResponseFormatter($type, $data, $code = 200, $status = Status::OK, $message = '') { // Validate the arguments. if ($status == Status::OK && empty($type)) { throw new Exception('Cannot prepare response. No type specified'); } else { $type = preg_replace('/[^A-Za-z]/si', '_', strtolower($type)); } // Ensure the data is in an array. if (is_object($data)) { $data = [(array) $data]; } // Prepare the response object. $response = new stdClass(); $response->status = $status; $response->code = $code; $response->message = $message; // Return data in an array. if (!empty($data)) { $response->data = new stdClass(); $response->data->{$type} = $data; } elseif (!empty($type)) { // Return an empty array even if there are no data. $response->data = new stdClass(); $response->data->{$type} = []; } return $response; }
[ "public", "static", "function", "jsonResponseFormatter", "(", "$", "type", ",", "$", "data", ",", "$", "code", "=", "200", ",", "$", "status", "=", "Status", "::", "OK", ",", "$", "message", "=", "''", ")", "{", "// Validate the arguments.", "if", "(", ...
Prepare a response an endpoint. This ensures that all API endpoints return data in a standardised format: { "status": "ok", - Can contain any string. Usually 'ok', 'error' etc. "code": 200, - A HTTP status code. "message": "", - A message string elaborating on the status. "data": {[ - A collection of return data. Can be omitted in the event ]} an error occurred. } @param string $type The type of data being returned. Will be used to name the collection. @param object|array|NULL $data The data to return. Will always be parsed into a collection. @param int $code HTTP status code for the response. @param string $status A short status message. Examples: 'OK', 'Bad Request', 'Not Found'. @param string $message A more detailed status message. @return object The formatted response object. @throws Exception
[ "Prepare", "a", "response", "an", "endpoint", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Helpers/MicroServiceHelper.php#L64-L96
train
LUSHDigital/microservice-core
src/Traits/MicroServiceStringTrait.php
MicroServiceStringTrait.padTrim
protected function padTrim($input, $pad = '0', $length = 3, $mode = STR_PAD_LEFT) { // Make sure we have a string. if (!is_string($input)) { $input = (string) $input; } return substr(str_pad($input, $length, $pad, $mode), 0, $length); }
php
protected function padTrim($input, $pad = '0', $length = 3, $mode = STR_PAD_LEFT) { // Make sure we have a string. if (!is_string($input)) { $input = (string) $input; } return substr(str_pad($input, $length, $pad, $mode), 0, $length); }
[ "protected", "function", "padTrim", "(", "$", "input", ",", "$", "pad", "=", "'0'", ",", "$", "length", "=", "3", ",", "$", "mode", "=", "STR_PAD_LEFT", ")", "{", "// Make sure we have a string.", "if", "(", "!", "is_string", "(", "$", "input", ")", ")...
Trim a string to the specified length. Padding if necessary. @param string $input The input string. @param string $pad The padding character. @param int $length The length of string we want. @param int $mode The string padding mode. @return string
[ "Trim", "a", "string", "to", "the", "specified", "length", ".", "Padding", "if", "necessary", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Traits/MicroServiceStringTrait.php#L30-L38
train
LUSHDigital/microservice-core
src/Traits/MicroServiceJsonResponseTrait.php
MicroServiceJsonResponseTrait.generateResponse
protected function generateResponse($type, $data, $code = 200, $status = Status::OK, $message = '') { if ($code == 204) { return response('', 204); } $returnData = MicroServiceHelper::jsonResponseFormatter($type, $data, $code, $status, $message); return response()->json($returnData, $code); }
php
protected function generateResponse($type, $data, $code = 200, $status = Status::OK, $message = '') { if ($code == 204) { return response('', 204); } $returnData = MicroServiceHelper::jsonResponseFormatter($type, $data, $code, $status, $message); return response()->json($returnData, $code); }
[ "protected", "function", "generateResponse", "(", "$", "type", ",", "$", "data", ",", "$", "code", "=", "200", ",", "$", "status", "=", "Status", "::", "OK", ",", "$", "message", "=", "''", ")", "{", "if", "(", "$", "code", "==", "204", ")", "{",...
Generate a response object in the microservices expected format. @param string $type The type of data being returned. Will be used to name the collection. @param object|array|NULL $data The data to return. Will always be parsed into a collection. @param int $code HTTP status code for the response. @param string $status A short status message. Examples: 'OK', 'Bad Request', 'Not Found'. @param string $message A more detailed status message. @return \Illuminate\Http\Response
[ "Generate", "a", "response", "object", "in", "the", "microservices", "expected", "format", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Traits/MicroServiceJsonResponseTrait.php#L36-L43
train
LUSHDigital/microservice-core
src/Traits/MicroServiceJsonResponseTrait.php
MicroServiceJsonResponseTrait.generatePaginatedResponse
protected function generatePaginatedResponse(Paginator $paginator, $type, $data, $code = 200, $status = Status::OK, $message = '') { $returnData = MicroServiceHelper::jsonResponseFormatter($type, $data, $code, $status, $message); // Append the pagination response to the data. $returnData->pagination = $paginator->preparePaginationResponse()->snakeFormat(); return response()->json($returnData, $code); }
php
protected function generatePaginatedResponse(Paginator $paginator, $type, $data, $code = 200, $status = Status::OK, $message = '') { $returnData = MicroServiceHelper::jsonResponseFormatter($type, $data, $code, $status, $message); // Append the pagination response to the data. $returnData->pagination = $paginator->preparePaginationResponse()->snakeFormat(); return response()->json($returnData, $code); }
[ "protected", "function", "generatePaginatedResponse", "(", "Paginator", "$", "paginator", ",", "$", "type", ",", "$", "data", ",", "$", "code", "=", "200", ",", "$", "status", "=", "Status", "::", "OK", ",", "$", "message", "=", "''", ")", "{", "$", ...
Generate a paginated response object in the microservices expected format. @param Paginator $paginator A paginator for the data being returned. @param string $type The type of data being returned. Will be used to name the collection. @param object|array|NULL $data The data to return. Will always be parsed into a collection. @param int $code HTTP status code for the response. @param string $status A short status message. Examples: 'OK', 'Bad Request', 'Not Found'. @param string $message A more detailed status message. @return \Illuminate\Http\Response
[ "Generate", "a", "paginated", "response", "object", "in", "the", "microservices", "expected", "format", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Traits/MicroServiceJsonResponseTrait.php#L63-L71
train
LUSHDigital/microservice-core
src/Traits/MicroServiceExceptionHandlerTrait.php
MicroServiceExceptionHandlerTrait.isMicroServiceException
public function isMicroServiceException(Exception $e) { foreach ($this->microServicesExceptionTypes as $exceptionType) { if ($e instanceof $exceptionType) { return true; } } return false; }
php
public function isMicroServiceException(Exception $e) { foreach ($this->microServicesExceptionTypes as $exceptionType) { if ($e instanceof $exceptionType) { return true; } } return false; }
[ "public", "function", "isMicroServiceException", "(", "Exception", "$", "e", ")", "{", "foreach", "(", "$", "this", "->", "microServicesExceptionTypes", "as", "$", "exceptionType", ")", "{", "if", "(", "$", "e", "instanceof", "$", "exceptionType", ")", "{", ...
Check if the supplied exception is of any of the types we handle. @param Exception $e @return bool
[ "Check", "if", "the", "supplied", "exception", "is", "of", "any", "of", "the", "types", "we", "handle", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Traits/MicroServiceExceptionHandlerTrait.php#L42-L51
train
LUSHDigital/microservice-core
src/Traits/MicroServiceExceptionHandlerTrait.php
MicroServiceExceptionHandlerTrait.handleMicroServiceException
public function handleMicroServiceException(Exception $e) { // Determine the status code and message to return. if ($e instanceof HttpException) { return $this->handleHttpException($e); } elseif ($e instanceof ModelNotFoundException) { return $this->handleModelNotFoundException($e); } elseif ($e instanceof ValidationException) { return $this->handleValidationException($e); } else { return $this->handleGenericException($e); } }
php
public function handleMicroServiceException(Exception $e) { // Determine the status code and message to return. if ($e instanceof HttpException) { return $this->handleHttpException($e); } elseif ($e instanceof ModelNotFoundException) { return $this->handleModelNotFoundException($e); } elseif ($e instanceof ValidationException) { return $this->handleValidationException($e); } else { return $this->handleGenericException($e); } }
[ "public", "function", "handleMicroServiceException", "(", "Exception", "$", "e", ")", "{", "// Determine the status code and message to return.", "if", "(", "$", "e", "instanceof", "HttpException", ")", "{", "return", "$", "this", "->", "handleHttpException", "(", "$"...
Handle the exception and produce a valid JSON response. @param Exception $e @return \Illuminate\Http\JsonResponse
[ "Handle", "the", "exception", "and", "produce", "a", "valid", "JSON", "response", "." ]
8455b7c0d53f2d06bcbfd2854191bf0da1f263f5
https://github.com/LUSHDigital/microservice-core/blob/8455b7c0d53f2d06bcbfd2854191bf0da1f263f5/src/Traits/MicroServiceExceptionHandlerTrait.php#L59-L71
train