repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
Wedeto/Util
src/Hook.php
Hook.unsubscribe
public static function unsubscribe(string $hook, int $hook_reference) { $parts = explode(".", $hook); if (count($parts) < 2) throw new InvalidArgumentException("Hook name must consist of at least two parts"); if (!isset(self::$hooks[$hook])) throw new InvalidArgumentException("Hook was not set"); foreach (self::$hooks[$hook] as $idx => $hook_data) { if ($hook_data['ref'] === $hook_reference) { unset(self::$hooks[$hook][$idx]); return true; } } return false; }
php
public static function unsubscribe(string $hook, int $hook_reference) { $parts = explode(".", $hook); if (count($parts) < 2) throw new InvalidArgumentException("Hook name must consist of at least two parts"); if (!isset(self::$hooks[$hook])) throw new InvalidArgumentException("Hook was not set"); foreach (self::$hooks[$hook] as $idx => $hook_data) { if ($hook_data['ref'] === $hook_reference) { unset(self::$hooks[$hook][$idx]); return true; } } return false; }
[ "public", "static", "function", "unsubscribe", "(", "string", "$", "hook", ",", "int", "$", "hook_reference", ")", "{", "$", "parts", "=", "explode", "(", "\".\"", ",", "$", "hook", ")", ";", "if", "(", "count", "(", "$", "parts", ")", "<", "2", ")", "throw", "new", "InvalidArgumentException", "(", "\"Hook name must consist of at least two parts\"", ")", ";", "if", "(", "!", "isset", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", ")", ")", "throw", "new", "InvalidArgumentException", "(", "\"Hook was not set\"", ")", ";", "foreach", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", "as", "$", "idx", "=>", "$", "hook_data", ")", "{", "if", "(", "$", "hook_data", "[", "'ref'", "]", "===", "$", "hook_reference", ")", "{", "unset", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", "[", "$", "idx", "]", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Unsubscribe from a hook. @param string $hook The hook to unsubscribe from @param int The hook reference @return bool True when the hook was removed, false if it was not present
[ "Unsubscribe", "from", "a", "hook", "." ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Hook.php#L140-L158
train
Wedeto/Util
src/Hook.php
Hook.execute
public static function execute(string $hook, $params) { if (!($params instanceof Dictionary)) $params = TypedDictionary::wrap($params); if (isset(self::$in_progress[$hook])) throw new RecursionException("Recursion in hooks is not supported"); self::$in_progress[$hook] = true; // Count invoked hooks if (!isset(self::$counters[$hook])) self::$counters[$hook] = 1; else ++self::$counters[$hook]; // Add the name of the hook to the parameters if ($params instanceof TypedDictionary) $params->setType('hook', Type::STRING); $params['hook'] = $hook; // Check if the hook has any subscribers and if it hasn't been paused if (isset(self::$hooks[$hook]) && empty(self::$paused[$hook])) { // Call hooks and collect responses foreach (self::$hooks[$hook] as $subscriber) { $cb = $subscriber['callback']; try { $cb($params); } catch (HookInterrupted $e) { break; } catch (\Throwable $e) { $logger = self::getLogger(); if (!($logger instanceof NullLogger)) { // Log the error when a logger is available self::getLogger()->error("Callback to {0} throw an exception: {1}", [$hook, $e]); } else { // Otherwise debug. Doing this because otherwise exceptions go completely unnoticed Functions::debug($e); } } } } unset(self::$in_progress[$hook]); return $params; }
php
public static function execute(string $hook, $params) { if (!($params instanceof Dictionary)) $params = TypedDictionary::wrap($params); if (isset(self::$in_progress[$hook])) throw new RecursionException("Recursion in hooks is not supported"); self::$in_progress[$hook] = true; // Count invoked hooks if (!isset(self::$counters[$hook])) self::$counters[$hook] = 1; else ++self::$counters[$hook]; // Add the name of the hook to the parameters if ($params instanceof TypedDictionary) $params->setType('hook', Type::STRING); $params['hook'] = $hook; // Check if the hook has any subscribers and if it hasn't been paused if (isset(self::$hooks[$hook]) && empty(self::$paused[$hook])) { // Call hooks and collect responses foreach (self::$hooks[$hook] as $subscriber) { $cb = $subscriber['callback']; try { $cb($params); } catch (HookInterrupted $e) { break; } catch (\Throwable $e) { $logger = self::getLogger(); if (!($logger instanceof NullLogger)) { // Log the error when a logger is available self::getLogger()->error("Callback to {0} throw an exception: {1}", [$hook, $e]); } else { // Otherwise debug. Doing this because otherwise exceptions go completely unnoticed Functions::debug($e); } } } } unset(self::$in_progress[$hook]); return $params; }
[ "public", "static", "function", "execute", "(", "string", "$", "hook", ",", "$", "params", ")", "{", "if", "(", "!", "(", "$", "params", "instanceof", "Dictionary", ")", ")", "$", "params", "=", "TypedDictionary", "::", "wrap", "(", "$", "params", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "in_progress", "[", "$", "hook", "]", ")", ")", "throw", "new", "RecursionException", "(", "\"Recursion in hooks is not supported\"", ")", ";", "self", "::", "$", "in_progress", "[", "$", "hook", "]", "=", "true", ";", "// Count invoked hooks", "if", "(", "!", "isset", "(", "self", "::", "$", "counters", "[", "$", "hook", "]", ")", ")", "self", "::", "$", "counters", "[", "$", "hook", "]", "=", "1", ";", "else", "++", "self", "::", "$", "counters", "[", "$", "hook", "]", ";", "// Add the name of the hook to the parameters", "if", "(", "$", "params", "instanceof", "TypedDictionary", ")", "$", "params", "->", "setType", "(", "'hook'", ",", "Type", "::", "STRING", ")", ";", "$", "params", "[", "'hook'", "]", "=", "$", "hook", ";", "// Check if the hook has any subscribers and if it hasn't been paused", "if", "(", "isset", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", ")", "&&", "empty", "(", "self", "::", "$", "paused", "[", "$", "hook", "]", ")", ")", "{", "// Call hooks and collect responses", "foreach", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", "as", "$", "subscriber", ")", "{", "$", "cb", "=", "$", "subscriber", "[", "'callback'", "]", ";", "try", "{", "$", "cb", "(", "$", "params", ")", ";", "}", "catch", "(", "HookInterrupted", "$", "e", ")", "{", "break", ";", "}", "catch", "(", "\\", "Throwable", "$", "e", ")", "{", "$", "logger", "=", "self", "::", "getLogger", "(", ")", ";", "if", "(", "!", "(", "$", "logger", "instanceof", "NullLogger", ")", ")", "{", "// Log the error when a logger is available", "self", "::", "getLogger", "(", ")", "->", "error", "(", "\"Callback to {0} throw an exception: {1}\"", ",", "[", "$", "hook", ",", "$", "e", "]", ")", ";", "}", "else", "{", "// Otherwise debug. Doing this because otherwise exceptions go completely unnoticed", "Functions", "::", "debug", "(", "$", "e", ")", ";", "}", "}", "}", "}", "unset", "(", "self", "::", "$", "in_progress", "[", "$", "hook", "]", ")", ";", "return", "$", "params", ";", "}" ]
Call the specified hook with the provided parameters. @param array $params The parameters for the hook. You can pass in an array or any traversable object. If it is not yet an instance of Dictionary, it will be converted to a TypedDictionary to fix the types. @return Dictionary The collected responses of the hooks.
[ "Call", "the", "specified", "hook", "with", "the", "provided", "parameters", "." ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Hook.php#L197-L254
train
Wedeto/Util
src/Hook.php
Hook.getSubscribers
public static function getSubscribers(string $hook) { if (!isset(self::$hooks[$hook])) return array(); $subs = []; foreach (self::$hooks[$hook] as $h) $subs[] = $h['callback']; return $subs; }
php
public static function getSubscribers(string $hook) { if (!isset(self::$hooks[$hook])) return array(); $subs = []; foreach (self::$hooks[$hook] as $h) $subs[] = $h['callback']; return $subs; }
[ "public", "static", "function", "getSubscribers", "(", "string", "$", "hook", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", ")", ")", "return", "array", "(", ")", ";", "$", "subs", "=", "[", "]", ";", "foreach", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", "as", "$", "h", ")", "$", "subs", "[", "]", "=", "$", "h", "[", "'callback'", "]", ";", "return", "$", "subs", ";", "}" ]
Return the subscribers for the hook. @param string $hook The hook name @return array The list of subscribers to that hook
[ "Return", "the", "subscribers", "for", "the", "hook", "." ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Hook.php#L288-L298
train
Wedeto/Util
src/Hook.php
Hook.getExecuteCount
public static function getExecuteCount(string $hook) { return isset(self::$counters[$hook]) ? self::$counters[$hook] : 0; }
php
public static function getExecuteCount(string $hook) { return isset(self::$counters[$hook]) ? self::$counters[$hook] : 0; }
[ "public", "static", "function", "getExecuteCount", "(", "string", "$", "hook", ")", "{", "return", "isset", "(", "self", "::", "$", "counters", "[", "$", "hook", "]", ")", "?", "self", "::", "$", "counters", "[", "$", "hook", "]", ":", "0", ";", "}" ]
Return the amount of times the hook has been executed @param string $hook The hook name @return int The hook execution counter for this hook
[ "Return", "the", "amount", "of", "times", "the", "hook", "has", "been", "executed" ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Hook.php#L305-L308
train
Wedeto/Util
src/Hook.php
Hook.resetHook
public static function resetHook(string $hook) { if (isset(self::$hooks[$hook])) unset(self::$hooks[$hook]); if (isset(self::$counters[$hook])) unset(self::$counters[$hook]); if (isset(self::$paused[$hook])) unset(self::$paused[$hook]); }
php
public static function resetHook(string $hook) { if (isset(self::$hooks[$hook])) unset(self::$hooks[$hook]); if (isset(self::$counters[$hook])) unset(self::$counters[$hook]); if (isset(self::$paused[$hook])) unset(self::$paused[$hook]); }
[ "public", "static", "function", "resetHook", "(", "string", "$", "hook", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", ")", ")", "unset", "(", "self", "::", "$", "hooks", "[", "$", "hook", "]", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "counters", "[", "$", "hook", "]", ")", ")", "unset", "(", "self", "::", "$", "counters", "[", "$", "hook", "]", ")", ";", "if", "(", "isset", "(", "self", "::", "$", "paused", "[", "$", "hook", "]", ")", ")", "unset", "(", "self", "::", "$", "paused", "[", "$", "hook", "]", ")", ";", "}" ]
Forget about a hook entirely. This will remove all subscribers, reset the counter to 0 and remove the paused state for the hook. @param string $hook The hook to forget
[ "Forget", "about", "a", "hook", "entirely", ".", "This", "will", "remove", "all", "subscribers", "reset", "the", "counter", "to", "0", "and", "remove", "the", "paused", "state", "for", "the", "hook", "." ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Hook.php#L316-L324
train
Wedeto/Util
src/Hook.php
Hook.getRegisteredHooks
public static function getRegisteredHooks() { $subscribed = array_keys(self::$hooks); $called = array_keys(self::$counters); $all = array_merge($subscribed, $called); return array_unique($all); }
php
public static function getRegisteredHooks() { $subscribed = array_keys(self::$hooks); $called = array_keys(self::$counters); $all = array_merge($subscribed, $called); return array_unique($all); }
[ "public", "static", "function", "getRegisteredHooks", "(", ")", "{", "$", "subscribed", "=", "array_keys", "(", "self", "::", "$", "hooks", ")", ";", "$", "called", "=", "array_keys", "(", "self", "::", "$", "counters", ")", ";", "$", "all", "=", "array_merge", "(", "$", "subscribed", ",", "$", "called", ")", ";", "return", "array_unique", "(", "$", "all", ")", ";", "}" ]
Get all hooks that either have subscribers or have been executed @return array The list of hooks that have been called or subscribed to.
[ "Get", "all", "hooks", "that", "either", "have", "subscribers", "or", "have", "been", "executed" ]
0e080251bbaa8e7d91ae8d02eb79c029c976744a
https://github.com/Wedeto/Util/blob/0e080251bbaa8e7d91ae8d02eb79c029c976744a/src/Hook.php#L330-L336
train
bkstg/schedule-bundle
Controller/CalendarController.php
CalendarController.personalAction
public function personalAction( AuthorizationCheckerInterface $auth, Request $request ): Response { return new Response($this->templating->render( '@BkstgSchedule/Calendar/personal.html.twig' )); }
php
public function personalAction( AuthorizationCheckerInterface $auth, Request $request ): Response { return new Response($this->templating->render( '@BkstgSchedule/Calendar/personal.html.twig' )); }
[ "public", "function", "personalAction", "(", "AuthorizationCheckerInterface", "$", "auth", ",", "Request", "$", "request", ")", ":", "Response", "{", "return", "new", "Response", "(", "$", "this", "->", "templating", "->", "render", "(", "'@BkstgSchedule/Calendar/personal.html.twig'", ")", ")", ";", "}" ]
Show a calendar for a user. @param AuthorizationCheckerInterface $auth The authorization checker service. @param Request $request The current request. @throws NotFoundHttpException When the production does not exist. @throws AccessDeniedException When the user is not an editor. @return Response A response.
[ "Show", "a", "calendar", "for", "a", "user", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Controller/CalendarController.php#L112-L119
train
bkstg/schedule-bundle
Controller/CalendarController.php
CalendarController.prepareResult
private function prepareResult(array $events, Production $production = null): array { // Create array of events for calendar. $result = [ 'success' => 1, 'result' => [], ]; // Index schedules so we don't duplicate them. $schedules = []; foreach ($events as $event) { $event_production = (null !== $production) ? $production : $event->getGroups()[0]; if (null === $schedule = $event->getSchedule()) { // Add the event directly. $result['result'][] = [ 'icon' => 'calendar', 'id' => 'event:' . $event->getId(), 'title' => ((null === $production) ? $event_production->getName() . ': ' : '') . $event->getName(), 'url' => $this->url_generator->generate( 'bkstg_event_read', ['production_slug' => $event_production->getSlug(), 'id' => $event->getId()] ), 'class' => 'event-' . $event->getColour(), 'start' => $event->getStart()->format('U') * 1000, 'end' => $event->getEnd()->format('U') * 1000, ]; } elseif (!isset($schedules[$schedule->getId()])) { // Add the schedule instead of the event. $schedules[$schedule->getId()] = true; $result['result'][] = [ 'icon' => 'list', 'id' => 'schedule:' . $schedule->getId(), 'title' => ( (null === $production) ? $event_production->getName() . ': ' : '' ) . $schedule->getName(), 'url' => $this->url_generator->generate( 'bkstg_schedule_read', ['production_slug' => $event_production->getSlug(), 'id' => $schedule->getId()] ), 'class' => 'event-' . $schedule->getColour(), 'start' => $schedule->getStart()->format('U') * 1000, 'end' => $schedule->getEnd()->format('U') * 1000, ]; } } return $result; }
php
private function prepareResult(array $events, Production $production = null): array { // Create array of events for calendar. $result = [ 'success' => 1, 'result' => [], ]; // Index schedules so we don't duplicate them. $schedules = []; foreach ($events as $event) { $event_production = (null !== $production) ? $production : $event->getGroups()[0]; if (null === $schedule = $event->getSchedule()) { // Add the event directly. $result['result'][] = [ 'icon' => 'calendar', 'id' => 'event:' . $event->getId(), 'title' => ((null === $production) ? $event_production->getName() . ': ' : '') . $event->getName(), 'url' => $this->url_generator->generate( 'bkstg_event_read', ['production_slug' => $event_production->getSlug(), 'id' => $event->getId()] ), 'class' => 'event-' . $event->getColour(), 'start' => $event->getStart()->format('U') * 1000, 'end' => $event->getEnd()->format('U') * 1000, ]; } elseif (!isset($schedules[$schedule->getId()])) { // Add the schedule instead of the event. $schedules[$schedule->getId()] = true; $result['result'][] = [ 'icon' => 'list', 'id' => 'schedule:' . $schedule->getId(), 'title' => ( (null === $production) ? $event_production->getName() . ': ' : '' ) . $schedule->getName(), 'url' => $this->url_generator->generate( 'bkstg_schedule_read', ['production_slug' => $event_production->getSlug(), 'id' => $schedule->getId()] ), 'class' => 'event-' . $schedule->getColour(), 'start' => $schedule->getStart()->format('U') * 1000, 'end' => $schedule->getEnd()->format('U') * 1000, ]; } } return $result; }
[ "private", "function", "prepareResult", "(", "array", "$", "events", ",", "Production", "$", "production", "=", "null", ")", ":", "array", "{", "// Create array of events for calendar.", "$", "result", "=", "[", "'success'", "=>", "1", ",", "'result'", "=>", "[", "]", ",", "]", ";", "// Index schedules so we don't duplicate them.", "$", "schedules", "=", "[", "]", ";", "foreach", "(", "$", "events", "as", "$", "event", ")", "{", "$", "event_production", "=", "(", "null", "!==", "$", "production", ")", "?", "$", "production", ":", "$", "event", "->", "getGroups", "(", ")", "[", "0", "]", ";", "if", "(", "null", "===", "$", "schedule", "=", "$", "event", "->", "getSchedule", "(", ")", ")", "{", "// Add the event directly.", "$", "result", "[", "'result'", "]", "[", "]", "=", "[", "'icon'", "=>", "'calendar'", ",", "'id'", "=>", "'event:'", ".", "$", "event", "->", "getId", "(", ")", ",", "'title'", "=>", "(", "(", "null", "===", "$", "production", ")", "?", "$", "event_production", "->", "getName", "(", ")", ".", "': '", ":", "''", ")", ".", "$", "event", "->", "getName", "(", ")", ",", "'url'", "=>", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_event_read'", ",", "[", "'production_slug'", "=>", "$", "event_production", "->", "getSlug", "(", ")", ",", "'id'", "=>", "$", "event", "->", "getId", "(", ")", "]", ")", ",", "'class'", "=>", "'event-'", ".", "$", "event", "->", "getColour", "(", ")", ",", "'start'", "=>", "$", "event", "->", "getStart", "(", ")", "->", "format", "(", "'U'", ")", "*", "1000", ",", "'end'", "=>", "$", "event", "->", "getEnd", "(", ")", "->", "format", "(", "'U'", ")", "*", "1000", ",", "]", ";", "}", "elseif", "(", "!", "isset", "(", "$", "schedules", "[", "$", "schedule", "->", "getId", "(", ")", "]", ")", ")", "{", "// Add the schedule instead of the event.", "$", "schedules", "[", "$", "schedule", "->", "getId", "(", ")", "]", "=", "true", ";", "$", "result", "[", "'result'", "]", "[", "]", "=", "[", "'icon'", "=>", "'list'", ",", "'id'", "=>", "'schedule:'", ".", "$", "schedule", "->", "getId", "(", ")", ",", "'title'", "=>", "(", "(", "null", "===", "$", "production", ")", "?", "$", "event_production", "->", "getName", "(", ")", ".", "': '", ":", "''", ")", ".", "$", "schedule", "->", "getName", "(", ")", ",", "'url'", "=>", "$", "this", "->", "url_generator", "->", "generate", "(", "'bkstg_schedule_read'", ",", "[", "'production_slug'", "=>", "$", "event_production", "->", "getSlug", "(", ")", ",", "'id'", "=>", "$", "schedule", "->", "getId", "(", ")", "]", ")", ",", "'class'", "=>", "'event-'", ".", "$", "schedule", "->", "getColour", "(", ")", ",", "'start'", "=>", "$", "schedule", "->", "getStart", "(", ")", "->", "format", "(", "'U'", ")", "*", "1000", ",", "'end'", "=>", "$", "schedule", "->", "getEnd", "(", ")", "->", "format", "(", "'U'", ")", "*", "1000", ",", "]", ";", "}", "}", "return", "$", "result", ";", "}" ]
Helper function to prepare results for the calendar. @param array $events The events to return. @param Production $production The production for these events. @return array The formatted events.
[ "Helper", "function", "to", "prepare", "results", "for", "the", "calendar", "." ]
e64ac897aa7b28bc48319470d65de13cd4788afe
https://github.com/bkstg/schedule-bundle/blob/e64ac897aa7b28bc48319470d65de13cd4788afe/Controller/CalendarController.php#L158-L205
train
black-lamp/blcms-cart
frontend/controllers/CartController.php
CartController.actionAdd
public function actionAdd() { $model = new CartForm(); $post = \Yii::$app->request->post(); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $additionalProductForm = []; $productAdditionalProducts = ProductAdditionalProduct::find()->where(['product_id' => $model->productId]) ->indexBy('additional_product_id')->all(); foreach ($productAdditionalProducts as $key => $productAdditionalProduct) { $additionalProductForm[$key] = new AdditionalProductForm(); } if (!empty($productAdditionalProducts)) { Model::loadMultiple($additionalProductForm, $post); Model::validateMultiple($additionalProductForm); } Module::$cart->add($model->productId, $model->count, json_encode($model->attribute_value_id), $additionalProductForm, $model->combinationId ); if (\Yii::$app->request->isAjax) { $data = [ 'orderCounterValue' => Module::$cart->getOrderItemsCount(), 'totalCost' => \Yii::$app->formatter->asCurrency(Module::$cart->getTotalCost()) ]; Yii::$app->response->format = Response::FORMAT_JSON; return Json::encode($data); } Yii::$app->getSession()->setFlash('success', Yii::t('cart', 'You have successfully added this product to cart') ); } else { Yii::$app->log->logger->log($model->errors, Logger::LEVEL_ERROR, 'application.shop.product'); Yii::$app->session->setFlash('error', Yii::t('cart', 'An error occurred while adding a product, please try again later') ); } } if (\Yii::$app->request->isAjax) { return false; } return $this->redirect(Yii::$app->request->referrer); }
php
public function actionAdd() { $model = new CartForm(); $post = \Yii::$app->request->post(); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { $additionalProductForm = []; $productAdditionalProducts = ProductAdditionalProduct::find()->where(['product_id' => $model->productId]) ->indexBy('additional_product_id')->all(); foreach ($productAdditionalProducts as $key => $productAdditionalProduct) { $additionalProductForm[$key] = new AdditionalProductForm(); } if (!empty($productAdditionalProducts)) { Model::loadMultiple($additionalProductForm, $post); Model::validateMultiple($additionalProductForm); } Module::$cart->add($model->productId, $model->count, json_encode($model->attribute_value_id), $additionalProductForm, $model->combinationId ); if (\Yii::$app->request->isAjax) { $data = [ 'orderCounterValue' => Module::$cart->getOrderItemsCount(), 'totalCost' => \Yii::$app->formatter->asCurrency(Module::$cart->getTotalCost()) ]; Yii::$app->response->format = Response::FORMAT_JSON; return Json::encode($data); } Yii::$app->getSession()->setFlash('success', Yii::t('cart', 'You have successfully added this product to cart') ); } else { Yii::$app->log->logger->log($model->errors, Logger::LEVEL_ERROR, 'application.shop.product'); Yii::$app->session->setFlash('error', Yii::t('cart', 'An error occurred while adding a product, please try again later') ); } } if (\Yii::$app->request->isAjax) { return false; } return $this->redirect(Yii::$app->request->referrer); }
[ "public", "function", "actionAdd", "(", ")", "{", "$", "model", "=", "new", "CartForm", "(", ")", ";", "$", "post", "=", "\\", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ";", "if", "(", "$", "model", "->", "load", "(", "Yii", "::", "$", "app", "->", "request", "->", "post", "(", ")", ")", ")", "{", "if", "(", "$", "model", "->", "validate", "(", ")", ")", "{", "$", "additionalProductForm", "=", "[", "]", ";", "$", "productAdditionalProducts", "=", "ProductAdditionalProduct", "::", "find", "(", ")", "->", "where", "(", "[", "'product_id'", "=>", "$", "model", "->", "productId", "]", ")", "->", "indexBy", "(", "'additional_product_id'", ")", "->", "all", "(", ")", ";", "foreach", "(", "$", "productAdditionalProducts", "as", "$", "key", "=>", "$", "productAdditionalProduct", ")", "{", "$", "additionalProductForm", "[", "$", "key", "]", "=", "new", "AdditionalProductForm", "(", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "productAdditionalProducts", ")", ")", "{", "Model", "::", "loadMultiple", "(", "$", "additionalProductForm", ",", "$", "post", ")", ";", "Model", "::", "validateMultiple", "(", "$", "additionalProductForm", ")", ";", "}", "Module", "::", "$", "cart", "->", "add", "(", "$", "model", "->", "productId", ",", "$", "model", "->", "count", ",", "json_encode", "(", "$", "model", "->", "attribute_value_id", ")", ",", "$", "additionalProductForm", ",", "$", "model", "->", "combinationId", ")", ";", "if", "(", "\\", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "$", "data", "=", "[", "'orderCounterValue'", "=>", "Module", "::", "$", "cart", "->", "getOrderItemsCount", "(", ")", ",", "'totalCost'", "=>", "\\", "Yii", "::", "$", "app", "->", "formatter", "->", "asCurrency", "(", "Module", "::", "$", "cart", "->", "getTotalCost", "(", ")", ")", "]", ";", "Yii", "::", "$", "app", "->", "response", "->", "format", "=", "Response", "::", "FORMAT_JSON", ";", "return", "Json", "::", "encode", "(", "$", "data", ")", ";", "}", "Yii", "::", "$", "app", "->", "getSession", "(", ")", "->", "setFlash", "(", "'success'", ",", "Yii", "::", "t", "(", "'cart'", ",", "'You have successfully added this product to cart'", ")", ")", ";", "}", "else", "{", "Yii", "::", "$", "app", "->", "log", "->", "logger", "->", "log", "(", "$", "model", "->", "errors", ",", "Logger", "::", "LEVEL_ERROR", ",", "'application.shop.product'", ")", ";", "Yii", "::", "$", "app", "->", "session", "->", "setFlash", "(", "'error'", ",", "Yii", "::", "t", "(", "'cart'", ",", "'An error occurred while adding a product, please try again later'", ")", ")", ";", "}", "}", "if", "(", "\\", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "redirect", "(", "Yii", "::", "$", "app", "->", "request", "->", "referrer", ")", ";", "}" ]
Adds product to cart @return array|bool|\yii\web\Response
[ "Adds", "product", "to", "cart" ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/frontend/controllers/CartController.php#L55-L105
train
black-lamp/blcms-cart
frontend/controllers/CartController.php
CartController.actionShow
public function actionShow() { $this->registerStaticSeoData(); $cart = \Yii::$app->cart; $items = $cart->getOrderItems(); /*EMPTY CART*/ if (empty($items)) { return $this->render('empty-cart'); } /*CART IS NOT EMPTY*/ else { /*FOR GUEST*/ if (\Yii::$app->user->isGuest) { $user = new User(); $profile = new Profile(); $address = new UserAddress(); $order = new Order(); $products = []; $orderProductViewModels = []; foreach ($items as $item) { $product = Product::findOne($item['id']); if (!empty($product)) { $product->count = $item['count']; $product->combinationId = $item['combinationId']; if (!empty($item['additionalProducts'])) { foreach ($item['additionalProducts'] as $additionalProduct) { $product->additionalProducts[] = [ 'product' => Product::findOne($additionalProduct['productId']), 'number' => $additionalProduct['number'] ]; } } $products[] = $product; $orderProductViewModels[] = new OrderProductViewModel([ 'product_id' => $item['id'], 'combination_id' => $item['combinationId'], 'count' => $item['count'], ]); } } $view = 'show-for-guest'; } /*FOR USER*/ else { $user = User::findOne(\Yii::$app->user->id) ?? new User(); $profile = Profile::find()->where(['user_id' => \Yii::$app->user->id])->one() ?? new Profile(); $address = new UserAddress(); $order = Order::find() ->where(['user_id' => \Yii::$app->user->id, 'status' => OrderStatus::STATUS_INCOMPLETE]) ->one() ?? new Order(); $products = OrderProduct::find()->where(['order_id' => $order->id])->all(); $orderProductViewModels = $products; $view = 'show'; } return $this->render($view, [ 'products' => $products, 'order' => $order, 'profile' => $profile, 'user' => $user, 'address' => $address, 'orderProductViewModels' => $orderProductViewModels ]); } }
php
public function actionShow() { $this->registerStaticSeoData(); $cart = \Yii::$app->cart; $items = $cart->getOrderItems(); /*EMPTY CART*/ if (empty($items)) { return $this->render('empty-cart'); } /*CART IS NOT EMPTY*/ else { /*FOR GUEST*/ if (\Yii::$app->user->isGuest) { $user = new User(); $profile = new Profile(); $address = new UserAddress(); $order = new Order(); $products = []; $orderProductViewModels = []; foreach ($items as $item) { $product = Product::findOne($item['id']); if (!empty($product)) { $product->count = $item['count']; $product->combinationId = $item['combinationId']; if (!empty($item['additionalProducts'])) { foreach ($item['additionalProducts'] as $additionalProduct) { $product->additionalProducts[] = [ 'product' => Product::findOne($additionalProduct['productId']), 'number' => $additionalProduct['number'] ]; } } $products[] = $product; $orderProductViewModels[] = new OrderProductViewModel([ 'product_id' => $item['id'], 'combination_id' => $item['combinationId'], 'count' => $item['count'], ]); } } $view = 'show-for-guest'; } /*FOR USER*/ else { $user = User::findOne(\Yii::$app->user->id) ?? new User(); $profile = Profile::find()->where(['user_id' => \Yii::$app->user->id])->one() ?? new Profile(); $address = new UserAddress(); $order = Order::find() ->where(['user_id' => \Yii::$app->user->id, 'status' => OrderStatus::STATUS_INCOMPLETE]) ->one() ?? new Order(); $products = OrderProduct::find()->where(['order_id' => $order->id])->all(); $orderProductViewModels = $products; $view = 'show'; } return $this->render($view, [ 'products' => $products, 'order' => $order, 'profile' => $profile, 'user' => $user, 'address' => $address, 'orderProductViewModels' => $orderProductViewModels ]); } }
[ "public", "function", "actionShow", "(", ")", "{", "$", "this", "->", "registerStaticSeoData", "(", ")", ";", "$", "cart", "=", "\\", "Yii", "::", "$", "app", "->", "cart", ";", "$", "items", "=", "$", "cart", "->", "getOrderItems", "(", ")", ";", "/*EMPTY CART*/", "if", "(", "empty", "(", "$", "items", ")", ")", "{", "return", "$", "this", "->", "render", "(", "'empty-cart'", ")", ";", "}", "/*CART IS NOT EMPTY*/", "else", "{", "/*FOR GUEST*/", "if", "(", "\\", "Yii", "::", "$", "app", "->", "user", "->", "isGuest", ")", "{", "$", "user", "=", "new", "User", "(", ")", ";", "$", "profile", "=", "new", "Profile", "(", ")", ";", "$", "address", "=", "new", "UserAddress", "(", ")", ";", "$", "order", "=", "new", "Order", "(", ")", ";", "$", "products", "=", "[", "]", ";", "$", "orderProductViewModels", "=", "[", "]", ";", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "product", "=", "Product", "::", "findOne", "(", "$", "item", "[", "'id'", "]", ")", ";", "if", "(", "!", "empty", "(", "$", "product", ")", ")", "{", "$", "product", "->", "count", "=", "$", "item", "[", "'count'", "]", ";", "$", "product", "->", "combinationId", "=", "$", "item", "[", "'combinationId'", "]", ";", "if", "(", "!", "empty", "(", "$", "item", "[", "'additionalProducts'", "]", ")", ")", "{", "foreach", "(", "$", "item", "[", "'additionalProducts'", "]", "as", "$", "additionalProduct", ")", "{", "$", "product", "->", "additionalProducts", "[", "]", "=", "[", "'product'", "=>", "Product", "::", "findOne", "(", "$", "additionalProduct", "[", "'productId'", "]", ")", ",", "'number'", "=>", "$", "additionalProduct", "[", "'number'", "]", "]", ";", "}", "}", "$", "products", "[", "]", "=", "$", "product", ";", "$", "orderProductViewModels", "[", "]", "=", "new", "OrderProductViewModel", "(", "[", "'product_id'", "=>", "$", "item", "[", "'id'", "]", ",", "'combination_id'", "=>", "$", "item", "[", "'combinationId'", "]", ",", "'count'", "=>", "$", "item", "[", "'count'", "]", ",", "]", ")", ";", "}", "}", "$", "view", "=", "'show-for-guest'", ";", "}", "/*FOR USER*/", "else", "{", "$", "user", "=", "User", "::", "findOne", "(", "\\", "Yii", "::", "$", "app", "->", "user", "->", "id", ")", "??", "new", "User", "(", ")", ";", "$", "profile", "=", "Profile", "::", "find", "(", ")", "->", "where", "(", "[", "'user_id'", "=>", "\\", "Yii", "::", "$", "app", "->", "user", "->", "id", "]", ")", "->", "one", "(", ")", "??", "new", "Profile", "(", ")", ";", "$", "address", "=", "new", "UserAddress", "(", ")", ";", "$", "order", "=", "Order", "::", "find", "(", ")", "->", "where", "(", "[", "'user_id'", "=>", "\\", "Yii", "::", "$", "app", "->", "user", "->", "id", ",", "'status'", "=>", "OrderStatus", "::", "STATUS_INCOMPLETE", "]", ")", "->", "one", "(", ")", "??", "new", "Order", "(", ")", ";", "$", "products", "=", "OrderProduct", "::", "find", "(", ")", "->", "where", "(", "[", "'order_id'", "=>", "$", "order", "->", "id", "]", ")", "->", "all", "(", ")", ";", "$", "orderProductViewModels", "=", "$", "products", ";", "$", "view", "=", "'show'", ";", "}", "return", "$", "this", "->", "render", "(", "$", "view", ",", "[", "'products'", "=>", "$", "products", ",", "'order'", "=>", "$", "order", ",", "'profile'", "=>", "$", "profile", ",", "'user'", "=>", "$", "user", ",", "'address'", "=>", "$", "address", ",", "'orderProductViewModels'", "=>", "$", "orderProductViewModels", "]", ")", ";", "}", "}" ]
Renders cart view with all order products. @return mixed
[ "Renders", "cart", "view", "with", "all", "order", "products", "." ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/frontend/controllers/CartController.php#L111-L176
train
black-lamp/blcms-cart
frontend/controllers/CartController.php
CartController.actionRemove
public function actionRemove(int $productId, int $combinationId = null) { \Yii::$app->cart->removeItem($productId, $combinationId); return $this->redirect(\Yii::$app->request->referrer); }
php
public function actionRemove(int $productId, int $combinationId = null) { \Yii::$app->cart->removeItem($productId, $combinationId); return $this->redirect(\Yii::$app->request->referrer); }
[ "public", "function", "actionRemove", "(", "int", "$", "productId", ",", "int", "$", "combinationId", "=", "null", ")", "{", "\\", "Yii", "::", "$", "app", "->", "cart", "->", "removeItem", "(", "$", "productId", ",", "$", "combinationId", ")", ";", "return", "$", "this", "->", "redirect", "(", "\\", "Yii", "::", "$", "app", "->", "request", "->", "referrer", ")", ";", "}" ]
Removes product from cart @param int $productId @param int $combinationId @return \yii\web\Response
[ "Removes", "product", "from", "cart" ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/frontend/controllers/CartController.php#L184-L188
train
black-lamp/blcms-cart
frontend/controllers/CartController.php
CartController.actionClear
public function actionClear() { \Yii::$app->cart->clearCart(); return $this->redirect(\Yii::$app->request->referrer); }
php
public function actionClear() { \Yii::$app->cart->clearCart(); return $this->redirect(\Yii::$app->request->referrer); }
[ "public", "function", "actionClear", "(", ")", "{", "\\", "Yii", "::", "$", "app", "->", "cart", "->", "clearCart", "(", ")", ";", "return", "$", "this", "->", "redirect", "(", "\\", "Yii", "::", "$", "app", "->", "request", "->", "referrer", ")", ";", "}" ]
Removes all products from cart @return \yii\web\Response
[ "Removes", "all", "products", "from", "cart" ]
314796eecae3ca4ed5fecfdc0231a738af50eba7
https://github.com/black-lamp/blcms-cart/blob/314796eecae3ca4ed5fecfdc0231a738af50eba7/frontend/controllers/CartController.php#L194-L198
train
koolkode/security
src/SecurityUtil.php
SecurityUtil.timingSafeEquals
public static function timingSafeEquals($safe, $user) { // Use builtin has comparison function available when running on PHP 5.6+ if(function_exists('hash_equals')) { return hash_equals((string)$safe, (string)$user); } $safe .= chr(0); $user .= chr(0); $safeLen = strlen($safe); $userLen = strlen($user); $result = $safeLen - $userLen; for($i = 0; $i < $userLen; $i++) { $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i])); } return $result === 0; }
php
public static function timingSafeEquals($safe, $user) { // Use builtin has comparison function available when running on PHP 5.6+ if(function_exists('hash_equals')) { return hash_equals((string)$safe, (string)$user); } $safe .= chr(0); $user .= chr(0); $safeLen = strlen($safe); $userLen = strlen($user); $result = $safeLen - $userLen; for($i = 0; $i < $userLen; $i++) { $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i])); } return $result === 0; }
[ "public", "static", "function", "timingSafeEquals", "(", "$", "safe", ",", "$", "user", ")", "{", "// Use builtin has comparison function available when running on PHP 5.6+", "if", "(", "function_exists", "(", "'hash_equals'", ")", ")", "{", "return", "hash_equals", "(", "(", "string", ")", "$", "safe", ",", "(", "string", ")", "$", "user", ")", ";", "}", "$", "safe", ".=", "chr", "(", "0", ")", ";", "$", "user", ".=", "chr", "(", "0", ")", ";", "$", "safeLen", "=", "strlen", "(", "$", "safe", ")", ";", "$", "userLen", "=", "strlen", "(", "$", "user", ")", ";", "$", "result", "=", "$", "safeLen", "-", "$", "userLen", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "userLen", ";", "$", "i", "++", ")", "{", "$", "result", "|=", "(", "ord", "(", "$", "safe", "[", "$", "i", "%", "$", "safeLen", "]", ")", "^", "ord", "(", "$", "user", "[", "$", "i", "]", ")", ")", ";", "}", "return", "$", "result", "===", "0", ";", "}" ]
Perform a timing-safe string comparison. @param string $safe Safe string value. @param string $user User-supplied value for comparsion. @return boolean
[ "Perform", "a", "timing", "-", "safe", "string", "comparison", "." ]
d3d8d42392f520754847d29b6df19aaa38c79e8e
https://github.com/koolkode/security/blob/d3d8d42392f520754847d29b6df19aaa38c79e8e/src/SecurityUtil.php#L26-L47
train
CismonX/Acast-CronService
src/CronService.php
CronService.loadTasks
function loadTasks(string $namespace, $tasks) { if (!is_array($tasks)) $tasks = [$tasks]; foreach ($tasks as &$task) { $class_name = $namespace.$task; if (!is_subclass_of($class_name, '\\Acast\\CronService\\TaskInterface')) { Console::warning("Invalid class \"$task\"."); continue; } $this->addTask($class_name::init()); } }
php
function loadTasks(string $namespace, $tasks) { if (!is_array($tasks)) $tasks = [$tasks]; foreach ($tasks as &$task) { $class_name = $namespace.$task; if (!is_subclass_of($class_name, '\\Acast\\CronService\\TaskInterface')) { Console::warning("Invalid class \"$task\"."); continue; } $this->addTask($class_name::init()); } }
[ "function", "loadTasks", "(", "string", "$", "namespace", ",", "$", "tasks", ")", "{", "if", "(", "!", "is_array", "(", "$", "tasks", ")", ")", "$", "tasks", "=", "[", "$", "tasks", "]", ";", "foreach", "(", "$", "tasks", "as", "&", "$", "task", ")", "{", "$", "class_name", "=", "$", "namespace", ".", "$", "task", ";", "if", "(", "!", "is_subclass_of", "(", "$", "class_name", ",", "'\\\\Acast\\\\CronService\\\\TaskInterface'", ")", ")", "{", "Console", "::", "warning", "(", "\"Invalid class \\\"$task\\\".\"", ")", ";", "continue", ";", "}", "$", "this", "->", "addTask", "(", "$", "class_name", "::", "init", "(", ")", ")", ";", "}", "}" ]
Load tasks by namespace and class name. @param string $namespace @param mixed $tasks
[ "Load", "tasks", "by", "namespace", "and", "class", "name", "." ]
a1e48dfb391376421924a91c243ff5756c35c333
https://github.com/CismonX/Acast-CronService/blob/a1e48dfb391376421924a91c243ff5756c35c333/src/CronService.php#L44-L55
train
CismonX/Acast-CronService
src/CronService.php
CronService.addTask
protected function addTask(TaskInterface $instance) { $this->_task_list[] = $instance; $this->_cron->add( $instance->name, $instance->time, [$instance, 'execute'], $instance->params, $instance->persistent ); }
php
protected function addTask(TaskInterface $instance) { $this->_task_list[] = $instance; $this->_cron->add( $instance->name, $instance->time, [$instance, 'execute'], $instance->params, $instance->persistent ); }
[ "protected", "function", "addTask", "(", "TaskInterface", "$", "instance", ")", "{", "$", "this", "->", "_task_list", "[", "]", "=", "$", "instance", ";", "$", "this", "->", "_cron", "->", "add", "(", "$", "instance", "->", "name", ",", "$", "instance", "->", "time", ",", "[", "$", "instance", ",", "'execute'", "]", ",", "$", "instance", "->", "params", ",", "$", "instance", "->", "persistent", ")", ";", "}" ]
Add a task to cron service. @param TaskInterface $instance
[ "Add", "a", "task", "to", "cron", "service", "." ]
a1e48dfb391376421924a91c243ff5756c35c333
https://github.com/CismonX/Acast-CronService/blob/a1e48dfb391376421924a91c243ff5756c35c333/src/CronService.php#L61-L70
train
CismonX/Acast-CronService
src/CronService.php
CronService.destroy
function destroy() { foreach ($this->_task_list as $task) $task->destroy(); Cron::destroy($this->_name); }
php
function destroy() { foreach ($this->_task_list as $task) $task->destroy(); Cron::destroy($this->_name); }
[ "function", "destroy", "(", ")", "{", "foreach", "(", "$", "this", "->", "_task_list", "as", "$", "task", ")", "$", "task", "->", "destroy", "(", ")", ";", "Cron", "::", "destroy", "(", "$", "this", "->", "_name", ")", ";", "}" ]
Destroy cron service.
[ "Destroy", "cron", "service", "." ]
a1e48dfb391376421924a91c243ff5756c35c333
https://github.com/CismonX/Acast-CronService/blob/a1e48dfb391376421924a91c243ff5756c35c333/src/CronService.php#L74-L78
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/AbstractSystemValidator.php
AbstractSystemValidator.add
protected function add(ModelObject $obj) { // Check that all required fields exist. $this->getErrors()->validateModelObject($obj); if ($this->dao->slugExists($obj->Slug)) $this->errors->reject("The slug for this ".get_class($obj)." record is already in use."); }
php
protected function add(ModelObject $obj) { // Check that all required fields exist. $this->getErrors()->validateModelObject($obj); if ($this->dao->slugExists($obj->Slug)) $this->errors->reject("The slug for this ".get_class($obj)." record is already in use."); }
[ "protected", "function", "add", "(", "ModelObject", "$", "obj", ")", "{", "// Check that all required fields exist.", "$", "this", "->", "getErrors", "(", ")", "->", "validateModelObject", "(", "$", "obj", ")", ";", "if", "(", "$", "this", "->", "dao", "->", "slugExists", "(", "$", "obj", "->", "Slug", ")", ")", "$", "this", "->", "errors", "->", "reject", "(", "\"The slug for this \"", ".", "get_class", "(", "$", "obj", ")", ".", "\" record is already in use.\"", ")", ";", "}" ]
Validates the model object and ensures that slug doesn't exist anywhere. @param ModelObject $obj The object to validate @return void
[ "Validates", "the", "model", "object", "and", "ensures", "that", "slug", "doesn", "t", "exist", "anywhere", "." ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/AbstractSystemValidator.php#L49-L56
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/AbstractSystemValidator.php
AbstractSystemValidator.edit
protected function edit(ModelObject $obj) { if ($obj->{$obj->getPrimaryKey()} == null) $this->errors->reject("{$obj->getPrimaryKey()} is required to edit.")->throwOnError(); if ($this->dao->getByID($obj->{$obj->getPrimaryKey()}) == false) $this->getErrors()->reject("Record not found for ID: " . $obj->{$obj->getPrimaryKey()})->throwOnError(); if ($this->dao->slugExists($obj->Slug, $obj->{$obj->getPrimaryKey()})) $this->errors->reject("The slug for this ".get_class($obj)." record is already in use.")->throwOnError(); $this->errors->validateModelObject($obj); }
php
protected function edit(ModelObject $obj) { if ($obj->{$obj->getPrimaryKey()} == null) $this->errors->reject("{$obj->getPrimaryKey()} is required to edit.")->throwOnError(); if ($this->dao->getByID($obj->{$obj->getPrimaryKey()}) == false) $this->getErrors()->reject("Record not found for ID: " . $obj->{$obj->getPrimaryKey()})->throwOnError(); if ($this->dao->slugExists($obj->Slug, $obj->{$obj->getPrimaryKey()})) $this->errors->reject("The slug for this ".get_class($obj)." record is already in use.")->throwOnError(); $this->errors->validateModelObject($obj); }
[ "protected", "function", "edit", "(", "ModelObject", "$", "obj", ")", "{", "if", "(", "$", "obj", "->", "{", "$", "obj", "->", "getPrimaryKey", "(", ")", "}", "==", "null", ")", "$", "this", "->", "errors", "->", "reject", "(", "\"{$obj->getPrimaryKey()} is required to edit.\"", ")", "->", "throwOnError", "(", ")", ";", "if", "(", "$", "this", "->", "dao", "->", "getByID", "(", "$", "obj", "->", "{", "$", "obj", "->", "getPrimaryKey", "(", ")", "}", ")", "==", "false", ")", "$", "this", "->", "getErrors", "(", ")", "->", "reject", "(", "\"Record not found for ID: \"", ".", "$", "obj", "->", "{", "$", "obj", "->", "getPrimaryKey", "(", ")", "}", ")", "->", "throwOnError", "(", ")", ";", "if", "(", "$", "this", "->", "dao", "->", "slugExists", "(", "$", "obj", "->", "Slug", ",", "$", "obj", "->", "{", "$", "obj", "->", "getPrimaryKey", "(", ")", "}", ")", ")", "$", "this", "->", "errors", "->", "reject", "(", "\"The slug for this \"", ".", "get_class", "(", "$", "obj", ")", ".", "\" record is already in use.\"", ")", "->", "throwOnError", "(", ")", ";", "$", "this", "->", "errors", "->", "validateModelObject", "(", "$", "obj", ")", ";", "}" ]
Ensures we have a valid model object, and that it's slug is not in conflict, then validates the object @param ModelObject $obj The object to validate @return void
[ "Ensures", "we", "have", "a", "valid", "model", "object", "and", "that", "it", "s", "slug", "is", "not", "in", "conflict", "then", "validates", "the", "object" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/AbstractSystemValidator.php#L66-L78
train
wb-crowdfusion/crowdfusion
system/core/classes/systemdb/AbstractSystemValidator.php
AbstractSystemValidator.delete
protected function delete($slug) { if ($this->dao->getBySlug($slug) == false) $this->getErrors()->reject('Record not found for slug:' . $slug); }
php
protected function delete($slug) { if ($this->dao->getBySlug($slug) == false) $this->getErrors()->reject('Record not found for slug:' . $slug); }
[ "protected", "function", "delete", "(", "$", "slug", ")", "{", "if", "(", "$", "this", "->", "dao", "->", "getBySlug", "(", "$", "slug", ")", "==", "false", ")", "$", "this", "->", "getErrors", "(", ")", "->", "reject", "(", "'Record not found for slug:'", ".", "$", "slug", ")", ";", "}" ]
Ensures that the record exists for the given slug @param string $slug The slug to lookup @return void
[ "Ensures", "that", "the", "record", "exists", "for", "the", "given", "slug" ]
8cad7988f046a6fefbed07d026cb4ae6706c1217
https://github.com/wb-crowdfusion/crowdfusion/blob/8cad7988f046a6fefbed07d026cb4ae6706c1217/system/core/classes/systemdb/AbstractSystemValidator.php#L87-L91
train
zwilias/beanie
src/Server/Socket.php
Socket.readLine
public function readLine($endOfLine = Server::EOL) { $this->ensureConnected(); $buffer = ''; do { $buffer .= $this->read(self::MAX_SINGLE_RESPONSE_LENGTH); $eolPosition = strpos($buffer, $endOfLine); } while ($eolPosition === false); $this->readBuffer = substr($buffer, $eolPosition + strlen($endOfLine)); return substr($buffer, 0, $eolPosition + strlen($endOfLine)); }
php
public function readLine($endOfLine = Server::EOL) { $this->ensureConnected(); $buffer = ''; do { $buffer .= $this->read(self::MAX_SINGLE_RESPONSE_LENGTH); $eolPosition = strpos($buffer, $endOfLine); } while ($eolPosition === false); $this->readBuffer = substr($buffer, $eolPosition + strlen($endOfLine)); return substr($buffer, 0, $eolPosition + strlen($endOfLine)); }
[ "public", "function", "readLine", "(", "$", "endOfLine", "=", "Server", "::", "EOL", ")", "{", "$", "this", "->", "ensureConnected", "(", ")", ";", "$", "buffer", "=", "''", ";", "do", "{", "$", "buffer", ".=", "$", "this", "->", "read", "(", "self", "::", "MAX_SINGLE_RESPONSE_LENGTH", ")", ";", "$", "eolPosition", "=", "strpos", "(", "$", "buffer", ",", "$", "endOfLine", ")", ";", "}", "while", "(", "$", "eolPosition", "===", "false", ")", ";", "$", "this", "->", "readBuffer", "=", "substr", "(", "$", "buffer", ",", "$", "eolPosition", "+", "strlen", "(", "$", "endOfLine", ")", ")", ";", "return", "substr", "(", "$", "buffer", ",", "0", ",", "$", "eolPosition", "+", "strlen", "(", "$", "endOfLine", ")", ")", ";", "}" ]
Reads data from the connected socket in chunks of MAX_SINGLE_RESPONSE_LENGTH The MAX_SINGLE_RESPONSE_LENGTH should always capture at least the first line of a response, assuming the longest possible response is the USING <tubename>\r\n response, which could be up to 208 bytes in length, for any valid <tubename>. As a result, this function will, in reality, read some overflow of data for any response containing data. This data is saved in a read-buffer, which `readData()` will read from first. @see readData() @param string $endOfLine @return string @throws SocketException
[ "Reads", "data", "from", "the", "connected", "socket", "in", "chunks", "of", "MAX_SINGLE_RESPONSE_LENGTH" ]
8f0993a163c73ca0dfe1d0b3779fb188ff9cc304
https://github.com/zwilias/beanie/blob/8f0993a163c73ca0dfe1d0b3779fb188ff9cc304/src/Server/Socket.php#L86-L99
train
kambalabs/KmbCache
src/KmbCache/Service/MainCacheManager.php
MainCacheManager.getCacheManager
public function getCacheManager($key) { return array_key_exists($key, $this->cacheManagers) ? $this->cacheManagers[$key] : null; }
php
public function getCacheManager($key) { return array_key_exists($key, $this->cacheManagers) ? $this->cacheManagers[$key] : null; }
[ "public", "function", "getCacheManager", "(", "$", "key", ")", "{", "return", "array_key_exists", "(", "$", "key", ",", "$", "this", "->", "cacheManagers", ")", "?", "$", "this", "->", "cacheManagers", "[", "$", "key", "]", ":", "null", ";", "}" ]
Get CacheManager. @param string $key @return \KmbCache\Service\AbstractCacheManager
[ "Get", "CacheManager", "." ]
9865ccde8f17fa5ad0ace103e50c164559a389f0
https://github.com/kambalabs/KmbCache/blob/9865ccde8f17fa5ad0ace103e50c164559a389f0/src/KmbCache/Service/MainCacheManager.php#L96-L99
train
shrink0r/monatic
src/Maybe.php
Maybe.get
public function get(callable $codeBlock = null) { if (is_callable($codeBlock)) { return call_user_func($codeBlock, $this->value); } else { return $this->value; } }
php
public function get(callable $codeBlock = null) { if (is_callable($codeBlock)) { return call_user_func($codeBlock, $this->value); } else { return $this->value; } }
[ "public", "function", "get", "(", "callable", "$", "codeBlock", "=", "null", ")", "{", "if", "(", "is_callable", "(", "$", "codeBlock", ")", ")", "{", "return", "call_user_func", "(", "$", "codeBlock", ",", "$", "this", "->", "value", ")", ";", "}", "else", "{", "return", "$", "this", "->", "value", ";", "}", "}" ]
Returns the monad's value and applies an optional code-block before returning it. @param callable $codeBlock @return mixed
[ "Returns", "the", "monad", "s", "value", "and", "applies", "an", "optional", "code", "-", "block", "before", "returning", "it", "." ]
f39b8b2ef68a397d31d844341487412b335fd107
https://github.com/shrink0r/monatic/blob/f39b8b2ef68a397d31d844341487412b335fd107/src/Maybe.php#L41-L48
train
shrink0r/monatic
src/Maybe.php
Maybe.bind
public function bind(callable $codeBlock) { if ($this->value === null) { return new None; } else { return static::unit(call_user_func($codeBlock, $this->value)); } }
php
public function bind(callable $codeBlock) { if ($this->value === null) { return new None; } else { return static::unit(call_user_func($codeBlock, $this->value)); } }
[ "public", "function", "bind", "(", "callable", "$", "codeBlock", ")", "{", "if", "(", "$", "this", "->", "value", "===", "null", ")", "{", "return", "new", "None", ";", "}", "else", "{", "return", "static", "::", "unit", "(", "call_user_func", "(", "$", "codeBlock", ",", "$", "this", "->", "value", ")", ")", ";", "}", "}" ]
Runs the given code-block on the monad's value, if the value isn't null. @param callable $codeBlock Is expected to return the next value to be unitped. @return Maybe Returns None if the next value is null.
[ "Runs", "the", "given", "code", "-", "block", "on", "the", "monad", "s", "value", "if", "the", "value", "isn", "t", "null", "." ]
f39b8b2ef68a397d31d844341487412b335fd107
https://github.com/shrink0r/monatic/blob/f39b8b2ef68a397d31d844341487412b335fd107/src/Maybe.php#L57-L64
train
bkstg/resource-bundle
Timeline/EventSubscriber/ResourceTimelineSubscriber.php
ResourceTimelineSubscriber.createResourceTimelineEntry
public function createResourceTimelineEntry(EntityPublishedEvent $event): void { // Only act on resource objects. $resource = $event->getObject(); if (!$resource instanceof Resource) { return; } // Get the author for the resource. $author = $this->user_provider->loadUserByUsername($resource->getAuthor()); // Create components for this action. $resource_component = $this->action_manager->findOrCreateComponent($resource); $author_component = $this->action_manager->findOrCreateComponent($author); // Add timeline entries for each group. foreach ($resource->getGroups() as $group) { // Create the group component. $group_component = $this->action_manager->findOrCreateComponent($group); // Create the action and link it. $action = $this->action_manager->create($author_component, 'created_resource', [ 'directComplement' => $resource_component, 'indirectComplement' => $group_component, ]); // Update the action. $this->action_manager->updateAction($action); } }
php
public function createResourceTimelineEntry(EntityPublishedEvent $event): void { // Only act on resource objects. $resource = $event->getObject(); if (!$resource instanceof Resource) { return; } // Get the author for the resource. $author = $this->user_provider->loadUserByUsername($resource->getAuthor()); // Create components for this action. $resource_component = $this->action_manager->findOrCreateComponent($resource); $author_component = $this->action_manager->findOrCreateComponent($author); // Add timeline entries for each group. foreach ($resource->getGroups() as $group) { // Create the group component. $group_component = $this->action_manager->findOrCreateComponent($group); // Create the action and link it. $action = $this->action_manager->create($author_component, 'created_resource', [ 'directComplement' => $resource_component, 'indirectComplement' => $group_component, ]); // Update the action. $this->action_manager->updateAction($action); } }
[ "public", "function", "createResourceTimelineEntry", "(", "EntityPublishedEvent", "$", "event", ")", ":", "void", "{", "// Only act on resource objects.", "$", "resource", "=", "$", "event", "->", "getObject", "(", ")", ";", "if", "(", "!", "$", "resource", "instanceof", "Resource", ")", "{", "return", ";", "}", "// Get the author for the resource.", "$", "author", "=", "$", "this", "->", "user_provider", "->", "loadUserByUsername", "(", "$", "resource", "->", "getAuthor", "(", ")", ")", ";", "// Create components for this action.", "$", "resource_component", "=", "$", "this", "->", "action_manager", "->", "findOrCreateComponent", "(", "$", "resource", ")", ";", "$", "author_component", "=", "$", "this", "->", "action_manager", "->", "findOrCreateComponent", "(", "$", "author", ")", ";", "// Add timeline entries for each group.", "foreach", "(", "$", "resource", "->", "getGroups", "(", ")", "as", "$", "group", ")", "{", "// Create the group component.", "$", "group_component", "=", "$", "this", "->", "action_manager", "->", "findOrCreateComponent", "(", "$", "group", ")", ";", "// Create the action and link it.", "$", "action", "=", "$", "this", "->", "action_manager", "->", "create", "(", "$", "author_component", ",", "'created_resource'", ",", "[", "'directComplement'", "=>", "$", "resource_component", ",", "'indirectComplement'", "=>", "$", "group_component", ",", "]", ")", ";", "// Update the action.", "$", "this", "->", "action_manager", "->", "updateAction", "(", "$", "action", ")", ";", "}", "}" ]
Create the resource timeline entry. @param EntityPublishedEvent $event The entity published event. @return void
[ "Create", "the", "resource", "timeline", "entry", "." ]
9d094366799a4df117a1dd747af9bb6debe14325
https://github.com/bkstg/resource-bundle/blob/9d094366799a4df117a1dd747af9bb6debe14325/Timeline/EventSubscriber/ResourceTimelineSubscriber.php#L60-L89
train
cmsgears/module-sns-connect
common/models/forms/SnsLogin.php
SnsLogin.validateUser
public function validateUser( $attribute, $params ) { if( !$this->hasErrors() ) { $user = $this->user; if( !isset( $user ) ) { $this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_USER_NOT_EXIST ) ); } else { if( !$this->hasErrors() && !$user->isVerified( false ) ) { $this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_USER_VERIFICATION ) ); } if( !$this->hasErrors() && $user->isBlocked() ) { $this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_BLOCKED ) ); } } } }
php
public function validateUser( $attribute, $params ) { if( !$this->hasErrors() ) { $user = $this->user; if( !isset( $user ) ) { $this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_USER_NOT_EXIST ) ); } else { if( !$this->hasErrors() && !$user->isVerified( false ) ) { $this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_USER_VERIFICATION ) ); } if( !$this->hasErrors() && $user->isBlocked() ) { $this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_BLOCKED ) ); } } } }
[ "public", "function", "validateUser", "(", "$", "attribute", ",", "$", "params", ")", "{", "if", "(", "!", "$", "this", "->", "hasErrors", "(", ")", ")", "{", "$", "user", "=", "$", "this", "->", "user", ";", "if", "(", "!", "isset", "(", "$", "user", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "attribute", ",", "Yii", "::", "$", "app", "->", "coreMessage", "->", "getMessage", "(", "CoreGlobal", "::", "ERROR_USER_NOT_EXIST", ")", ")", ";", "}", "else", "{", "if", "(", "!", "$", "this", "->", "hasErrors", "(", ")", "&&", "!", "$", "user", "->", "isVerified", "(", "false", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "attribute", ",", "Yii", "::", "$", "app", "->", "coreMessage", "->", "getMessage", "(", "CoreGlobal", "::", "ERROR_USER_VERIFICATION", ")", ")", ";", "}", "if", "(", "!", "$", "this", "->", "hasErrors", "(", ")", "&&", "$", "user", "->", "isBlocked", "(", ")", ")", "{", "$", "this", "->", "addError", "(", "$", "attribute", ",", "Yii", "::", "$", "app", "->", "coreMessage", "->", "getMessage", "(", "CoreGlobal", "::", "ERROR_BLOCKED", ")", ")", ";", "}", "}", "}", "}" ]
Check whether valid user already exist and available for SNS login. @param string $attribute @param array $params @return void
[ "Check", "whether", "valid", "user", "already", "exist", "and", "available", "for", "SNS", "login", "." ]
753ee4157d41c81a701689624f4c44760a6cada3
https://github.com/cmsgears/module-sns-connect/blob/753ee4157d41c81a701689624f4c44760a6cada3/common/models/forms/SnsLogin.php#L129-L152
train
cmsgears/module-sns-connect
common/models/forms/SnsLogin.php
SnsLogin.login
public function login() { if( $this->validate() ) { $user = $this->getUser(); $user->lastLoginAt = DateUtil::getDateTime(); $user->save(); return Yii::$app->user->login( $user, false ); } return false; }
php
public function login() { if( $this->validate() ) { $user = $this->getUser(); $user->lastLoginAt = DateUtil::getDateTime(); $user->save(); return Yii::$app->user->login( $user, false ); } return false; }
[ "public", "function", "login", "(", ")", "{", "if", "(", "$", "this", "->", "validate", "(", ")", ")", "{", "$", "user", "=", "$", "this", "->", "getUser", "(", ")", ";", "$", "user", "->", "lastLoginAt", "=", "DateUtil", "::", "getDateTime", "(", ")", ";", "$", "user", "->", "save", "(", ")", ";", "return", "Yii", "::", "$", "app", "->", "user", "->", "login", "(", "$", "user", ",", "false", ")", ";", "}", "return", "false", ";", "}" ]
Logs in the user. @return boolean
[ "Logs", "in", "the", "user", "." ]
753ee4157d41c81a701689624f4c44760a6cada3
https://github.com/cmsgears/module-sns-connect/blob/753ee4157d41c81a701689624f4c44760a6cada3/common/models/forms/SnsLogin.php#L176-L190
train
ornament-orm/core
src/Model.php
Model.__isset
public function __isset(string $prop) : bool { $annotations = $this->__ornamentalize(); foreach ($annotations['methods'] as $name => $anns) { if (isset($anns['get']) && $anns['get'] == $prop) { return true; } } return property_exists($this->__state, $prop) && !is_null($this->__state->$prop); }
php
public function __isset(string $prop) : bool { $annotations = $this->__ornamentalize(); foreach ($annotations['methods'] as $name => $anns) { if (isset($anns['get']) && $anns['get'] == $prop) { return true; } } return property_exists($this->__state, $prop) && !is_null($this->__state->$prop); }
[ "public", "function", "__isset", "(", "string", "$", "prop", ")", ":", "bool", "{", "$", "annotations", "=", "$", "this", "->", "__ornamentalize", "(", ")", ";", "foreach", "(", "$", "annotations", "[", "'methods'", "]", "as", "$", "name", "=>", "$", "anns", ")", "{", "if", "(", "isset", "(", "$", "anns", "[", "'get'", "]", ")", "&&", "$", "anns", "[", "'get'", "]", "==", "$", "prop", ")", "{", "return", "true", ";", "}", "}", "return", "property_exists", "(", "$", "this", "->", "__state", ",", "$", "prop", ")", "&&", "!", "is_null", "(", "$", "this", "->", "__state", "->", "$", "prop", ")", ";", "}" ]
Check if a property is defined. Note that this will return true for protected properties. @param string $prop The property to check. @return boolean True if set, otherwise false.
[ "Check", "if", "a", "property", "is", "defined", ".", "Note", "that", "this", "will", "return", "true", "for", "protected", "properties", "." ]
b573c89d11a183c2e0e11afe8b6fdd56b2cd5ba8
https://github.com/ornament-orm/core/blob/b573c89d11a183c2e0e11afe8b6fdd56b2cd5ba8/src/Model.php#L252-L262
train
rollerworks/search-core
Loader/ConditionExporterLoader.php
ConditionExporterLoader.create
public static function create(): self { return new self( new ClosureContainer( [ 'rollerworks_search.condition_exporter.json' => function () { return new Exporter\JsonExporter(); }, 'rollerworks_search.condition_exporter.string_query' => function () { return new Exporter\StringQueryExporter(); }, 'rollerworks_search.condition_exporter.norm_string_query' => function () { return new Exporter\NormStringQueryExporter(); }, ] ), [ 'json' => 'rollerworks_search.condition_exporter.json', 'string_query' => 'rollerworks_search.condition_exporter.string_query', 'norm_string_query' => 'rollerworks_search.condition_exporter.norm_string_query', ] ); }
php
public static function create(): self { return new self( new ClosureContainer( [ 'rollerworks_search.condition_exporter.json' => function () { return new Exporter\JsonExporter(); }, 'rollerworks_search.condition_exporter.string_query' => function () { return new Exporter\StringQueryExporter(); }, 'rollerworks_search.condition_exporter.norm_string_query' => function () { return new Exporter\NormStringQueryExporter(); }, ] ), [ 'json' => 'rollerworks_search.condition_exporter.json', 'string_query' => 'rollerworks_search.condition_exporter.string_query', 'norm_string_query' => 'rollerworks_search.condition_exporter.norm_string_query', ] ); }
[ "public", "static", "function", "create", "(", ")", ":", "self", "{", "return", "new", "self", "(", "new", "ClosureContainer", "(", "[", "'rollerworks_search.condition_exporter.json'", "=>", "function", "(", ")", "{", "return", "new", "Exporter", "\\", "JsonExporter", "(", ")", ";", "}", ",", "'rollerworks_search.condition_exporter.string_query'", "=>", "function", "(", ")", "{", "return", "new", "Exporter", "\\", "StringQueryExporter", "(", ")", ";", "}", ",", "'rollerworks_search.condition_exporter.norm_string_query'", "=>", "function", "(", ")", "{", "return", "new", "Exporter", "\\", "NormStringQueryExporter", "(", ")", ";", "}", ",", "]", ")", ",", "[", "'json'", "=>", "'rollerworks_search.condition_exporter.json'", ",", "'string_query'", "=>", "'rollerworks_search.condition_exporter.string_query'", ",", "'norm_string_query'", "=>", "'rollerworks_search.condition_exporter.norm_string_query'", ",", "]", ")", ";", "}" ]
Create a new ConditionExporterLoader with the build-in ConditionExporters loadable. @return ConditionExporterLoader
[ "Create", "a", "new", "ConditionExporterLoader", "with", "the", "build", "-", "in", "ConditionExporters", "loadable", "." ]
6b5671b8c4d6298906ded768261b0a59845140fb
https://github.com/rollerworks/search-core/blob/6b5671b8c4d6298906ded768261b0a59845140fb/Loader/ConditionExporterLoader.php#L48-L70
train
phpffcms/ffcms-core
src/Network/Request.php
Request.loadTrustedProxies
private function loadTrustedProxies() { $proxies = App::$Properties->get('trustedProxy'); if (!$proxies || Str::likeEmpty($proxies)) { return; } $pList = explode(',', $proxies); $resultList = []; foreach ($pList as $proxy) { $resultList[] = trim($proxy); } self::setTrustedProxies($resultList, self::HEADER_X_FORWARDED_ALL); }
php
private function loadTrustedProxies() { $proxies = App::$Properties->get('trustedProxy'); if (!$proxies || Str::likeEmpty($proxies)) { return; } $pList = explode(',', $proxies); $resultList = []; foreach ($pList as $proxy) { $resultList[] = trim($proxy); } self::setTrustedProxies($resultList, self::HEADER_X_FORWARDED_ALL); }
[ "private", "function", "loadTrustedProxies", "(", ")", "{", "$", "proxies", "=", "App", "::", "$", "Properties", "->", "get", "(", "'trustedProxy'", ")", ";", "if", "(", "!", "$", "proxies", "||", "Str", "::", "likeEmpty", "(", "$", "proxies", ")", ")", "{", "return", ";", "}", "$", "pList", "=", "explode", "(", "','", ",", "$", "proxies", ")", ";", "$", "resultList", "=", "[", "]", ";", "foreach", "(", "$", "pList", "as", "$", "proxy", ")", "{", "$", "resultList", "[", "]", "=", "trim", "(", "$", "proxy", ")", ";", "}", "self", "::", "setTrustedProxies", "(", "$", "resultList", ",", "self", "::", "HEADER_X_FORWARDED_ALL", ")", ";", "}" ]
Set trusted proxies from configs
[ "Set", "trusted", "proxies", "from", "configs" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Network/Request.php#L88-L101
train
phpffcms/ffcms-core
src/Network/Request.php
Request.getPathInfo
public function getPathInfo() { $route = $this->languageInPath ? Str::sub(parent::getPathInfo(), Str::length($this->language) + 1) : parent::getPathInfo(); if (!Str::startsWith('/', $route)) { $route = '/' . $route; } return $route; }
php
public function getPathInfo() { $route = $this->languageInPath ? Str::sub(parent::getPathInfo(), Str::length($this->language) + 1) : parent::getPathInfo(); if (!Str::startsWith('/', $route)) { $route = '/' . $route; } return $route; }
[ "public", "function", "getPathInfo", "(", ")", "{", "$", "route", "=", "$", "this", "->", "languageInPath", "?", "Str", "::", "sub", "(", "parent", "::", "getPathInfo", "(", ")", ",", "Str", "::", "length", "(", "$", "this", "->", "language", ")", "+", "1", ")", ":", "parent", "::", "getPathInfo", "(", ")", ";", "if", "(", "!", "Str", "::", "startsWith", "(", "'/'", ",", "$", "route", ")", ")", "{", "$", "route", "=", "'/'", ".", "$", "route", ";", "}", "return", "$", "route", ";", "}" ]
Get pathway as string @return string
[ "Get", "pathway", "as", "string" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Network/Request.php#L107-L114
train
phpffcms/ffcms-core
src/Network/Request.php
Request.getInterfaceSlug
public function getInterfaceSlug(): string { $path = $this->getBasePath(); $subDir = App::$Properties->get('basePath'); if ($subDir !== '/') { $offset = (int)Str::length($subDir); $path = Str::sub($path, --$offset); } return $path; }
php
public function getInterfaceSlug(): string { $path = $this->getBasePath(); $subDir = App::$Properties->get('basePath'); if ($subDir !== '/') { $offset = (int)Str::length($subDir); $path = Str::sub($path, --$offset); } return $path; }
[ "public", "function", "getInterfaceSlug", "(", ")", ":", "string", "{", "$", "path", "=", "$", "this", "->", "getBasePath", "(", ")", ";", "$", "subDir", "=", "App", "::", "$", "Properties", "->", "get", "(", "'basePath'", ")", ";", "if", "(", "$", "subDir", "!==", "'/'", ")", "{", "$", "offset", "=", "(", "int", ")", "Str", "::", "length", "(", "$", "subDir", ")", ";", "$", "path", "=", "Str", "::", "sub", "(", "$", "path", ",", "--", "$", "offset", ")", ";", "}", "return", "$", "path", ";", "}" ]
Get base path from current environment without basePath of subdirectories @return string
[ "Get", "base", "path", "from", "current", "environment", "without", "basePath", "of", "subdirectories" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Network/Request.php#L152-L161
train
phpffcms/ffcms-core
src/Network/Request.php
Request.setTemplexFeatures
private function setTemplexFeatures(): void { $url = $this->getSchemeAndHttpHost(); $sub = null; if ($this->getInterfaceSlug() && Str::length($this->getInterfaceSlug()) > 0) { $sub = $this->getInterfaceSlug() . '/'; } if ($this->languageInPath()) { $sub .= $this->getLanguage(); } UrlRepository::factory()->setUrlAndSubdir($url, $sub); }
php
private function setTemplexFeatures(): void { $url = $this->getSchemeAndHttpHost(); $sub = null; if ($this->getInterfaceSlug() && Str::length($this->getInterfaceSlug()) > 0) { $sub = $this->getInterfaceSlug() . '/'; } if ($this->languageInPath()) { $sub .= $this->getLanguage(); } UrlRepository::factory()->setUrlAndSubdir($url, $sub); }
[ "private", "function", "setTemplexFeatures", "(", ")", ":", "void", "{", "$", "url", "=", "$", "this", "->", "getSchemeAndHttpHost", "(", ")", ";", "$", "sub", "=", "null", ";", "if", "(", "$", "this", "->", "getInterfaceSlug", "(", ")", "&&", "Str", "::", "length", "(", "$", "this", "->", "getInterfaceSlug", "(", ")", ")", ">", "0", ")", "{", "$", "sub", "=", "$", "this", "->", "getInterfaceSlug", "(", ")", ".", "'/'", ";", "}", "if", "(", "$", "this", "->", "languageInPath", "(", ")", ")", "{", "$", "sub", ".=", "$", "this", "->", "getLanguage", "(", ")", ";", "}", "UrlRepository", "::", "factory", "(", ")", "->", "setUrlAndSubdir", "(", "$", "url", ",", "$", "sub", ")", ";", "}" ]
Set templex template engine URL features @return void
[ "Set", "templex", "template", "engine", "URL", "features" ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Network/Request.php#L167-L180
train
dms-org/common.structure
src/FileSystem/UploadedFileFactory.php
UploadedFileFactory.build
public static function build(string $fullPath, int $uploadStatus, string $clientFileName = null, string $clientMimeType = null) : \Dms\Core\File\IUploadedFile { if ($clientMimeType && stripos($clientMimeType, 'image') === 0) { return new UploadedImage( $fullPath, $uploadStatus, $clientFileName, $clientMimeType ); } else { return new UploadedFile( $fullPath, $uploadStatus, $clientFileName, $clientMimeType ); } }
php
public static function build(string $fullPath, int $uploadStatus, string $clientFileName = null, string $clientMimeType = null) : \Dms\Core\File\IUploadedFile { if ($clientMimeType && stripos($clientMimeType, 'image') === 0) { return new UploadedImage( $fullPath, $uploadStatus, $clientFileName, $clientMimeType ); } else { return new UploadedFile( $fullPath, $uploadStatus, $clientFileName, $clientMimeType ); } }
[ "public", "static", "function", "build", "(", "string", "$", "fullPath", ",", "int", "$", "uploadStatus", ",", "string", "$", "clientFileName", "=", "null", ",", "string", "$", "clientMimeType", "=", "null", ")", ":", "\\", "Dms", "\\", "Core", "\\", "File", "\\", "IUploadedFile", "{", "if", "(", "$", "clientMimeType", "&&", "stripos", "(", "$", "clientMimeType", ",", "'image'", ")", "===", "0", ")", "{", "return", "new", "UploadedImage", "(", "$", "fullPath", ",", "$", "uploadStatus", ",", "$", "clientFileName", ",", "$", "clientMimeType", ")", ";", "}", "else", "{", "return", "new", "UploadedFile", "(", "$", "fullPath", ",", "$", "uploadStatus", ",", "$", "clientFileName", ",", "$", "clientMimeType", ")", ";", "}", "}" ]
Builds a new uploaded file instance based on the given mime type. @param string $fullPath @param int $uploadStatus @param string|null $clientFileName @param string|null $clientMimeType @return IUploadedFile
[ "Builds", "a", "new", "uploaded", "file", "instance", "based", "on", "the", "given", "mime", "type", "." ]
23f122182f60df5ec847047a81a39c8aab019ff1
https://github.com/dms-org/common.structure/blob/23f122182f60df5ec847047a81a39c8aab019ff1/src/FileSystem/UploadedFileFactory.php#L24-L41
train
luxorphp/collections
src/Lists/InfiniteList.php
InfiniteList.get
public function get(int $address = null): int { if ($address == null) { $temp = $this->value++; $this->memory[$this->lenght] = $temp; $this->lenght++; return $temp; } else { if ($address > -1) { return $this->memory[$address]; } } }
php
public function get(int $address = null): int { if ($address == null) { $temp = $this->value++; $this->memory[$this->lenght] = $temp; $this->lenght++; return $temp; } else { if ($address > -1) { return $this->memory[$address]; } } }
[ "public", "function", "get", "(", "int", "$", "address", "=", "null", ")", ":", "int", "{", "if", "(", "$", "address", "==", "null", ")", "{", "$", "temp", "=", "$", "this", "->", "value", "++", ";", "$", "this", "->", "memory", "[", "$", "this", "->", "lenght", "]", "=", "$", "temp", ";", "$", "this", "->", "lenght", "++", ";", "return", "$", "temp", ";", "}", "else", "{", "if", "(", "$", "address", ">", "-", "1", ")", "{", "return", "$", "this", "->", "memory", "[", "$", "address", "]", ";", "}", "}", "}" ]
Autogenera un numero entero de forma correlativa. @link http://php.net/manual/es/ @return int Se retorna un numero entero autogenerado.
[ "Autogenera", "un", "numero", "entero", "de", "forma", "correlativa", "." ]
4ee72e854874616c14938fdb40cabee00673edd9
https://github.com/luxorphp/collections/blob/4ee72e854874616c14938fdb40cabee00673edd9/src/Lists/InfiniteList.php#L36-L48
train
squareproton/Bond
src/Bond/Pg/Catalog/Repository/Index.php
Index.findByName
public function findByName( $name ) { // is this name schema qualified $call = sprintf( "findBy%s", ( false !== strpos( $name, '.' ) ) ? 'FullyQualifiedName' : 'Name' ); $found = $this->persistedGet()->$call( $name ); // return switch( $count = count( $found ) ) { case 0: return null; case 1: return $found->pop(); default: throw new \LogicException( "{$count} relations' found with name `{$name}`. Ambiguous. Can't proceed." ); } }
php
public function findByName( $name ) { // is this name schema qualified $call = sprintf( "findBy%s", ( false !== strpos( $name, '.' ) ) ? 'FullyQualifiedName' : 'Name' ); $found = $this->persistedGet()->$call( $name ); // return switch( $count = count( $found ) ) { case 0: return null; case 1: return $found->pop(); default: throw new \LogicException( "{$count} relations' found with name `{$name}`. Ambiguous. Can't proceed." ); } }
[ "public", "function", "findByName", "(", "$", "name", ")", "{", "// is this name schema qualified", "$", "call", "=", "sprintf", "(", "\"findBy%s\"", ",", "(", "false", "!==", "strpos", "(", "$", "name", ",", "'.'", ")", ")", "?", "'FullyQualifiedName'", ":", "'Name'", ")", ";", "$", "found", "=", "$", "this", "->", "persistedGet", "(", ")", "->", "$", "call", "(", "$", "name", ")", ";", "// return", "switch", "(", "$", "count", "=", "count", "(", "$", "found", ")", ")", "{", "case", "0", ":", "return", "null", ";", "case", "1", ":", "return", "$", "found", "->", "pop", "(", ")", ";", "default", ":", "throw", "new", "\\", "LogicException", "(", "\"{$count} relations' found with name `{$name}`. Ambiguous. Can't proceed.\"", ")", ";", "}", "}" ]
Return a index from it's name @param string @return Entity\Relation
[ "Return", "a", "index", "from", "it", "s", "name" ]
a04ad9dd1a35adeaec98237716c2a41ce02b4f1a
https://github.com/squareproton/Bond/blob/a04ad9dd1a35adeaec98237716c2a41ce02b4f1a/src/Bond/Pg/Catalog/Repository/Index.php#L88-L109
train
guide42/plan
library/MultipleInvalid.php
MultipleInvalid.getDepth
public function getDepth(): int { $depth = parent::getDepth(); $paths = array_filter(array_map( /** * Extracts error path. * * @param Invalid $error the exception * * @return array|null */ function(Invalid $error) { return $error->getPath(); }, $this->errors )); if ($paths && ($max = max(array_map('count', $paths))) > $depth) { $depth = $max; } return $depth; }
php
public function getDepth(): int { $depth = parent::getDepth(); $paths = array_filter(array_map( /** * Extracts error path. * * @param Invalid $error the exception * * @return array|null */ function(Invalid $error) { return $error->getPath(); }, $this->errors )); if ($paths && ($max = max(array_map('count', $paths))) > $depth) { $depth = $max; } return $depth; }
[ "public", "function", "getDepth", "(", ")", ":", "int", "{", "$", "depth", "=", "parent", "::", "getDepth", "(", ")", ";", "$", "paths", "=", "array_filter", "(", "array_map", "(", "/**\n * Extracts error path.\n *\n * @param Invalid $error the exception\n *\n * @return array|null\n */", "function", "(", "Invalid", "$", "error", ")", "{", "return", "$", "error", "->", "getPath", "(", ")", ";", "}", ",", "$", "this", "->", "errors", ")", ")", ";", "if", "(", "$", "paths", "&&", "(", "$", "max", "=", "max", "(", "array_map", "(", "'count'", ",", "$", "paths", ")", ")", ")", ">", "$", "depth", ")", "{", "$", "depth", "=", "$", "max", ";", "}", "return", "$", "depth", ";", "}" ]
Calculate the maximum depth between its errors. @return int
[ "Calculate", "the", "maximum", "depth", "between", "its", "errors", "." ]
f1b23687fedaff5dcca11bda774613a0a6117d7e
https://github.com/guide42/plan/blob/f1b23687fedaff5dcca11bda774613a0a6117d7e/library/MultipleInvalid.php#L72-L94
train
guide42/plan
library/MultipleInvalid.php
MultipleInvalid.getFlatErrors
public function getFlatErrors(): array { /** * Reducer that flat the errors. * * @param array $carry previous error list * @param Invalid $item to append to $carry * * @return array<Invalid> */ $reduce = function(array $carry, Invalid $item) use(&$reduce) { if ($item instanceof self) { $carry = array_merge($carry, $item->getFlatErrors()); } else { $carry[] = $item; } if ($item->getPrevious()) { $carry = $reduce($carry, $item->getPrevious()); } return $carry; }; return array_reduce($this->errors, $reduce, []); }
php
public function getFlatErrors(): array { /** * Reducer that flat the errors. * * @param array $carry previous error list * @param Invalid $item to append to $carry * * @return array<Invalid> */ $reduce = function(array $carry, Invalid $item) use(&$reduce) { if ($item instanceof self) { $carry = array_merge($carry, $item->getFlatErrors()); } else { $carry[] = $item; } if ($item->getPrevious()) { $carry = $reduce($carry, $item->getPrevious()); } return $carry; }; return array_reduce($this->errors, $reduce, []); }
[ "public", "function", "getFlatErrors", "(", ")", ":", "array", "{", "/**\n * Reducer that flat the errors.\n *\n * @param array $carry previous error list\n * @param Invalid $item to append to $carry\n *\n * @return array<Invalid>\n */", "$", "reduce", "=", "function", "(", "array", "$", "carry", ",", "Invalid", "$", "item", ")", "use", "(", "&", "$", "reduce", ")", "{", "if", "(", "$", "item", "instanceof", "self", ")", "{", "$", "carry", "=", "array_merge", "(", "$", "carry", ",", "$", "item", "->", "getFlatErrors", "(", ")", ")", ";", "}", "else", "{", "$", "carry", "[", "]", "=", "$", "item", ";", "}", "if", "(", "$", "item", "->", "getPrevious", "(", ")", ")", "{", "$", "carry", "=", "$", "reduce", "(", "$", "carry", ",", "$", "item", "->", "getPrevious", "(", ")", ")", ";", "}", "return", "$", "carry", ";", "}", ";", "return", "array_reduce", "(", "$", "this", "->", "errors", ",", "$", "reduce", ",", "[", "]", ")", ";", "}" ]
Retrieve a list of `Invalid` errors. The returning array will have one level deep only. @return array<Invalid>
[ "Retrieve", "a", "list", "of", "Invalid", "errors", ".", "The", "returning", "array", "will", "have", "one", "level", "deep", "only", "." ]
f1b23687fedaff5dcca11bda774613a0a6117d7e
https://github.com/guide42/plan/blob/f1b23687fedaff5dcca11bda774613a0a6117d7e/library/MultipleInvalid.php#L102-L126
train
Dhii/callback-abstract
src/InvokeCallableCapableTrait.php
InvokeCallableCapableTrait._invokeCallable
protected function _invokeCallable($callable, $args) { if (!is_callable($callable)) { throw $this->_createInvalidArgumentException($this->__('Callable is not callable'), null, null, $callable); } $args = $this->_normalizeArray($args); try { $reflection = $this->_createReflectionForCallable($callable); $params = $reflection->getParameters(); $this->_validateParams($args, $params); } catch (RootException $e) { throw $this->_createInvocationException($this->__('Could not invoke callable'), null, $e, $callable, $args); } // Invoke the callable try { if ($reflection instanceof ReflectionMethod) { if (is_object($callable)) { $target = $callable; } else { $target = is_object($callable[0]) ? $callable[0] : null; } return $reflection->invokeArgs($target, $args); } else { return call_user_func_array($callable, $args); } } catch (RootException $e) { throw $this->_createInternalException( $this->__('There was an error during invocation'), null, $e ); } }
php
protected function _invokeCallable($callable, $args) { if (!is_callable($callable)) { throw $this->_createInvalidArgumentException($this->__('Callable is not callable'), null, null, $callable); } $args = $this->_normalizeArray($args); try { $reflection = $this->_createReflectionForCallable($callable); $params = $reflection->getParameters(); $this->_validateParams($args, $params); } catch (RootException $e) { throw $this->_createInvocationException($this->__('Could not invoke callable'), null, $e, $callable, $args); } // Invoke the callable try { if ($reflection instanceof ReflectionMethod) { if (is_object($callable)) { $target = $callable; } else { $target = is_object($callable[0]) ? $callable[0] : null; } return $reflection->invokeArgs($target, $args); } else { return call_user_func_array($callable, $args); } } catch (RootException $e) { throw $this->_createInternalException( $this->__('There was an error during invocation'), null, $e ); } }
[ "protected", "function", "_invokeCallable", "(", "$", "callable", ",", "$", "args", ")", "{", "if", "(", "!", "is_callable", "(", "$", "callable", ")", ")", "{", "throw", "$", "this", "->", "_createInvalidArgumentException", "(", "$", "this", "->", "__", "(", "'Callable is not callable'", ")", ",", "null", ",", "null", ",", "$", "callable", ")", ";", "}", "$", "args", "=", "$", "this", "->", "_normalizeArray", "(", "$", "args", ")", ";", "try", "{", "$", "reflection", "=", "$", "this", "->", "_createReflectionForCallable", "(", "$", "callable", ")", ";", "$", "params", "=", "$", "reflection", "->", "getParameters", "(", ")", ";", "$", "this", "->", "_validateParams", "(", "$", "args", ",", "$", "params", ")", ";", "}", "catch", "(", "RootException", "$", "e", ")", "{", "throw", "$", "this", "->", "_createInvocationException", "(", "$", "this", "->", "__", "(", "'Could not invoke callable'", ")", ",", "null", ",", "$", "e", ",", "$", "callable", ",", "$", "args", ")", ";", "}", "// Invoke the callable", "try", "{", "if", "(", "$", "reflection", "instanceof", "ReflectionMethod", ")", "{", "if", "(", "is_object", "(", "$", "callable", ")", ")", "{", "$", "target", "=", "$", "callable", ";", "}", "else", "{", "$", "target", "=", "is_object", "(", "$", "callable", "[", "0", "]", ")", "?", "$", "callable", "[", "0", "]", ":", "null", ";", "}", "return", "$", "reflection", "->", "invokeArgs", "(", "$", "target", ",", "$", "args", ")", ";", "}", "else", "{", "return", "call_user_func_array", "(", "$", "callable", ",", "$", "args", ")", ";", "}", "}", "catch", "(", "RootException", "$", "e", ")", "{", "throw", "$", "this", "->", "_createInternalException", "(", "$", "this", "->", "__", "(", "'There was an error during invocation'", ")", ",", "null", ",", "$", "e", ")", ";", "}", "}" ]
Invokes a callable. @since [*next-version*] @param callable $callable The callable to invoke. @param array|Traversable|stdClass $args The arguments to invoke the callable with. @throws InvalidArgumentException If the callable is not callable. @throws InvalidArgumentException If the args are not a valid list. @throws InvocationExceptionInterface If the callable cannot be invoked. @throws InternalExceptionInterface If a problem occurs during invocation. @return mixed The result of the invocation.
[ "Invokes", "a", "callable", "." ]
43ed4e99fc6ccdaf46a25d06da482a2fba8d9b19
https://github.com/Dhii/callback-abstract/blob/43ed4e99fc6ccdaf46a25d06da482a2fba8d9b19/src/InvokeCallableCapableTrait.php#L40-L78
train
phpffcms/ffcms-core
src/Helper/FileSystem/Normalize.php
Normalize.diskFullPath
public static function diskFullPath($path) { $path = self::diskPath($path); if (!Str::startsWith(root, $path)) { $path = root . DIRECTORY_SEPARATOR . ltrim($path, '\\/'); } return $path; }
php
public static function diskFullPath($path) { $path = self::diskPath($path); if (!Str::startsWith(root, $path)) { $path = root . DIRECTORY_SEPARATOR . ltrim($path, '\\/'); } return $path; }
[ "public", "static", "function", "diskFullPath", "(", "$", "path", ")", "{", "$", "path", "=", "self", "::", "diskPath", "(", "$", "path", ")", ";", "if", "(", "!", "Str", "::", "startsWith", "(", "root", ",", "$", "path", ")", ")", "{", "$", "path", "=", "root", ".", "DIRECTORY_SEPARATOR", ".", "ltrim", "(", "$", "path", ",", "'\\\\/'", ")", ";", "}", "return", "$", "path", ";", "}" ]
Normalize local disk-based ABSOLUTE path. @param string $path @return string
[ "Normalize", "local", "disk", "-", "based", "ABSOLUTE", "path", "." ]
44a309553ef9f115ccfcfd71f2ac6e381c612082
https://github.com/phpffcms/ffcms-core/blob/44a309553ef9f115ccfcfd71f2ac6e381c612082/src/Helper/FileSystem/Normalize.php#L54-L61
train
gplcart/cli
controllers/commands/Category.php
Category.cmdGetCategory
public function cmdGetCategory() { $result = $this->getListCategory(); $this->outputFormat($result); $this->outputFormatTableCategory($result); $this->output(); }
php
public function cmdGetCategory() { $result = $this->getListCategory(); $this->outputFormat($result); $this->outputFormatTableCategory($result); $this->output(); }
[ "public", "function", "cmdGetCategory", "(", ")", "{", "$", "result", "=", "$", "this", "->", "getListCategory", "(", ")", ";", "$", "this", "->", "outputFormat", "(", "$", "result", ")", ";", "$", "this", "->", "outputFormatTableCategory", "(", "$", "result", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "category-get" command
[ "Callback", "for", "category", "-", "get", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Category.php#L40-L46
train
gplcart/cli
controllers/commands/Category.php
Category.cmdUpdateCategory
public function cmdUpdateCategory() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->validateComponent('category'); $this->updateCategory($params[0]); $this->output(); }
php
public function cmdUpdateCategory() { $params = $this->getParam(); if (empty($params[0]) || count($params) < 2) { $this->errorAndExit($this->text('Invalid command')); } if (!is_numeric($params[0])) { $this->errorAndExit($this->text('Invalid argument')); } $this->setSubmitted(null, $params); $this->setSubmitted('update', $params[0]); $this->validateComponent('category'); $this->updateCategory($params[0]); $this->output(); }
[ "public", "function", "cmdUpdateCategory", "(", ")", "{", "$", "params", "=", "$", "this", "->", "getParam", "(", ")", ";", "if", "(", "empty", "(", "$", "params", "[", "0", "]", ")", "||", "count", "(", "$", "params", ")", "<", "2", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid command'", ")", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "params", "[", "0", "]", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "params", ")", ";", "$", "this", "->", "setSubmitted", "(", "'update'", ",", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "validateComponent", "(", "'category'", ")", ";", "$", "this", "->", "updateCategory", "(", "$", "params", "[", "0", "]", ")", ";", "$", "this", "->", "output", "(", ")", ";", "}" ]
Callback for "category-update" command
[ "Callback", "for", "category", "-", "update", "command" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Category.php#L113-L131
train
gplcart/cli
controllers/commands/Category.php
Category.getListCategory
protected function getListCategory() { $id = $this->getParam(0); if (!isset($id)) { return $this->category->getList(array('limit' => $this->getLimit())); } if (!is_numeric($id)) { $this->errorAndExit($this->text('Invalid argument')); } if ($this->getParam('group')) { return $this->category->getList(array('category_group_id' => $id, 'limit' => $this->getLimit())); } if ($this->getParam('parent')) { return $this->category->getList(array('parent_id' => $id, 'limit' => $this->getLimit())); } $result = $this->category->get($id); if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } return array($result); }
php
protected function getListCategory() { $id = $this->getParam(0); if (!isset($id)) { return $this->category->getList(array('limit' => $this->getLimit())); } if (!is_numeric($id)) { $this->errorAndExit($this->text('Invalid argument')); } if ($this->getParam('group')) { return $this->category->getList(array('category_group_id' => $id, 'limit' => $this->getLimit())); } if ($this->getParam('parent')) { return $this->category->getList(array('parent_id' => $id, 'limit' => $this->getLimit())); } $result = $this->category->get($id); if (empty($result)) { $this->errorAndExit($this->text('Unexpected result')); } return array($result); }
[ "protected", "function", "getListCategory", "(", ")", "{", "$", "id", "=", "$", "this", "->", "getParam", "(", "0", ")", ";", "if", "(", "!", "isset", "(", "$", "id", ")", ")", "{", "return", "$", "this", "->", "category", "->", "getList", "(", "array", "(", "'limit'", "=>", "$", "this", "->", "getLimit", "(", ")", ")", ")", ";", "}", "if", "(", "!", "is_numeric", "(", "$", "id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Invalid argument'", ")", ")", ";", "}", "if", "(", "$", "this", "->", "getParam", "(", "'group'", ")", ")", "{", "return", "$", "this", "->", "category", "->", "getList", "(", "array", "(", "'category_group_id'", "=>", "$", "id", ",", "'limit'", "=>", "$", "this", "->", "getLimit", "(", ")", ")", ")", ";", "}", "if", "(", "$", "this", "->", "getParam", "(", "'parent'", ")", ")", "{", "return", "$", "this", "->", "category", "->", "getList", "(", "array", "(", "'parent_id'", "=>", "$", "id", ",", "'limit'", "=>", "$", "this", "->", "getLimit", "(", ")", ")", ")", ";", "}", "$", "result", "=", "$", "this", "->", "category", "->", "get", "(", "$", "id", ")", ";", "if", "(", "empty", "(", "$", "result", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "return", "array", "(", "$", "result", ")", ";", "}" ]
Returns an array of categories @return array
[ "Returns", "an", "array", "of", "categories" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Category.php#L137-L164
train
gplcart/cli
controllers/commands/Category.php
Category.addCategory
protected function addCategory() { if (!$this->isError()) { $id = $this->category->add($this->getSubmitted()); if (empty($id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($id); } }
php
protected function addCategory() { if (!$this->isError()) { $id = $this->category->add($this->getSubmitted()); if (empty($id)) { $this->errorAndExit($this->text('Unexpected result')); } $this->line($id); } }
[ "protected", "function", "addCategory", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isError", "(", ")", ")", "{", "$", "id", "=", "$", "this", "->", "category", "->", "add", "(", "$", "this", "->", "getSubmitted", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "id", ")", ")", "{", "$", "this", "->", "errorAndExit", "(", "$", "this", "->", "text", "(", "'Unexpected result'", ")", ")", ";", "}", "$", "this", "->", "line", "(", "$", "id", ")", ";", "}", "}" ]
Add a new category
[ "Add", "a", "new", "category" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Category.php#L200-L209
train
gplcart/cli
controllers/commands/Category.php
Category.submitAddCategory
protected function submitAddCategory() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('category'); $this->addCategory(); }
php
protected function submitAddCategory() { $this->setSubmitted(null, $this->getParam()); $this->validateComponent('category'); $this->addCategory(); }
[ "protected", "function", "submitAddCategory", "(", ")", "{", "$", "this", "->", "setSubmitted", "(", "null", ",", "$", "this", "->", "getParam", "(", ")", ")", ";", "$", "this", "->", "validateComponent", "(", "'category'", ")", ";", "$", "this", "->", "addCategory", "(", ")", ";", "}" ]
Add a new category at once
[ "Add", "a", "new", "category", "at", "once" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Category.php#L225-L230
train
gplcart/cli
controllers/commands/Category.php
Category.wizardAddCategory
protected function wizardAddCategory() { // Required $this->validatePrompt('title', $this->text('Title'), 'category'); $this->validatePrompt('category_group_id', $this->text('Category group ID'), 'category'); // Optional $this->validatePrompt('parent_id', $this->text('Parent category ID'), 'category', 0); $this->validatePrompt('description_1', $this->text('First description'), 'category', ''); $this->validatePrompt('description_2', $this->text('Second description'), 'category', ''); $this->validatePrompt('meta_title', $this->text('Meta title'), 'category', ''); $this->validatePrompt('meta_description', $this->text('Meta description'), 'category', ''); $this->validatePrompt('status', $this->text('Status'), 'category', 0); $this->validatePrompt('weight', $this->text('Weight'), 'category', 0); $this->validateComponent('category'); $this->addCategory(); }
php
protected function wizardAddCategory() { // Required $this->validatePrompt('title', $this->text('Title'), 'category'); $this->validatePrompt('category_group_id', $this->text('Category group ID'), 'category'); // Optional $this->validatePrompt('parent_id', $this->text('Parent category ID'), 'category', 0); $this->validatePrompt('description_1', $this->text('First description'), 'category', ''); $this->validatePrompt('description_2', $this->text('Second description'), 'category', ''); $this->validatePrompt('meta_title', $this->text('Meta title'), 'category', ''); $this->validatePrompt('meta_description', $this->text('Meta description'), 'category', ''); $this->validatePrompt('status', $this->text('Status'), 'category', 0); $this->validatePrompt('weight', $this->text('Weight'), 'category', 0); $this->validateComponent('category'); $this->addCategory(); }
[ "protected", "function", "wizardAddCategory", "(", ")", "{", "// Required", "$", "this", "->", "validatePrompt", "(", "'title'", ",", "$", "this", "->", "text", "(", "'Title'", ")", ",", "'category'", ")", ";", "$", "this", "->", "validatePrompt", "(", "'category_group_id'", ",", "$", "this", "->", "text", "(", "'Category group ID'", ")", ",", "'category'", ")", ";", "// Optional", "$", "this", "->", "validatePrompt", "(", "'parent_id'", ",", "$", "this", "->", "text", "(", "'Parent category ID'", ")", ",", "'category'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'description_1'", ",", "$", "this", "->", "text", "(", "'First description'", ")", ",", "'category'", ",", "''", ")", ";", "$", "this", "->", "validatePrompt", "(", "'description_2'", ",", "$", "this", "->", "text", "(", "'Second description'", ")", ",", "'category'", ",", "''", ")", ";", "$", "this", "->", "validatePrompt", "(", "'meta_title'", ",", "$", "this", "->", "text", "(", "'Meta title'", ")", ",", "'category'", ",", "''", ")", ";", "$", "this", "->", "validatePrompt", "(", "'meta_description'", ",", "$", "this", "->", "text", "(", "'Meta description'", ")", ",", "'category'", ",", "''", ")", ";", "$", "this", "->", "validatePrompt", "(", "'status'", ",", "$", "this", "->", "text", "(", "'Status'", ")", ",", "'category'", ",", "0", ")", ";", "$", "this", "->", "validatePrompt", "(", "'weight'", ",", "$", "this", "->", "text", "(", "'Weight'", ")", ",", "'category'", ",", "0", ")", ";", "$", "this", "->", "validateComponent", "(", "'category'", ")", ";", "$", "this", "->", "addCategory", "(", ")", ";", "}" ]
Add a new category step by step
[ "Add", "a", "new", "category", "step", "by", "step" ]
e57dba53e291a225b4bff0c0d9b23d685dd1c125
https://github.com/gplcart/cli/blob/e57dba53e291a225b4bff0c0d9b23d685dd1c125/controllers/commands/Category.php#L235-L252
train
Topolis/FunctionLibrary
src/Math.php
Math.baseToDec
public static function baseToDec($input, $Chars) { if (preg_match('/^[' . $Chars . ']+$/', $input)){ $Result = (string)'0'; for ($i=0; $i<strlen($input); $i++){ if ($i != 0) $Result = bcmul($Result, strlen($Chars),0); $Result = bcadd($Result, strpos($Chars, $input[$i]),0); } return $Result; } return false; }
php
public static function baseToDec($input, $Chars) { if (preg_match('/^[' . $Chars . ']+$/', $input)){ $Result = (string)'0'; for ($i=0; $i<strlen($input); $i++){ if ($i != 0) $Result = bcmul($Result, strlen($Chars),0); $Result = bcadd($Result, strpos($Chars, $input[$i]),0); } return $Result; } return false; }
[ "public", "static", "function", "baseToDec", "(", "$", "input", ",", "$", "Chars", ")", "{", "if", "(", "preg_match", "(", "'/^['", ".", "$", "Chars", ".", "']+$/'", ",", "$", "input", ")", ")", "{", "$", "Result", "=", "(", "string", ")", "'0'", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "strlen", "(", "$", "input", ")", ";", "$", "i", "++", ")", "{", "if", "(", "$", "i", "!=", "0", ")", "$", "Result", "=", "bcmul", "(", "$", "Result", ",", "strlen", "(", "$", "Chars", ")", ",", "0", ")", ";", "$", "Result", "=", "bcadd", "(", "$", "Result", ",", "strpos", "(", "$", "Chars", ",", "$", "input", "[", "$", "i", "]", ")", ",", "0", ")", ";", "}", "return", "$", "Result", ";", "}", "return", "false", ";", "}" ]
convert character string with arbitrary base to decimal string @param string $input arbitrary base string @param string $Chars list of letters in arbitrary base @return string decimal base string
[ "convert", "character", "string", "with", "arbitrary", "base", "to", "decimal", "string" ]
bc57f465932fbf297927c2a32765255131b907eb
https://github.com/Topolis/FunctionLibrary/blob/bc57f465932fbf297927c2a32765255131b907eb/src/Math.php#L17-L29
train
Topolis/FunctionLibrary
src/Math.php
Math.baseFromDec
public static function baseFromDec($input, $Chars) { if (preg_match('/^[0-9]+$/', $input)) { $Result = ''; do { $Result .= $Chars[bcmod($input, strlen($Chars))]; $input = bcdiv($input, strlen($Chars), 0); } while (bccomp($input, '0') != 0); return strrev($Result); } return false; }
php
public static function baseFromDec($input, $Chars) { if (preg_match('/^[0-9]+$/', $input)) { $Result = ''; do { $Result .= $Chars[bcmod($input, strlen($Chars))]; $input = bcdiv($input, strlen($Chars), 0); } while (bccomp($input, '0') != 0); return strrev($Result); } return false; }
[ "public", "static", "function", "baseFromDec", "(", "$", "input", ",", "$", "Chars", ")", "{", "if", "(", "preg_match", "(", "'/^[0-9]+$/'", ",", "$", "input", ")", ")", "{", "$", "Result", "=", "''", ";", "do", "{", "$", "Result", ".=", "$", "Chars", "[", "bcmod", "(", "$", "input", ",", "strlen", "(", "$", "Chars", ")", ")", "]", ";", "$", "input", "=", "bcdiv", "(", "$", "input", ",", "strlen", "(", "$", "Chars", ")", ",", "0", ")", ";", "}", "while", "(", "bccomp", "(", "$", "input", ",", "'0'", ")", "!=", "0", ")", ";", "return", "strrev", "(", "$", "Result", ")", ";", "}", "return", "false", ";", "}" ]
convert character string with decimal base to arbitrary base @param string $input decimal string @param string $Chars @return string|boolean
[ "convert", "character", "string", "with", "decimal", "base", "to", "arbitrary", "base" ]
bc57f465932fbf297927c2a32765255131b907eb
https://github.com/Topolis/FunctionLibrary/blob/bc57f465932fbf297927c2a32765255131b907eb/src/Math.php#L37-L52
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.updateIndex
public function updateIndex() { $this->startLogging(); $this->addLog('Indexing start.'); $this->addLog('Clearing index.'); $this->resetIndex(); $this->addLog('Cleaning Published Deleted Documents'); $this->storage->getDocuments()->cleanPublishedDeletedDocuments(); $this->addLog('Retrieving documents to be indexed.'); $documents = $this->storage->getDocuments()->getPublishedDocumentsNoFolders(); $this->addLog('Start Document Term Count for ' . count($documents) . ' documents'); $this->createDocumentTermCount($documents); $this->addLog('Start Document Term Frequency.'); $this->createDocumentTermFrequency(); $this->addLog('Start Term Field Length Norm.'); $this->createTermFieldLengthNorm(); $this->addLog('Start Inverse Document Frequency.'); $this->createInverseDocumentFrequency(); $this->addLog('Replacing old index.'); $this->replaceOldIndex(); $this->addLog('Indexing complete.'); return $this->log; }
php
public function updateIndex() { $this->startLogging(); $this->addLog('Indexing start.'); $this->addLog('Clearing index.'); $this->resetIndex(); $this->addLog('Cleaning Published Deleted Documents'); $this->storage->getDocuments()->cleanPublishedDeletedDocuments(); $this->addLog('Retrieving documents to be indexed.'); $documents = $this->storage->getDocuments()->getPublishedDocumentsNoFolders(); $this->addLog('Start Document Term Count for ' . count($documents) . ' documents'); $this->createDocumentTermCount($documents); $this->addLog('Start Document Term Frequency.'); $this->createDocumentTermFrequency(); $this->addLog('Start Term Field Length Norm.'); $this->createTermFieldLengthNorm(); $this->addLog('Start Inverse Document Frequency.'); $this->createInverseDocumentFrequency(); $this->addLog('Replacing old index.'); $this->replaceOldIndex(); $this->addLog('Indexing complete.'); return $this->log; }
[ "public", "function", "updateIndex", "(", ")", "{", "$", "this", "->", "startLogging", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Indexing start.'", ")", ";", "$", "this", "->", "addLog", "(", "'Clearing index.'", ")", ";", "$", "this", "->", "resetIndex", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Cleaning Published Deleted Documents'", ")", ";", "$", "this", "->", "storage", "->", "getDocuments", "(", ")", "->", "cleanPublishedDeletedDocuments", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Retrieving documents to be indexed.'", ")", ";", "$", "documents", "=", "$", "this", "->", "storage", "->", "getDocuments", "(", ")", "->", "getPublishedDocumentsNoFolders", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Start Document Term Count for '", ".", "count", "(", "$", "documents", ")", ".", "' documents'", ")", ";", "$", "this", "->", "createDocumentTermCount", "(", "$", "documents", ")", ";", "$", "this", "->", "addLog", "(", "'Start Document Term Frequency.'", ")", ";", "$", "this", "->", "createDocumentTermFrequency", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Start Term Field Length Norm.'", ")", ";", "$", "this", "->", "createTermFieldLengthNorm", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Start Inverse Document Frequency.'", ")", ";", "$", "this", "->", "createInverseDocumentFrequency", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Replacing old index.'", ")", ";", "$", "this", "->", "replaceOldIndex", "(", ")", ";", "$", "this", "->", "addLog", "(", "'Indexing complete.'", ")", ";", "return", "$", "this", "->", "log", ";", "}" ]
Creates a new temporary search db, cleans it if it exists then calculates and stores the search index in this db and finally if indexing completed replaces the current search db with the temporary one. Returns the log in string format. @return string
[ "Creates", "a", "new", "temporary", "search", "db", "cleans", "it", "if", "it", "exists", "then", "calculates", "and", "stores", "the", "search", "index", "in", "this", "db", "and", "finally", "if", "indexing", "completed", "replaces", "the", "current", "search", "db", "with", "the", "temporary", "one", ".", "Returns", "the", "log", "in", "string", "format", "." ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L53-L75
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.createDocumentTermCount
public function createDocumentTermCount($documents) { $termCount = new TermCount($this->getSearchDbHandle(), $documents, $this->filters, $this->storage); $termCount->execute(); }
php
public function createDocumentTermCount($documents) { $termCount = new TermCount($this->getSearchDbHandle(), $documents, $this->filters, $this->storage); $termCount->execute(); }
[ "public", "function", "createDocumentTermCount", "(", "$", "documents", ")", "{", "$", "termCount", "=", "new", "TermCount", "(", "$", "this", "->", "getSearchDbHandle", "(", ")", ",", "$", "documents", ",", "$", "this", "->", "filters", ",", "$", "this", "->", "storage", ")", ";", "$", "termCount", "->", "execute", "(", ")", ";", "}" ]
Count how often a term is used in a document @param $documents
[ "Count", "how", "often", "a", "term", "is", "used", "in", "a", "document" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L82-L86
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.createInverseDocumentFrequency
public function createInverseDocumentFrequency() { $documentCount = $this->getTotalDocumentCount(); $inverseDocumentFrequency = new InverseDocumentFrequency($this->getSearchDbHandle(), $documentCount); $inverseDocumentFrequency->execute(); }
php
public function createInverseDocumentFrequency() { $documentCount = $this->getTotalDocumentCount(); $inverseDocumentFrequency = new InverseDocumentFrequency($this->getSearchDbHandle(), $documentCount); $inverseDocumentFrequency->execute(); }
[ "public", "function", "createInverseDocumentFrequency", "(", ")", "{", "$", "documentCount", "=", "$", "this", "->", "getTotalDocumentCount", "(", ")", ";", "$", "inverseDocumentFrequency", "=", "new", "InverseDocumentFrequency", "(", "$", "this", "->", "getSearchDbHandle", "(", ")", ",", "$", "documentCount", ")", ";", "$", "inverseDocumentFrequency", "->", "execute", "(", ")", ";", "}" ]
Calculates the inverse document frequency for each term. This is a representation of how often a certain term is used in comparison to all terms.
[ "Calculates", "the", "inverse", "document", "frequency", "for", "each", "term", ".", "This", "is", "a", "representation", "of", "how", "often", "a", "certain", "term", "is", "used", "in", "comparison", "to", "all", "terms", "." ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L121-L126
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.startLogging
private function startLogging() { $this->loggingStart = round(microtime(true) * 1000); $this->lastLog = $this->loggingStart; }
php
private function startLogging() { $this->loggingStart = round(microtime(true) * 1000); $this->lastLog = $this->loggingStart; }
[ "private", "function", "startLogging", "(", ")", "{", "$", "this", "->", "loggingStart", "=", "round", "(", "microtime", "(", "true", ")", "*", "1000", ")", ";", "$", "this", "->", "lastLog", "=", "$", "this", "->", "loggingStart", ";", "}" ]
Stores the time the indexing started in memory
[ "Stores", "the", "time", "the", "indexing", "started", "in", "memory" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L151-L155
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.addLog
private function addLog($string) { $currentTime = round(microtime(true) * 1000); $this->log .= date('d-m-Y H:i:s - ') . str_pad($string, 50, " ", STR_PAD_RIGHT) . "\t" . ($currentTime - $this->lastLog) . 'ms since last log. ' . "\t" . ($currentTime - $this->loggingStart) . 'ms since start.' . PHP_EOL; $this->lastLog = round(microtime(true) * 1000); }
php
private function addLog($string) { $currentTime = round(microtime(true) * 1000); $this->log .= date('d-m-Y H:i:s - ') . str_pad($string, 50, " ", STR_PAD_RIGHT) . "\t" . ($currentTime - $this->lastLog) . 'ms since last log. ' . "\t" . ($currentTime - $this->loggingStart) . 'ms since start.' . PHP_EOL; $this->lastLog = round(microtime(true) * 1000); }
[ "private", "function", "addLog", "(", "$", "string", ")", "{", "$", "currentTime", "=", "round", "(", "microtime", "(", "true", ")", "*", "1000", ")", ";", "$", "this", "->", "log", ".=", "date", "(", "'d-m-Y H:i:s - '", ")", ".", "str_pad", "(", "$", "string", ",", "50", ",", "\" \"", ",", "STR_PAD_RIGHT", ")", ".", "\"\\t\"", ".", "(", "$", "currentTime", "-", "$", "this", "->", "lastLog", ")", ".", "'ms since last log. '", ".", "\"\\t\"", ".", "(", "$", "currentTime", "-", "$", "this", "->", "loggingStart", ")", ".", "'ms since start.'", ".", "PHP_EOL", ";", "$", "this", "->", "lastLog", "=", "round", "(", "microtime", "(", "true", ")", "*", "1000", ")", ";", "}" ]
Adds a logline with the time since last log @param $string
[ "Adds", "a", "logline", "with", "the", "time", "since", "last", "log" ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L161-L167
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.getSearchDbHandle
protected function getSearchDbHandle() { if ($this->searchDbHandle === null) { $path = $this->storageDir . DIRECTORY_SEPARATOR; $this->searchDbHandle = new \PDO('sqlite:' . $path . self::SEARCH_TEMP_DB); } return $this->searchDbHandle; }
php
protected function getSearchDbHandle() { if ($this->searchDbHandle === null) { $path = $this->storageDir . DIRECTORY_SEPARATOR; $this->searchDbHandle = new \PDO('sqlite:' . $path . self::SEARCH_TEMP_DB); } return $this->searchDbHandle; }
[ "protected", "function", "getSearchDbHandle", "(", ")", "{", "if", "(", "$", "this", "->", "searchDbHandle", "===", "null", ")", "{", "$", "path", "=", "$", "this", "->", "storageDir", ".", "DIRECTORY_SEPARATOR", ";", "$", "this", "->", "searchDbHandle", "=", "new", "\\", "PDO", "(", "'sqlite:'", ".", "$", "path", ".", "self", "::", "SEARCH_TEMP_DB", ")", ";", "}", "return", "$", "this", "->", "searchDbHandle", ";", "}" ]
Creates the SQLite \PDO object if it doesnt exist and returns it. @return \PDO
[ "Creates", "the", "SQLite", "\\", "PDO", "object", "if", "it", "doesnt", "exist", "and", "returns", "it", "." ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L174-L181
train
jenskooij/cloudcontrol
src/search/Indexer.php
Indexer.replaceOldIndex
public function replaceOldIndex() { $this->searchDbHandle = null; $path = $this->storageDir . DIRECTORY_SEPARATOR; rename($path . self::SEARCH_TEMP_DB, $path . 'search.db'); }
php
public function replaceOldIndex() { $this->searchDbHandle = null; $path = $this->storageDir . DIRECTORY_SEPARATOR; rename($path . self::SEARCH_TEMP_DB, $path . 'search.db'); }
[ "public", "function", "replaceOldIndex", "(", ")", "{", "$", "this", "->", "searchDbHandle", "=", "null", ";", "$", "path", "=", "$", "this", "->", "storageDir", ".", "DIRECTORY_SEPARATOR", ";", "rename", "(", "$", "path", ".", "self", "::", "SEARCH_TEMP_DB", ",", "$", "path", ".", "'search.db'", ")", ";", "}" ]
Replaces the old search index database with the new one.
[ "Replaces", "the", "old", "search", "index", "database", "with", "the", "new", "one", "." ]
76e5d9ac8f9c50d06d39a995d13cc03742536548
https://github.com/jenskooij/cloudcontrol/blob/76e5d9ac8f9c50d06d39a995d13cc03742536548/src/search/Indexer.php#L186-L191
train
lanfisis/deflection
src/Deflection/Element/Functions.php
Functions.isPublic
public function isPublic($status = null) { $this->is_public = $status !== null ? $status : $this->is_public; return $this->is_public ; }
php
public function isPublic($status = null) { $this->is_public = $status !== null ? $status : $this->is_public; return $this->is_public ; }
[ "public", "function", "isPublic", "(", "$", "status", "=", "null", ")", "{", "$", "this", "->", "is_public", "=", "$", "status", "!==", "null", "?", "$", "status", ":", "$", "this", "->", "is_public", ";", "return", "$", "this", "->", "is_public", ";", "}" ]
Is an public class @return \Deflection\Element\Functions
[ "Is", "an", "public", "class" ]
31deaf7f085d6456d8a323e7ac3cc9914fbe49a9
https://github.com/lanfisis/deflection/blob/31deaf7f085d6456d8a323e7ac3cc9914fbe49a9/src/Deflection/Element/Functions.php#L42-L46
train
lanfisis/deflection
src/Deflection/Element/Functions.php
Functions.isStatic
public function isStatic($status = null) { $this->is_static = $status !== null ? $status : $this->is_static; return $this->is_static ; }
php
public function isStatic($status = null) { $this->is_static = $status !== null ? $status : $this->is_static; return $this->is_static ; }
[ "public", "function", "isStatic", "(", "$", "status", "=", "null", ")", "{", "$", "this", "->", "is_static", "=", "$", "status", "!==", "null", "?", "$", "status", ":", "$", "this", "->", "is_static", ";", "return", "$", "this", "->", "is_static", ";", "}" ]
Is an static class @return \Deflection\Element\Functions
[ "Is", "an", "static", "class" ]
31deaf7f085d6456d8a323e7ac3cc9914fbe49a9
https://github.com/lanfisis/deflection/blob/31deaf7f085d6456d8a323e7ac3cc9914fbe49a9/src/Deflection/Element/Functions.php#L53-L57
train
Nicklas766/Comment
src/Comment/ProfileController.php
ProfileController.renderProfile
public function renderProfile() { $this->checkIsLogin(); $name = $this->di->get('session')->get("user"); $user = $this->getUserDetails($name); $views = [ ["comment/user/profile/profile", ["user" => $user], "main"] ]; if ($user->authority == "admin") { $views = [ ["comment/admin/navbar", [], "main"], ["comment/user/profile/profile", ["user" => $user], "main"] ]; } $this->di->get("pageRenderComment")->renderPage([ "views" => $views, "title" => "$user->name" ]); }
php
public function renderProfile() { $this->checkIsLogin(); $name = $this->di->get('session')->get("user"); $user = $this->getUserDetails($name); $views = [ ["comment/user/profile/profile", ["user" => $user], "main"] ]; if ($user->authority == "admin") { $views = [ ["comment/admin/navbar", [], "main"], ["comment/user/profile/profile", ["user" => $user], "main"] ]; } $this->di->get("pageRenderComment")->renderPage([ "views" => $views, "title" => "$user->name" ]); }
[ "public", "function", "renderProfile", "(", ")", "{", "$", "this", "->", "checkIsLogin", "(", ")", ";", "$", "name", "=", "$", "this", "->", "di", "->", "get", "(", "'session'", ")", "->", "get", "(", "\"user\"", ")", ";", "$", "user", "=", "$", "this", "->", "getUserDetails", "(", "$", "name", ")", ";", "$", "views", "=", "[", "[", "\"comment/user/profile/profile\"", ",", "[", "\"user\"", "=>", "$", "user", "]", ",", "\"main\"", "]", "]", ";", "if", "(", "$", "user", "->", "authority", "==", "\"admin\"", ")", "{", "$", "views", "=", "[", "[", "\"comment/admin/navbar\"", ",", "[", "]", ",", "\"main\"", "]", ",", "[", "\"comment/user/profile/profile\"", ",", "[", "\"user\"", "=>", "$", "user", "]", ",", "\"main\"", "]", "]", ";", "}", "$", "this", "->", "di", "->", "get", "(", "\"pageRenderComment\"", ")", "->", "renderPage", "(", "[", "\"views\"", "=>", "$", "views", ",", "\"title\"", "=>", "\"$user->name\"", "]", ")", ";", "}" ]
Render profile page @return void
[ "Render", "profile", "page" ]
1483eaf1ebb120b8bd6c2a1552c084b3a288ff25
https://github.com/Nicklas766/Comment/blob/1483eaf1ebb120b8bd6c2a1552c084b3a288ff25/src/Comment/ProfileController.php#L33-L56
train
ErikTrapman/CQRankingParserBundle
Parser/CQParser.php
CQParser.getName
public function getName(Crawler $crawler) { $headers = $crawler->filter('table.borderNoOpac th.raceheader b'); $values = $headers->extract(array('_text', 'b')); $name = @$values[0][0]; if ($name === false) { return 'Naam kon niet worden opgehaald. Vul zelf in.'; } return trim($name); }
php
public function getName(Crawler $crawler) { $headers = $crawler->filter('table.borderNoOpac th.raceheader b'); $values = $headers->extract(array('_text', 'b')); $name = @$values[0][0]; if ($name === false) { return 'Naam kon niet worden opgehaald. Vul zelf in.'; } return trim($name); }
[ "public", "function", "getName", "(", "Crawler", "$", "crawler", ")", "{", "$", "headers", "=", "$", "crawler", "->", "filter", "(", "'table.borderNoOpac th.raceheader b'", ")", ";", "$", "values", "=", "$", "headers", "->", "extract", "(", "array", "(", "'_text'", ",", "'b'", ")", ")", ";", "$", "name", "=", "@", "$", "values", "[", "0", "]", "[", "0", "]", ";", "if", "(", "$", "name", "===", "false", ")", "{", "return", "'Naam kon niet worden opgehaald. Vul zelf in.'", ";", "}", "return", "trim", "(", "$", "name", ")", ";", "}" ]
Naam van de uitslag.
[ "Naam", "van", "de", "uitslag", "." ]
59a6e989c7d0b157f7dce042ec58267aaf3ac6ee
https://github.com/ErikTrapman/CQRankingParserBundle/blob/59a6e989c7d0b157f7dce042ec58267aaf3ac6ee/Parser/CQParser.php#L34-L43
train
Talis90/HtmlMediaFinder
library/HtmlMediaFinder/HtmlMediaFinder.php
HtmlMediaFinder.getDownloadUrl
static function getDownloadUrl($videoUrl) { $toplevelDomain = parse_url($videoUrl); $toplevelDomain = $toplevelDomain['host']; if (!is_dir(__DIR__ . DIRECTORY_SEPARATOR . 'ProviderHandler' . DIRECTORY_SEPARATOR . $toplevelDomain)) { throw new \Exception('There is no special implementation for the provider ' . $toplevelDomain . '!'); } require_once __DIR__ . DIRECTORY_SEPARATOR . 'ProviderHandler' . DIRECTORY_SEPARATOR . $toplevelDomain . DIRECTORY_SEPARATOR . 'Provider.php'; $provider = new \Provider($videoUrl); return $provider->getDownloadUrl(); }
php
static function getDownloadUrl($videoUrl) { $toplevelDomain = parse_url($videoUrl); $toplevelDomain = $toplevelDomain['host']; if (!is_dir(__DIR__ . DIRECTORY_SEPARATOR . 'ProviderHandler' . DIRECTORY_SEPARATOR . $toplevelDomain)) { throw new \Exception('There is no special implementation for the provider ' . $toplevelDomain . '!'); } require_once __DIR__ . DIRECTORY_SEPARATOR . 'ProviderHandler' . DIRECTORY_SEPARATOR . $toplevelDomain . DIRECTORY_SEPARATOR . 'Provider.php'; $provider = new \Provider($videoUrl); return $provider->getDownloadUrl(); }
[ "static", "function", "getDownloadUrl", "(", "$", "videoUrl", ")", "{", "$", "toplevelDomain", "=", "parse_url", "(", "$", "videoUrl", ")", ";", "$", "toplevelDomain", "=", "$", "toplevelDomain", "[", "'host'", "]", ";", "if", "(", "!", "is_dir", "(", "__DIR__", ".", "DIRECTORY_SEPARATOR", ".", "'ProviderHandler'", ".", "DIRECTORY_SEPARATOR", ".", "$", "toplevelDomain", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'There is no special implementation for the provider '", ".", "$", "toplevelDomain", ".", "'!'", ")", ";", "}", "require_once", "__DIR__", ".", "DIRECTORY_SEPARATOR", ".", "'ProviderHandler'", ".", "DIRECTORY_SEPARATOR", ".", "$", "toplevelDomain", ".", "DIRECTORY_SEPARATOR", ".", "'Provider.php'", ";", "$", "provider", "=", "new", "\\", "Provider", "(", "$", "videoUrl", ")", ";", "return", "$", "provider", "->", "getDownloadUrl", "(", ")", ";", "}" ]
Get the download url of a video url @param string $videoUrl @return string
[ "Get", "the", "download", "url", "of", "a", "video", "url" ]
fd19212a88d5d3f78d20aeea1accf7be427643b0
https://github.com/Talis90/HtmlMediaFinder/blob/fd19212a88d5d3f78d20aeea1accf7be427643b0/library/HtmlMediaFinder/HtmlMediaFinder.php#L17-L28
train
Aviogram/Common
src/Hydrator/ByConfig.php
ByConfig.hydrate
public static function hydrate(array $data, ByConfigBuilder $config) { // When entity is not available. Only use the collection to set the data if ($config->getEntity() === false) { return $config->getCollectionEntity($data); } // When there is no collection specified. Make sure there will be an array to iterate through if ($config->isCollection() === false) { $data = array($data); } $rows = array(); // Loop through the data foreach ($data as $index => $row) { $rows[$index] = $entity = $config->getEntity(); foreach ($row as $field => $value) { // Skip field if not defined in the configuration if ($config->hasField($field) === false) { $catchAll = $config->getCatchAllSetter(); if ($catchAll !== null) { call_user_func(array($entity, $catchAll), $field, $value); } continue; } $callable = array($entity, $config->getSetter($field)); if ($config->isInclude($field) === true) { if (is_array($value) === false) { throw new Exception\HydrateFailed(sprintf(static::$exceptions[1], $field, gettype($value))); } $value = static::hydrate($value, $config->getInclude($field)); } else if ($config->getFormatter($field) !== null) { $value = call_user_func($config->getFormatter($field), $value); } // Add the value call_user_func($callable, $value); } } return ($config->isCollection() === true) ? $config->getCollectionEntity($rows) : $entity; }
php
public static function hydrate(array $data, ByConfigBuilder $config) { // When entity is not available. Only use the collection to set the data if ($config->getEntity() === false) { return $config->getCollectionEntity($data); } // When there is no collection specified. Make sure there will be an array to iterate through if ($config->isCollection() === false) { $data = array($data); } $rows = array(); // Loop through the data foreach ($data as $index => $row) { $rows[$index] = $entity = $config->getEntity(); foreach ($row as $field => $value) { // Skip field if not defined in the configuration if ($config->hasField($field) === false) { $catchAll = $config->getCatchAllSetter(); if ($catchAll !== null) { call_user_func(array($entity, $catchAll), $field, $value); } continue; } $callable = array($entity, $config->getSetter($field)); if ($config->isInclude($field) === true) { if (is_array($value) === false) { throw new Exception\HydrateFailed(sprintf(static::$exceptions[1], $field, gettype($value))); } $value = static::hydrate($value, $config->getInclude($field)); } else if ($config->getFormatter($field) !== null) { $value = call_user_func($config->getFormatter($field), $value); } // Add the value call_user_func($callable, $value); } } return ($config->isCollection() === true) ? $config->getCollectionEntity($rows) : $entity; }
[ "public", "static", "function", "hydrate", "(", "array", "$", "data", ",", "ByConfigBuilder", "$", "config", ")", "{", "// When entity is not available. Only use the collection to set the data\r", "if", "(", "$", "config", "->", "getEntity", "(", ")", "===", "false", ")", "{", "return", "$", "config", "->", "getCollectionEntity", "(", "$", "data", ")", ";", "}", "// When there is no collection specified. Make sure there will be an array to iterate through\r", "if", "(", "$", "config", "->", "isCollection", "(", ")", "===", "false", ")", "{", "$", "data", "=", "array", "(", "$", "data", ")", ";", "}", "$", "rows", "=", "array", "(", ")", ";", "// Loop through the data\r", "foreach", "(", "$", "data", "as", "$", "index", "=>", "$", "row", ")", "{", "$", "rows", "[", "$", "index", "]", "=", "$", "entity", "=", "$", "config", "->", "getEntity", "(", ")", ";", "foreach", "(", "$", "row", "as", "$", "field", "=>", "$", "value", ")", "{", "// Skip field if not defined in the configuration\r", "if", "(", "$", "config", "->", "hasField", "(", "$", "field", ")", "===", "false", ")", "{", "$", "catchAll", "=", "$", "config", "->", "getCatchAllSetter", "(", ")", ";", "if", "(", "$", "catchAll", "!==", "null", ")", "{", "call_user_func", "(", "array", "(", "$", "entity", ",", "$", "catchAll", ")", ",", "$", "field", ",", "$", "value", ")", ";", "}", "continue", ";", "}", "$", "callable", "=", "array", "(", "$", "entity", ",", "$", "config", "->", "getSetter", "(", "$", "field", ")", ")", ";", "if", "(", "$", "config", "->", "isInclude", "(", "$", "field", ")", "===", "true", ")", "{", "if", "(", "is_array", "(", "$", "value", ")", "===", "false", ")", "{", "throw", "new", "Exception", "\\", "HydrateFailed", "(", "sprintf", "(", "static", "::", "$", "exceptions", "[", "1", "]", ",", "$", "field", ",", "gettype", "(", "$", "value", ")", ")", ")", ";", "}", "$", "value", "=", "static", "::", "hydrate", "(", "$", "value", ",", "$", "config", "->", "getInclude", "(", "$", "field", ")", ")", ";", "}", "else", "if", "(", "$", "config", "->", "getFormatter", "(", "$", "field", ")", "!==", "null", ")", "{", "$", "value", "=", "call_user_func", "(", "$", "config", "->", "getFormatter", "(", "$", "field", ")", ",", "$", "value", ")", ";", "}", "// Add the value\r", "call_user_func", "(", "$", "callable", ",", "$", "value", ")", ";", "}", "}", "return", "(", "$", "config", "->", "isCollection", "(", ")", "===", "true", ")", "?", "$", "config", "->", "getCollectionEntity", "(", "$", "rows", ")", ":", "$", "entity", ";", "}" ]
Hydrate array data to an object based on the configuration given @param array $data @param ByConfigBuilder $config @return object | \ArrayIterator on a collection
[ "Hydrate", "array", "data", "to", "an", "object", "based", "on", "the", "configuration", "given" ]
bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5
https://github.com/Aviogram/Common/blob/bcff2e409cccd4791a3f9bca0b2cdd70c25ddec5/src/Hydrator/ByConfig.php#L23-L71
train
romm/configuration_object
Classes/Legacy/Validation/ValidatorResolver.php
ValidatorResolver.createValidator
public function createValidator($validatorType, array $validatorOptions = []) { try { /** * @todo remove throwing Exceptions in resolveValidatorObjectName */ $validatorObjectName = $this->resolveValidatorObjectName($validatorType); $validator = $this->objectManager->get($validatorObjectName, $validatorOptions); if (!($validator instanceof \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface)) { throw new Exception\NoSuchValidatorException('The validator "' . $validatorObjectName . '" does not implement TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface!', 1300694875); } return $validator; } catch (NoSuchValidatorException $e) { return null; } }
php
public function createValidator($validatorType, array $validatorOptions = []) { try { /** * @todo remove throwing Exceptions in resolveValidatorObjectName */ $validatorObjectName = $this->resolveValidatorObjectName($validatorType); $validator = $this->objectManager->get($validatorObjectName, $validatorOptions); if (!($validator instanceof \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface)) { throw new Exception\NoSuchValidatorException('The validator "' . $validatorObjectName . '" does not implement TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface!', 1300694875); } return $validator; } catch (NoSuchValidatorException $e) { return null; } }
[ "public", "function", "createValidator", "(", "$", "validatorType", ",", "array", "$", "validatorOptions", "=", "[", "]", ")", "{", "try", "{", "/**\n * @todo remove throwing Exceptions in resolveValidatorObjectName\n */", "$", "validatorObjectName", "=", "$", "this", "->", "resolveValidatorObjectName", "(", "$", "validatorType", ")", ";", "$", "validator", "=", "$", "this", "->", "objectManager", "->", "get", "(", "$", "validatorObjectName", ",", "$", "validatorOptions", ")", ";", "if", "(", "!", "(", "$", "validator", "instanceof", "\\", "TYPO3", "\\", "CMS", "\\", "Extbase", "\\", "Validation", "\\", "Validator", "\\", "ValidatorInterface", ")", ")", "{", "throw", "new", "Exception", "\\", "NoSuchValidatorException", "(", "'The validator \"'", ".", "$", "validatorObjectName", ".", "'\" does not implement TYPO3\\CMS\\Extbase\\Validation\\Validator\\ValidatorInterface!'", ",", "1300694875", ")", ";", "}", "return", "$", "validator", ";", "}", "catch", "(", "NoSuchValidatorException", "$", "e", ")", "{", "return", "null", ";", "}", "}" ]
Get a validator for a given data type. Returns a validator implementing the \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface or NULL if no validator could be resolved. @param string $validatorType Either one of the built-in data types or fully qualified validator class name @param array $validatorOptions Options to be passed to the validator @return \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface Validator or NULL if none found.
[ "Get", "a", "validator", "for", "a", "given", "data", "type", ".", "Returns", "a", "validator", "implementing", "the", "\\", "TYPO3", "\\", "CMS", "\\", "Extbase", "\\", "Validation", "\\", "Validator", "\\", "ValidatorInterface", "or", "NULL", "if", "no", "validator", "could", "be", "resolved", "." ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Legacy/Validation/ValidatorResolver.php#L103-L121
train
romm/configuration_object
Classes/Legacy/Validation/ValidatorResolver.php
ValidatorResolver.resolveValidatorObjectName
protected function resolveValidatorObjectName($validatorName) { if (strpos($validatorName, ':') !== false || strpbrk($validatorName, '_\\') === false) { // Found shorthand validator, either extbase or foreign extension // NotEmpty or Acme.MyPck.Ext:MyValidator list($extensionName, $extensionValidatorName) = explode(':', $validatorName); if ($validatorName !== $extensionName && $extensionValidatorName !== '') { // Shorthand custom if (strpos($extensionName, '.') !== false) { $extensionNameParts = explode('.', $extensionName); $extensionName = array_pop($extensionNameParts); $vendorName = implode('\\', $extensionNameParts); $possibleClassName = $vendorName . '\\' . $extensionName . '\\Validation\\Validator\\' . $extensionValidatorName; } else { $possibleClassName = 'Tx_' . $extensionName . '_Validation_Validator_' . $extensionValidatorName; } } else { // Shorthand built in $possibleClassName = 'TYPO3\\CMS\\Extbase\\Validation\\Validator\\' . $this->getValidatorType($validatorName); } } else { // Full qualified // Tx_MyExt_Validation_Validator_MyValidator or \Acme\Ext\Validation\Validator\FooValidator $possibleClassName = $validatorName; if (!empty($possibleClassName) && $possibleClassName[0] === '\\') { $possibleClassName = substr($possibleClassName, 1); } } if (substr($possibleClassName, - strlen('Validator')) !== 'Validator') { $possibleClassName .= 'Validator'; } if (class_exists($possibleClassName)) { $possibleClassNameInterfaces = class_implements($possibleClassName); if (!in_array(\TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface::class, $possibleClassNameInterfaces)) { // The guessed validatorname is a valid class name, but does not implement the ValidatorInterface throw new NoSuchValidatorException('Validator class ' . $validatorName . ' must implement \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface', 1365776838); } $resolvedValidatorName = $possibleClassName; } else { throw new NoSuchValidatorException('Validator class ' . $validatorName . ' does not exist', 1365799920); } return $resolvedValidatorName; }
php
protected function resolveValidatorObjectName($validatorName) { if (strpos($validatorName, ':') !== false || strpbrk($validatorName, '_\\') === false) { // Found shorthand validator, either extbase or foreign extension // NotEmpty or Acme.MyPck.Ext:MyValidator list($extensionName, $extensionValidatorName) = explode(':', $validatorName); if ($validatorName !== $extensionName && $extensionValidatorName !== '') { // Shorthand custom if (strpos($extensionName, '.') !== false) { $extensionNameParts = explode('.', $extensionName); $extensionName = array_pop($extensionNameParts); $vendorName = implode('\\', $extensionNameParts); $possibleClassName = $vendorName . '\\' . $extensionName . '\\Validation\\Validator\\' . $extensionValidatorName; } else { $possibleClassName = 'Tx_' . $extensionName . '_Validation_Validator_' . $extensionValidatorName; } } else { // Shorthand built in $possibleClassName = 'TYPO3\\CMS\\Extbase\\Validation\\Validator\\' . $this->getValidatorType($validatorName); } } else { // Full qualified // Tx_MyExt_Validation_Validator_MyValidator or \Acme\Ext\Validation\Validator\FooValidator $possibleClassName = $validatorName; if (!empty($possibleClassName) && $possibleClassName[0] === '\\') { $possibleClassName = substr($possibleClassName, 1); } } if (substr($possibleClassName, - strlen('Validator')) !== 'Validator') { $possibleClassName .= 'Validator'; } if (class_exists($possibleClassName)) { $possibleClassNameInterfaces = class_implements($possibleClassName); if (!in_array(\TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface::class, $possibleClassNameInterfaces)) { // The guessed validatorname is a valid class name, but does not implement the ValidatorInterface throw new NoSuchValidatorException('Validator class ' . $validatorName . ' must implement \TYPO3\CMS\Extbase\Validation\Validator\ValidatorInterface', 1365776838); } $resolvedValidatorName = $possibleClassName; } else { throw new NoSuchValidatorException('Validator class ' . $validatorName . ' does not exist', 1365799920); } return $resolvedValidatorName; }
[ "protected", "function", "resolveValidatorObjectName", "(", "$", "validatorName", ")", "{", "if", "(", "strpos", "(", "$", "validatorName", ",", "':'", ")", "!==", "false", "||", "strpbrk", "(", "$", "validatorName", ",", "'_\\\\'", ")", "===", "false", ")", "{", "// Found shorthand validator, either extbase or foreign extension", "// NotEmpty or Acme.MyPck.Ext:MyValidator", "list", "(", "$", "extensionName", ",", "$", "extensionValidatorName", ")", "=", "explode", "(", "':'", ",", "$", "validatorName", ")", ";", "if", "(", "$", "validatorName", "!==", "$", "extensionName", "&&", "$", "extensionValidatorName", "!==", "''", ")", "{", "// Shorthand custom", "if", "(", "strpos", "(", "$", "extensionName", ",", "'.'", ")", "!==", "false", ")", "{", "$", "extensionNameParts", "=", "explode", "(", "'.'", ",", "$", "extensionName", ")", ";", "$", "extensionName", "=", "array_pop", "(", "$", "extensionNameParts", ")", ";", "$", "vendorName", "=", "implode", "(", "'\\\\'", ",", "$", "extensionNameParts", ")", ";", "$", "possibleClassName", "=", "$", "vendorName", ".", "'\\\\'", ".", "$", "extensionName", ".", "'\\\\Validation\\\\Validator\\\\'", ".", "$", "extensionValidatorName", ";", "}", "else", "{", "$", "possibleClassName", "=", "'Tx_'", ".", "$", "extensionName", ".", "'_Validation_Validator_'", ".", "$", "extensionValidatorName", ";", "}", "}", "else", "{", "// Shorthand built in", "$", "possibleClassName", "=", "'TYPO3\\\\CMS\\\\Extbase\\\\Validation\\\\Validator\\\\'", ".", "$", "this", "->", "getValidatorType", "(", "$", "validatorName", ")", ";", "}", "}", "else", "{", "// Full qualified", "// Tx_MyExt_Validation_Validator_MyValidator or \\Acme\\Ext\\Validation\\Validator\\FooValidator", "$", "possibleClassName", "=", "$", "validatorName", ";", "if", "(", "!", "empty", "(", "$", "possibleClassName", ")", "&&", "$", "possibleClassName", "[", "0", "]", "===", "'\\\\'", ")", "{", "$", "possibleClassName", "=", "substr", "(", "$", "possibleClassName", ",", "1", ")", ";", "}", "}", "if", "(", "substr", "(", "$", "possibleClassName", ",", "-", "strlen", "(", "'Validator'", ")", ")", "!==", "'Validator'", ")", "{", "$", "possibleClassName", ".=", "'Validator'", ";", "}", "if", "(", "class_exists", "(", "$", "possibleClassName", ")", ")", "{", "$", "possibleClassNameInterfaces", "=", "class_implements", "(", "$", "possibleClassName", ")", ";", "if", "(", "!", "in_array", "(", "\\", "TYPO3", "\\", "CMS", "\\", "Extbase", "\\", "Validation", "\\", "Validator", "\\", "ValidatorInterface", "::", "class", ",", "$", "possibleClassNameInterfaces", ")", ")", "{", "// The guessed validatorname is a valid class name, but does not implement the ValidatorInterface", "throw", "new", "NoSuchValidatorException", "(", "'Validator class '", ".", "$", "validatorName", ".", "' must implement \\TYPO3\\CMS\\Extbase\\Validation\\Validator\\ValidatorInterface'", ",", "1365776838", ")", ";", "}", "$", "resolvedValidatorName", "=", "$", "possibleClassName", ";", "}", "else", "{", "throw", "new", "NoSuchValidatorException", "(", "'Validator class '", ".", "$", "validatorName", ".", "' does not exist'", ",", "1365799920", ")", ";", "}", "return", "$", "resolvedValidatorName", ";", "}" ]
Returns an object of an appropriate validator for the given class. If no validator is available FALSE is returned @param string $validatorName Either the fully qualified class name of the validator or the short name of a built-in validator @throws Exception\NoSuchValidatorException @return string Name of the validator object
[ "Returns", "an", "object", "of", "an", "appropriate", "validator", "for", "the", "given", "class", ".", "If", "no", "validator", "is", "available", "FALSE", "is", "returned" ]
d3a40903386c2e0766bd8279337fe6da45cf5ce3
https://github.com/romm/configuration_object/blob/d3a40903386c2e0766bd8279337fe6da45cf5ce3/Classes/Legacy/Validation/ValidatorResolver.php#L437-L483
train
duncan3dc/serial
src/Json.php
Json.decode
public static function decode($string) { if (!$string) { return new ArrayObject(); } $array = json_decode($string, true); static::checkLastError(); if (!is_array($array)) { $array = []; } return ArrayObject::make($array); }
php
public static function decode($string) { if (!$string) { return new ArrayObject(); } $array = json_decode($string, true); static::checkLastError(); if (!is_array($array)) { $array = []; } return ArrayObject::make($array); }
[ "public", "static", "function", "decode", "(", "$", "string", ")", "{", "if", "(", "!", "$", "string", ")", "{", "return", "new", "ArrayObject", "(", ")", ";", "}", "$", "array", "=", "json_decode", "(", "$", "string", ",", "true", ")", ";", "static", "::", "checkLastError", "(", ")", ";", "if", "(", "!", "is_array", "(", "$", "array", ")", ")", "{", "$", "array", "=", "[", "]", ";", "}", "return", "ArrayObject", "::", "make", "(", "$", "array", ")", ";", "}" ]
Convert a JSON string to an array. {@inheritDoc}
[ "Convert", "a", "JSON", "string", "to", "an", "array", "." ]
2e40127a0a364ee1bd6f655b0f5b5d4a035a5716
https://github.com/duncan3dc/serial/blob/2e40127a0a364ee1bd6f655b0f5b5d4a035a5716/src/Json.php#L36-L51
train
ZendExperts/phpids
docs/examples/cakephp/ids.php
IdsComponent.detect
public function detect(&$controller) { $this->controller = &$controller; $this->name = Inflector::singularize($this->controller->name); #set include path for IDS and store old one $path = get_include_path(); set_include_path( VENDORS . 'phpids/'); #require the needed files vendor('phpids/IDS/Init'); #add request url and user agent $_REQUEST['IDS_request_uri'] = $_SERVER['REQUEST_URI']; if (isset($_SERVER['HTTP_USER_AGENT'])) { $_REQUEST['IDS_user_agent'] = $_SERVER['HTTP_USER_AGENT']; } #init the PHPIDS and pass the REQUEST array $this->init = IDS_Init::init(); $ids = new IDS_Monitor($_REQUEST, $this->init); $result = $ids->run(); // Re-set include path set_include_path($path); if (!$result->isEmpty()) { $this->react($result); } return true; }
php
public function detect(&$controller) { $this->controller = &$controller; $this->name = Inflector::singularize($this->controller->name); #set include path for IDS and store old one $path = get_include_path(); set_include_path( VENDORS . 'phpids/'); #require the needed files vendor('phpids/IDS/Init'); #add request url and user agent $_REQUEST['IDS_request_uri'] = $_SERVER['REQUEST_URI']; if (isset($_SERVER['HTTP_USER_AGENT'])) { $_REQUEST['IDS_user_agent'] = $_SERVER['HTTP_USER_AGENT']; } #init the PHPIDS and pass the REQUEST array $this->init = IDS_Init::init(); $ids = new IDS_Monitor($_REQUEST, $this->init); $result = $ids->run(); // Re-set include path set_include_path($path); if (!$result->isEmpty()) { $this->react($result); } return true; }
[ "public", "function", "detect", "(", "&", "$", "controller", ")", "{", "$", "this", "->", "controller", "=", "&", "$", "controller", ";", "$", "this", "->", "name", "=", "Inflector", "::", "singularize", "(", "$", "this", "->", "controller", "->", "name", ")", ";", "#set include path for IDS and store old one", "$", "path", "=", "get_include_path", "(", ")", ";", "set_include_path", "(", "VENDORS", ".", "'phpids/'", ")", ";", "#require the needed files", "vendor", "(", "'phpids/IDS/Init'", ")", ";", "#add request url and user agent", "$", "_REQUEST", "[", "'IDS_request_uri'", "]", "=", "$", "_SERVER", "[", "'REQUEST_URI'", "]", ";", "if", "(", "isset", "(", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ")", ")", "{", "$", "_REQUEST", "[", "'IDS_user_agent'", "]", "=", "$", "_SERVER", "[", "'HTTP_USER_AGENT'", "]", ";", "}", "#init the PHPIDS and pass the REQUEST array", "$", "this", "->", "init", "=", "IDS_Init", "::", "init", "(", ")", ";", "$", "ids", "=", "new", "IDS_Monitor", "(", "$", "_REQUEST", ",", "$", "this", "->", "init", ")", ";", "$", "result", "=", "$", "ids", "->", "run", "(", ")", ";", "// Re-set include path", "set_include_path", "(", "$", "path", ")", ";", "if", "(", "!", "$", "result", "->", "isEmpty", "(", ")", ")", "{", "$", "this", "->", "react", "(", "$", "result", ")", ";", "}", "return", "true", ";", "}" ]
This function includes the IDS vendor parts and runs the detection routines on the request array. @param object cake controller object @return boolean
[ "This", "function", "includes", "the", "IDS", "vendor", "parts", "and", "runs", "the", "detection", "routines", "on", "the", "request", "array", "." ]
f30df04eea47b94d056e2ae9ec8fea1c626f1c03
https://github.com/ZendExperts/phpids/blob/f30df04eea47b94d056e2ae9ec8fea1c626f1c03/docs/examples/cakephp/ids.php#L105-L136
train
ZendExperts/phpids
docs/examples/cakephp/ids.php
IdsComponent.react
private function react(IDS_Report $result) { $new = $this->controller ->Session ->read('IDS.Impact') + $result->getImpact(); $this->controller->Session->write('IDS.Impact', $new); $impact = $this->controller->Session->read('IDS.Impact'); if ($impact >= $this->threshold['kick']) { $this->idslog($result, 3, $impact); $this->idsmail($result); $this->idskick($result); return true; } else if ($impact >= $this->threshold['warn']) { $this->idslog($result, 2, $impact); $this->idsmail($result); $this->idswarn($result); return true; } else if ($impact >= $this->threshold['mail']) { $this->idslog($result, 1, $impact); $this->idsmail($result); return true; } else if ($impact >= $this->threshold['log']) { $this->idslog($result, 0, $impact); return true; } else { return true; } }
php
private function react(IDS_Report $result) { $new = $this->controller ->Session ->read('IDS.Impact') + $result->getImpact(); $this->controller->Session->write('IDS.Impact', $new); $impact = $this->controller->Session->read('IDS.Impact'); if ($impact >= $this->threshold['kick']) { $this->idslog($result, 3, $impact); $this->idsmail($result); $this->idskick($result); return true; } else if ($impact >= $this->threshold['warn']) { $this->idslog($result, 2, $impact); $this->idsmail($result); $this->idswarn($result); return true; } else if ($impact >= $this->threshold['mail']) { $this->idslog($result, 1, $impact); $this->idsmail($result); return true; } else if ($impact >= $this->threshold['log']) { $this->idslog($result, 0, $impact); return true; } else { return true; } }
[ "private", "function", "react", "(", "IDS_Report", "$", "result", ")", "{", "$", "new", "=", "$", "this", "->", "controller", "->", "Session", "->", "read", "(", "'IDS.Impact'", ")", "+", "$", "result", "->", "getImpact", "(", ")", ";", "$", "this", "->", "controller", "->", "Session", "->", "write", "(", "'IDS.Impact'", ",", "$", "new", ")", ";", "$", "impact", "=", "$", "this", "->", "controller", "->", "Session", "->", "read", "(", "'IDS.Impact'", ")", ";", "if", "(", "$", "impact", ">=", "$", "this", "->", "threshold", "[", "'kick'", "]", ")", "{", "$", "this", "->", "idslog", "(", "$", "result", ",", "3", ",", "$", "impact", ")", ";", "$", "this", "->", "idsmail", "(", "$", "result", ")", ";", "$", "this", "->", "idskick", "(", "$", "result", ")", ";", "return", "true", ";", "}", "else", "if", "(", "$", "impact", ">=", "$", "this", "->", "threshold", "[", "'warn'", "]", ")", "{", "$", "this", "->", "idslog", "(", "$", "result", ",", "2", ",", "$", "impact", ")", ";", "$", "this", "->", "idsmail", "(", "$", "result", ")", ";", "$", "this", "->", "idswarn", "(", "$", "result", ")", ";", "return", "true", ";", "}", "else", "if", "(", "$", "impact", ">=", "$", "this", "->", "threshold", "[", "'mail'", "]", ")", "{", "$", "this", "->", "idslog", "(", "$", "result", ",", "1", ",", "$", "impact", ")", ";", "$", "this", "->", "idsmail", "(", "$", "result", ")", ";", "return", "true", ";", "}", "else", "if", "(", "$", "impact", ">=", "$", "this", "->", "threshold", "[", "'log'", "]", ")", "{", "$", "this", "->", "idslog", "(", "$", "result", ",", "0", ",", "$", "impact", ")", ";", "return", "true", ";", "}", "else", "{", "return", "true", ";", "}", "}" ]
This function rects on the values in the incoming results array. Depending on the impact value certain actions are performed. @param IDS_Report $result @return boolean
[ "This", "function", "rects", "on", "the", "values", "in", "the", "incoming", "results", "array", "." ]
f30df04eea47b94d056e2ae9ec8fea1c626f1c03
https://github.com/ZendExperts/phpids/blob/f30df04eea47b94d056e2ae9ec8fea1c626f1c03/docs/examples/cakephp/ids.php#L148-L178
train
CismonX/CaptchaQueue
src/Captcha.php
Captcha.register
static function register(string $name, CaptchaInterface $captcha) { if (isset(self::$_captchaList[$name])) Console::warning("Overwriting captcha generator \"$name\"."); self::$_captchaList[$name] = $captcha; self::enable($name); }
php
static function register(string $name, CaptchaInterface $captcha) { if (isset(self::$_captchaList[$name])) Console::warning("Overwriting captcha generator \"$name\"."); self::$_captchaList[$name] = $captcha; self::enable($name); }
[ "static", "function", "register", "(", "string", "$", "name", ",", "CaptchaInterface", "$", "captcha", ")", "{", "if", "(", "isset", "(", "self", "::", "$", "_captchaList", "[", "$", "name", "]", ")", ")", "Console", "::", "warning", "(", "\"Overwriting captcha generator \\\"$name\\\".\"", ")", ";", "self", "::", "$", "_captchaList", "[", "$", "name", "]", "=", "$", "captcha", ";", "self", "::", "enable", "(", "$", "name", ")", ";", "}" ]
Register a new captcha generator. @param string $name @param CaptchaInterface $captcha
[ "Register", "a", "new", "captcha", "generator", "." ]
bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975
https://github.com/CismonX/CaptchaQueue/blob/bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975/src/Captcha.php#L39-L44
train
CismonX/CaptchaQueue
src/Captcha.php
Captcha.enable
static function enable(string $name) { if (!isset(self::$_captchaList[$name])) { Console::warning("Captcha generator \"$name\" do not exist."); return; } self::$_enableList = self::$_enableList + [$name]; }
php
static function enable(string $name) { if (!isset(self::$_captchaList[$name])) { Console::warning("Captcha generator \"$name\" do not exist."); return; } self::$_enableList = self::$_enableList + [$name]; }
[ "static", "function", "enable", "(", "string", "$", "name", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "_captchaList", "[", "$", "name", "]", ")", ")", "{", "Console", "::", "warning", "(", "\"Captcha generator \\\"$name\\\" do not exist.\"", ")", ";", "return", ";", "}", "self", "::", "$", "_enableList", "=", "self", "::", "$", "_enableList", "+", "[", "$", "name", "]", ";", "}" ]
Mark a captcha generator as enabled. @param string $name
[ "Mark", "a", "captcha", "generator", "as", "enabled", "." ]
bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975
https://github.com/CismonX/CaptchaQueue/blob/bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975/src/Captcha.php#L50-L56
train
CismonX/CaptchaQueue
src/Captcha.php
Captcha.disable
static function disable(string $name) { $pos = array_search($name, self::$_enableList); if ($pos === false) return; unset(self::$_enableList[$pos]); }
php
static function disable(string $name) { $pos = array_search($name, self::$_enableList); if ($pos === false) return; unset(self::$_enableList[$pos]); }
[ "static", "function", "disable", "(", "string", "$", "name", ")", "{", "$", "pos", "=", "array_search", "(", "$", "name", ",", "self", "::", "$", "_enableList", ")", ";", "if", "(", "$", "pos", "===", "false", ")", "return", ";", "unset", "(", "self", "::", "$", "_enableList", "[", "$", "pos", "]", ")", ";", "}" ]
Mark a captcha generator as disabled. @param string $name
[ "Mark", "a", "captcha", "generator", "as", "disabled", "." ]
bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975
https://github.com/CismonX/CaptchaQueue/blob/bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975/src/Captcha.php#L62-L67
train
CismonX/CaptchaQueue
src/Captcha.php
Captcha.init
static function init() { mt_srand(); foreach (self::$_captchaList as $captcha) $captcha->init(); if (!is_resource(self::$_queue)) self::_initQueue(); self::$_timer_id = Timer::add(Config::get('CAPTCHA_TIMER_INTERVAL'), function () { $obj = self::_chooseOne(); if ($obj->getStatus() != $obj::STATUS_INIT) return; if (msg_stat_queue(self::$_queue)['msg_qnum'] < Config::get('CAPTCHA_CACHE_MAX')) self::_chooseOne()->generate(); }); }
php
static function init() { mt_srand(); foreach (self::$_captchaList as $captcha) $captcha->init(); if (!is_resource(self::$_queue)) self::_initQueue(); self::$_timer_id = Timer::add(Config::get('CAPTCHA_TIMER_INTERVAL'), function () { $obj = self::_chooseOne(); if ($obj->getStatus() != $obj::STATUS_INIT) return; if (msg_stat_queue(self::$_queue)['msg_qnum'] < Config::get('CAPTCHA_CACHE_MAX')) self::_chooseOne()->generate(); }); }
[ "static", "function", "init", "(", ")", "{", "mt_srand", "(", ")", ";", "foreach", "(", "self", "::", "$", "_captchaList", "as", "$", "captcha", ")", "$", "captcha", "->", "init", "(", ")", ";", "if", "(", "!", "is_resource", "(", "self", "::", "$", "_queue", ")", ")", "self", "::", "_initQueue", "(", ")", ";", "self", "::", "$", "_timer_id", "=", "Timer", "::", "add", "(", "Config", "::", "get", "(", "'CAPTCHA_TIMER_INTERVAL'", ")", ",", "function", "(", ")", "{", "$", "obj", "=", "self", "::", "_chooseOne", "(", ")", ";", "if", "(", "$", "obj", "->", "getStatus", "(", ")", "!=", "$", "obj", "::", "STATUS_INIT", ")", "return", ";", "if", "(", "msg_stat_queue", "(", "self", "::", "$", "_queue", ")", "[", "'msg_qnum'", "]", "<", "Config", "::", "get", "(", "'CAPTCHA_CACHE_MAX'", ")", ")", "self", "::", "_chooseOne", "(", ")", "->", "generate", "(", ")", ";", "}", ")", ";", "}" ]
Initialize all registered captcha generators and start generating captcha.
[ "Initialize", "all", "registered", "captcha", "generators", "and", "start", "generating", "captcha", "." ]
bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975
https://github.com/CismonX/CaptchaQueue/blob/bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975/src/Captcha.php#L79-L92
train
CismonX/CaptchaQueue
src/Captcha.php
Captcha.destroy
static function destroy() { Timer::del(self::$_timer_id); foreach (self::$_captchaList as $captcha) $captcha->destroy(); self::$_captchaList = self::$_enableList = []; msg_remove_queue(self::$_queue); }
php
static function destroy() { Timer::del(self::$_timer_id); foreach (self::$_captchaList as $captcha) $captcha->destroy(); self::$_captchaList = self::$_enableList = []; msg_remove_queue(self::$_queue); }
[ "static", "function", "destroy", "(", ")", "{", "Timer", "::", "del", "(", "self", "::", "$", "_timer_id", ")", ";", "foreach", "(", "self", "::", "$", "_captchaList", "as", "$", "captcha", ")", "$", "captcha", "->", "destroy", "(", ")", ";", "self", "::", "$", "_captchaList", "=", "self", "::", "$", "_enableList", "=", "[", "]", ";", "msg_remove_queue", "(", "self", "::", "$", "_queue", ")", ";", "}" ]
Destroy captcha generators.
[ "Destroy", "captcha", "generators", "." ]
bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975
https://github.com/CismonX/CaptchaQueue/blob/bcf0fbeb4d52de471a99e9f744c4ad7ca2e59975/src/Captcha.php#L103-L109
train
Shelob9/jp-tax-query
class-jp-tax-query.php
JP_API_Tax_Query.register_routes
public function register_routes( $routes ) { $route = JP_API_ROUTE; $routes[] = array( //endpoints "/{$route}/tax-query" => array( array( array( $this, 'tax_query' ), WP_JSON_Server::READABLE | WP_JSON_Server::ACCEPT_JSON ), ), ); return $routes; }
php
public function register_routes( $routes ) { $route = JP_API_ROUTE; $routes[] = array( //endpoints "/{$route}/tax-query" => array( array( array( $this, 'tax_query' ), WP_JSON_Server::READABLE | WP_JSON_Server::ACCEPT_JSON ), ), ); return $routes; }
[ "public", "function", "register_routes", "(", "$", "routes", ")", "{", "$", "route", "=", "JP_API_ROUTE", ";", "$", "routes", "[", "]", "=", "array", "(", "//endpoints", "\"/{$route}/tax-query\"", "=>", "array", "(", "array", "(", "array", "(", "$", "this", ",", "'tax_query'", ")", ",", "WP_JSON_Server", "::", "READABLE", "|", "WP_JSON_Server", "::", "ACCEPT_JSON", ")", ",", ")", ",", ")", ";", "return", "$", "routes", ";", "}" ]
Register the post-related routes @param array $routes Existing routes @return array Modified routes
[ "Register", "the", "post", "-", "related", "routes" ]
0c0376018323aa46c95e01a3ce386b1de1640377
https://github.com/Shelob9/jp-tax-query/blob/0c0376018323aa46c95e01a3ce386b1de1640377/class-jp-tax-query.php#L28-L42
train
ekyna/PaymentBundle
Model/PaymentStates.php
PaymentStates.getNotifiableStates
static public function getNotifiableStates() { $states = []; foreach (static::getConfig() as $state => $config) { if ($config[2]) { $states[] = $state; } } return $states; }
php
static public function getNotifiableStates() { $states = []; foreach (static::getConfig() as $state => $config) { if ($config[2]) { $states[] = $state; } } return $states; }
[ "static", "public", "function", "getNotifiableStates", "(", ")", "{", "$", "states", "=", "[", "]", ";", "foreach", "(", "static", "::", "getConfig", "(", ")", "as", "$", "state", "=>", "$", "config", ")", "{", "if", "(", "$", "config", "[", "2", "]", ")", "{", "$", "states", "[", "]", "=", "$", "state", ";", "}", "}", "return", "$", "states", ";", "}" ]
Returns the notifiable states. @return array
[ "Returns", "the", "notifiable", "states", "." ]
1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1
https://github.com/ekyna/PaymentBundle/blob/1b4f4103b28e3a4f8dbfac2cbd872d728238f4d1/Model/PaymentStates.php#L54-L63
train
spress/spress-installer
src/Installer/SpressInstaller.php
SpressInstaller.getSpressSiteDir
protected function getSpressSiteDir() { $rootPackage = $this->composer->getPackage(); $extras = $rootPackage->getExtra(); return isset($extras[self::EXTRA_SPRESS_SITE_DIR]) ? $extras[self::EXTRA_SPRESS_SITE_DIR].'/' : ''; }
php
protected function getSpressSiteDir() { $rootPackage = $this->composer->getPackage(); $extras = $rootPackage->getExtra(); return isset($extras[self::EXTRA_SPRESS_SITE_DIR]) ? $extras[self::EXTRA_SPRESS_SITE_DIR].'/' : ''; }
[ "protected", "function", "getSpressSiteDir", "(", ")", "{", "$", "rootPackage", "=", "$", "this", "->", "composer", "->", "getPackage", "(", ")", ";", "$", "extras", "=", "$", "rootPackage", "->", "getExtra", "(", ")", ";", "return", "isset", "(", "$", "extras", "[", "self", "::", "EXTRA_SPRESS_SITE_DIR", "]", ")", "?", "$", "extras", "[", "self", "::", "EXTRA_SPRESS_SITE_DIR", "]", ".", "'/'", ":", "''", ";", "}" ]
Returns the Spress site directory. If the extra attributte "spress_site_dir" is not presents in the "extra" section of the root package,. @return string If the extra attributte "spress_site_dir" is not presents in the "extra" section of the root package, an empty string will be return
[ "Returns", "the", "Spress", "site", "directory", ".", "If", "the", "extra", "attributte", "spress_site_dir", "is", "not", "presents", "in", "the", "extra", "section", "of", "the", "root", "package", "." ]
ed31aa40817b133e4c19e5bf6224f343cf959275
https://github.com/spress/spress-installer/blob/ed31aa40817b133e4c19e5bf6224f343cf959275/src/Installer/SpressInstaller.php#L65-L71
train
jabernardo/lollipop-php
Library/Session/Cookie.php
Cookie.store
private function store($data) { $enc_data = Text::lock(json_encode($data)); HTTPCookie::set($this->name, $enc_data, 0, $this->path, $this->domain); }
php
private function store($data) { $enc_data = Text::lock(json_encode($data)); HTTPCookie::set($this->name, $enc_data, 0, $this->path, $this->domain); }
[ "private", "function", "store", "(", "$", "data", ")", "{", "$", "enc_data", "=", "Text", "::", "lock", "(", "json_encode", "(", "$", "data", ")", ")", ";", "HTTPCookie", "::", "set", "(", "$", "this", "->", "name", ",", "$", "enc_data", ",", "0", ",", "$", "this", "->", "path", ",", "$", "this", "->", "domain", ")", ";", "}" ]
Store session into cookie @access private @return void
[ "Store", "session", "into", "cookie" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/Session/Cookie.php#L85-L88
train
jabernardo/lollipop-php
Library/Session/Cookie.php
Cookie.restore
private function restore() { if (!HTTPCookie::exists($this->name)) return (object)[]; return json_decode(Text::unlock(HTTPCookie::get($this->name))); }
php
private function restore() { if (!HTTPCookie::exists($this->name)) return (object)[]; return json_decode(Text::unlock(HTTPCookie::get($this->name))); }
[ "private", "function", "restore", "(", ")", "{", "if", "(", "!", "HTTPCookie", "::", "exists", "(", "$", "this", "->", "name", ")", ")", "return", "(", "object", ")", "[", "]", ";", "return", "json_decode", "(", "Text", "::", "unlock", "(", "HTTPCookie", "::", "get", "(", "$", "this", "->", "name", ")", ")", ")", ";", "}" ]
Restore session from cookie @access private @return object
[ "Restore", "session", "from", "cookie" ]
004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5
https://github.com/jabernardo/lollipop-php/blob/004d80b21f7246bb3e08c7b9f74a165b0d3ca0f5/Library/Session/Cookie.php#L97-L101
train
native5/native5-sdk-client-php
src/Native5/Application.php
Application.route
public function route($request) { if (!self::$_cli) { $router = $this->get('routing'); $router->route($request); } }
php
public function route($request) { if (!self::$_cli) { $router = $this->get('routing'); $router->route($request); } }
[ "public", "function", "route", "(", "$", "request", ")", "{", "if", "(", "!", "self", "::", "$", "_cli", ")", "{", "$", "router", "=", "$", "this", "->", "get", "(", "'routing'", ")", ";", "$", "router", "->", "route", "(", "$", "request", ")", ";", "}", "}" ]
Handles routing for all incoming requests. @param mixed $request Route the application based on incoming request. @access public @return void
[ "Handles", "routing", "for", "all", "incoming", "requests", "." ]
e1f598cf27654d81bb5facace1990b737242a2f9
https://github.com/native5/native5-sdk-client-php/blob/e1f598cf27654d81bb5facace1990b737242a2f9/src/Native5/Application.php#L240-L246
train
SlaxWeb/Bootstrap
src/Application.php
Application.setRequestProperties
protected function setRequestProperties(Request $request) { $this["basePath"] = $request->getBasePath(); $this["baseUrl"] = $request->getSchemeAndHttpHost() . $this["basePath"]; }
php
protected function setRequestProperties(Request $request) { $this["basePath"] = $request->getBasePath(); $this["baseUrl"] = $request->getSchemeAndHttpHost() . $this["basePath"]; }
[ "protected", "function", "setRequestProperties", "(", "Request", "$", "request", ")", "{", "$", "this", "[", "\"basePath\"", "]", "=", "$", "request", "->", "getBasePath", "(", ")", ";", "$", "this", "[", "\"baseUrl\"", "]", "=", "$", "request", "->", "getSchemeAndHttpHost", "(", ")", ".", "$", "this", "[", "\"basePath\"", "]", ";", "}" ]
Set application properties Sets some basic request properties for the application. @param \SlaxWeb\Route\Request $request Received Request @return void
[ "Set", "application", "properties" ]
5ec8ef40f357f2c75afa0ad99090a9d2f7021557
https://github.com/SlaxWeb/Bootstrap/blob/5ec8ef40f357f2c75afa0ad99090a9d2f7021557/src/Application.php#L226-L230
train
hiqdev/minii-caching
src/MemCache.php
MemCache.addMemcacheServers
protected function addMemcacheServers($cache, $servers) { $class = new \ReflectionClass($cache); $paramCount = $class->getMethod('addServer')->getNumberOfParameters(); foreach ($servers as $server) { // $timeout is used for memcache versions that do not have $timeoutms parameter $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0); if ($paramCount === 9) { $cache->addServer( $server->host, $server->port, $server->persistent, $server->weight, $timeout, $server->retryInterval, $server->status, $server->failureCallback, $server->timeout ); } else { $cache->addServer( $server->host, $server->port, $server->persistent, $server->weight, $timeout, $server->retryInterval, $server->status, $server->failureCallback ); } } }
php
protected function addMemcacheServers($cache, $servers) { $class = new \ReflectionClass($cache); $paramCount = $class->getMethod('addServer')->getNumberOfParameters(); foreach ($servers as $server) { // $timeout is used for memcache versions that do not have $timeoutms parameter $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0); if ($paramCount === 9) { $cache->addServer( $server->host, $server->port, $server->persistent, $server->weight, $timeout, $server->retryInterval, $server->status, $server->failureCallback, $server->timeout ); } else { $cache->addServer( $server->host, $server->port, $server->persistent, $server->weight, $timeout, $server->retryInterval, $server->status, $server->failureCallback ); } } }
[ "protected", "function", "addMemcacheServers", "(", "$", "cache", ",", "$", "servers", ")", "{", "$", "class", "=", "new", "\\", "ReflectionClass", "(", "$", "cache", ")", ";", "$", "paramCount", "=", "$", "class", "->", "getMethod", "(", "'addServer'", ")", "->", "getNumberOfParameters", "(", ")", ";", "foreach", "(", "$", "servers", "as", "$", "server", ")", "{", "// $timeout is used for memcache versions that do not have $timeoutms parameter", "$", "timeout", "=", "(", "int", ")", "(", "$", "server", "->", "timeout", "/", "1000", ")", "+", "(", "(", "$", "server", "->", "timeout", "%", "1000", ">", "0", ")", "?", "1", ":", "0", ")", ";", "if", "(", "$", "paramCount", "===", "9", ")", "{", "$", "cache", "->", "addServer", "(", "$", "server", "->", "host", ",", "$", "server", "->", "port", ",", "$", "server", "->", "persistent", ",", "$", "server", "->", "weight", ",", "$", "timeout", ",", "$", "server", "->", "retryInterval", ",", "$", "server", "->", "status", ",", "$", "server", "->", "failureCallback", ",", "$", "server", "->", "timeout", ")", ";", "}", "else", "{", "$", "cache", "->", "addServer", "(", "$", "server", "->", "host", ",", "$", "server", "->", "port", ",", "$", "server", "->", "persistent", ",", "$", "server", "->", "weight", ",", "$", "timeout", ",", "$", "server", "->", "retryInterval", ",", "$", "server", "->", "status", ",", "$", "server", "->", "failureCallback", ")", ";", "}", "}", "}" ]
Add servers to the server pool of the cache specified Used for memcache PECL extension. @param \Memcache $cache @param MemCacheServer[] $servers
[ "Add", "servers", "to", "the", "server", "pool", "of", "the", "cache", "specified", "Used", "for", "memcache", "PECL", "extension", "." ]
04c3f810a4af43b53855ee9c5e3ef6455080b538
https://github.com/hiqdev/minii-caching/blob/04c3f810a4af43b53855ee9c5e3ef6455080b538/src/MemCache.php#L173-L205
train
Hnto/nuki
src/Skeletons/Providers/Repository.php
Repository.getProvider
public function getProvider($key) { if (!isset($this->providers[$key])) { return null; } return $this->providers[$key]; }
php
public function getProvider($key) { if (!isset($this->providers[$key])) { return null; } return $this->providers[$key]; }
[ "public", "function", "getProvider", "(", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "providers", "[", "$", "key", "]", ")", ")", "{", "return", "null", ";", "}", "return", "$", "this", "->", "providers", "[", "$", "key", "]", ";", "}" ]
Get provider by key @param string $key @return object
[ "Get", "provider", "by", "key" ]
c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c
https://github.com/Hnto/nuki/blob/c3fb16244e8d611c335a88e3b9c9ee7d81fafc0c/src/Skeletons/Providers/Repository.php#L96-L102
train
frameworkwtf/auth
src/Auth.php
Auth.login
public function login(string $login, string $password) { $user = $this->auth_repository->login($login, $password); if (null === $user) { return null; } if ($this->container->has('user')) { unset($this->container['user']); } $this->container['user'] = $user; return $this->auth_storage->setUser($user); }
php
public function login(string $login, string $password) { $user = $this->auth_repository->login($login, $password); if (null === $user) { return null; } if ($this->container->has('user')) { unset($this->container['user']); } $this->container['user'] = $user; return $this->auth_storage->setUser($user); }
[ "public", "function", "login", "(", "string", "$", "login", ",", "string", "$", "password", ")", "{", "$", "user", "=", "$", "this", "->", "auth_repository", "->", "login", "(", "$", "login", ",", "$", "password", ")", ";", "if", "(", "null", "===", "$", "user", ")", "{", "return", "null", ";", "}", "if", "(", "$", "this", "->", "container", "->", "has", "(", "'user'", ")", ")", "{", "unset", "(", "$", "this", "->", "container", "[", "'user'", "]", ")", ";", "}", "$", "this", "->", "container", "[", "'user'", "]", "=", "$", "user", ";", "return", "$", "this", "->", "auth_storage", "->", "setUser", "(", "$", "user", ")", ";", "}" ]
Log in user. Return result, based by selected session storage @param string $login @param string $password @return mixed
[ "Log", "in", "user", "." ]
2535d19ee326d1b491e36a341fe06d00bcc0731e
https://github.com/frameworkwtf/auth/blob/2535d19ee326d1b491e36a341fe06d00bcc0731e/src/Auth.php#L19-L33
train
frameworkwtf/auth
src/Auth.php
Auth.reset
public function reset(string $code, string $new_password): bool { return $this->auth_repository->reset($code, $new_password); }
php
public function reset(string $code, string $new_password): bool { return $this->auth_repository->reset($code, $new_password); }
[ "public", "function", "reset", "(", "string", "$", "code", ",", "string", "$", "new_password", ")", ":", "bool", "{", "return", "$", "this", "->", "auth_repository", "->", "reset", "(", "$", "code", ",", "$", "new_password", ")", ";", "}" ]
Reset user password by code. @param string $code Return value of self::forgot() @param string $new_password New password for user @return bool
[ "Reset", "user", "password", "by", "code", "." ]
2535d19ee326d1b491e36a341fe06d00bcc0731e
https://github.com/frameworkwtf/auth/blob/2535d19ee326d1b491e36a341fe06d00bcc0731e/src/Auth.php#L53-L56
train
codeblanche/Depend
src/Depend/Manager.php
Manager.module
public function module($module) { if (is_object($module)) { if (!($module instanceof ModuleInterface)) { $moduleType = get_class($module); throw new InvalidArgumentException("Given module object '$moduleType' does not implement 'Depend\\Abstraction\\ModuleInterface'"); } $module->register($this); return $this; } if (!class_exists((string) $module)) { throw new InvalidArgumentException("Given class name '$module' could not be found"); } return $this->module(new $module); }
php
public function module($module) { if (is_object($module)) { if (!($module instanceof ModuleInterface)) { $moduleType = get_class($module); throw new InvalidArgumentException("Given module object '$moduleType' does not implement 'Depend\\Abstraction\\ModuleInterface'"); } $module->register($this); return $this; } if (!class_exists((string) $module)) { throw new InvalidArgumentException("Given class name '$module' could not be found"); } return $this->module(new $module); }
[ "public", "function", "module", "(", "$", "module", ")", "{", "if", "(", "is_object", "(", "$", "module", ")", ")", "{", "if", "(", "!", "(", "$", "module", "instanceof", "ModuleInterface", ")", ")", "{", "$", "moduleType", "=", "get_class", "(", "$", "module", ")", ";", "throw", "new", "InvalidArgumentException", "(", "\"Given module object '$moduleType' does not implement 'Depend\\\\Abstraction\\\\ModuleInterface'\"", ")", ";", "}", "$", "module", "->", "register", "(", "$", "this", ")", ";", "return", "$", "this", ";", "}", "if", "(", "!", "class_exists", "(", "(", "string", ")", "$", "module", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "\"Given class name '$module' could not be found\"", ")", ";", "}", "return", "$", "this", "->", "module", "(", "new", "$", "module", ")", ";", "}" ]
Register a module object or class to register it's own dependencies. @param ModuleInterface|string $module @return $this @throws Exception\InvalidArgumentException
[ "Register", "a", "module", "object", "or", "class", "to", "register", "it", "s", "own", "dependencies", "." ]
6520d010ec71f5b2ea0d622b8abae2e029ef7f16
https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L76-L95
train
codeblanche/Depend
src/Depend/Manager.php
Manager.add
public function add(DescriptorInterface $descriptor) { $key = $this->makeKey($descriptor->getName()); $descriptor->setManager($this); $this->descriptors[$key] = $descriptor; }
php
public function add(DescriptorInterface $descriptor) { $key = $this->makeKey($descriptor->getName()); $descriptor->setManager($this); $this->descriptors[$key] = $descriptor; }
[ "public", "function", "add", "(", "DescriptorInterface", "$", "descriptor", ")", "{", "$", "key", "=", "$", "this", "->", "makeKey", "(", "$", "descriptor", "->", "getName", "(", ")", ")", ";", "$", "descriptor", "->", "setManager", "(", "$", "this", ")", ";", "$", "this", "->", "descriptors", "[", "$", "key", "]", "=", "$", "descriptor", ";", "}" ]
Add a class descriptor to the managers collection. @param Abstraction\DescriptorInterface $descriptor
[ "Add", "a", "class", "descriptor", "to", "the", "managers", "collection", "." ]
6520d010ec71f5b2ea0d622b8abae2e029ef7f16
https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L102-L109
train
codeblanche/Depend
src/Depend/Manager.php
Manager.resolveParams
public function resolveParams($params) { $resolved = array(); foreach ($params as $param) { if ($param instanceof DescriptorInterface) { $resolved[] = $this->get($param->getName()); continue; } $resolved[] = $param; } return $resolved; }
php
public function resolveParams($params) { $resolved = array(); foreach ($params as $param) { if ($param instanceof DescriptorInterface) { $resolved[] = $this->get($param->getName()); continue; } $resolved[] = $param; } return $resolved; }
[ "public", "function", "resolveParams", "(", "$", "params", ")", "{", "$", "resolved", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "if", "(", "$", "param", "instanceof", "DescriptorInterface", ")", "{", "$", "resolved", "[", "]", "=", "$", "this", "->", "get", "(", "$", "param", "->", "getName", "(", ")", ")", ";", "continue", ";", "}", "$", "resolved", "[", "]", "=", "$", "param", ";", "}", "return", "$", "resolved", ";", "}" ]
Resolve an array of mixed parameters and possible Descriptors. @param array $params @return array
[ "Resolve", "an", "array", "of", "mixed", "parameters", "and", "possible", "Descriptors", "." ]
6520d010ec71f5b2ea0d622b8abae2e029ef7f16
https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L271-L286
train
codeblanche/Depend
src/Depend/Manager.php
Manager.set
public function set($name, $instance) { $key = $this->makeKey($name); $this->alias($name, $this->describe(get_class($instance))); $this->instances[$key] = $instance; return $this; }
php
public function set($name, $instance) { $key = $this->makeKey($name); $this->alias($name, $this->describe(get_class($instance))); $this->instances[$key] = $instance; return $this; }
[ "public", "function", "set", "(", "$", "name", ",", "$", "instance", ")", "{", "$", "key", "=", "$", "this", "->", "makeKey", "(", "$", "name", ")", ";", "$", "this", "->", "alias", "(", "$", "name", ",", "$", "this", "->", "describe", "(", "get_class", "(", "$", "instance", ")", ")", ")", ";", "$", "this", "->", "instances", "[", "$", "key", "]", "=", "$", "instance", ";", "return", "$", "this", ";", "}" ]
Store an instance for injection by class name or alias. @param string $name Class name or alias @param object $instance @return Manager
[ "Store", "an", "instance", "for", "injection", "by", "class", "name", "or", "alias", "." ]
6520d010ec71f5b2ea0d622b8abae2e029ef7f16
https://github.com/codeblanche/Depend/blob/6520d010ec71f5b2ea0d622b8abae2e029ef7f16/src/Depend/Manager.php#L296-L305
train
RetItaliaSpA/AuthenticationBundle
Controller/GoogleController.php
GoogleController.connectAction
public function connectAction() { // will redirect to Facebook! $scope = $this->getParameter('scope_auth'); if(!isset($scope)){ $scope = []; } return $this->get('oauth2.registry') ->getClient('google_main') // key used in config.yml ->redirect($scope); }
php
public function connectAction() { // will redirect to Facebook! $scope = $this->getParameter('scope_auth'); if(!isset($scope)){ $scope = []; } return $this->get('oauth2.registry') ->getClient('google_main') // key used in config.yml ->redirect($scope); }
[ "public", "function", "connectAction", "(", ")", "{", "// will redirect to Facebook!", "$", "scope", "=", "$", "this", "->", "getParameter", "(", "'scope_auth'", ")", ";", "if", "(", "!", "isset", "(", "$", "scope", ")", ")", "{", "$", "scope", "=", "[", "]", ";", "}", "return", "$", "this", "->", "get", "(", "'oauth2.registry'", ")", "->", "getClient", "(", "'google_main'", ")", "// key used in config.yml", "->", "redirect", "(", "$", "scope", ")", ";", "}" ]
Link to this controller to start the "connect" process @Route("/login", name="login")
[ "Link", "to", "this", "controller", "to", "start", "the", "connect", "process" ]
4c2b28d0d290a68ade9215f872c417749deea2cd
https://github.com/RetItaliaSpA/AuthenticationBundle/blob/4c2b28d0d290a68ade9215f872c417749deea2cd/Controller/GoogleController.php#L23-L34
train
nguyenanhung/requests
src/SoapRequest.php
SoapRequest.setResponseIsJson
public function setResponseIsJson($responseIsJson = '') { $this->responseIsJson = $responseIsJson; $this->debug->info(__FUNCTION__, 'setResponseIsJson: ', $this->responseIsJson); return $this; }
php
public function setResponseIsJson($responseIsJson = '') { $this->responseIsJson = $responseIsJson; $this->debug->info(__FUNCTION__, 'setResponseIsJson: ', $this->responseIsJson); return $this; }
[ "public", "function", "setResponseIsJson", "(", "$", "responseIsJson", "=", "''", ")", "{", "$", "this", "->", "responseIsJson", "=", "$", "responseIsJson", ";", "$", "this", "->", "debug", "->", "info", "(", "__FUNCTION__", ",", "'setResponseIsJson: '", ",", "$", "this", "->", "responseIsJson", ")", ";", "return", "$", "this", ";", "}" ]
Function setResponseIsJson Return Response is Json if value = true @author: 713uk13m <[email protected]> @time : 10/8/18 19:00 @param string $responseIsJson @return $this|mixed if set value = TRUE, response is Json string @see clientRequestWsdl() method
[ "Function", "setResponseIsJson", "Return", "Response", "is", "Json", "if", "value", "=", "true" ]
fae98614a256be6a3ff9bea34a273d182a3ae730
https://github.com/nguyenanhung/requests/blob/fae98614a256be6a3ff9bea34a273d182a3ae730/src/SoapRequest.php#L186-L192
train
MichaelJ2324/PHP-REST-Client
src/Endpoint/Abstracts/AbstractModelEndpoint.php
AbstractModelEndpoint.setCurrentAction
public function setCurrentAction($action,array $actionArgs = array()){ $action = (string) $action; if (array_key_exists($action,$this->actions)){ $this->action = $action; $this->configureAction($this->action,$actionArgs); } return $this; }
php
public function setCurrentAction($action,array $actionArgs = array()){ $action = (string) $action; if (array_key_exists($action,$this->actions)){ $this->action = $action; $this->configureAction($this->action,$actionArgs); } return $this; }
[ "public", "function", "setCurrentAction", "(", "$", "action", ",", "array", "$", "actionArgs", "=", "array", "(", ")", ")", "{", "$", "action", "=", "(", "string", ")", "$", "action", ";", "if", "(", "array_key_exists", "(", "$", "action", ",", "$", "this", "->", "actions", ")", ")", "{", "$", "this", "->", "action", "=", "$", "action", ";", "$", "this", "->", "configureAction", "(", "$", "this", "->", "action", ",", "$", "actionArgs", ")", ";", "}", "return", "$", "this", ";", "}" ]
Set the current action taking place on the Model @param string $action @param array $actionArgs @return $this
[ "Set", "the", "current", "action", "taking", "place", "on", "the", "Model" ]
b8a2caaf6456eccaa845ba5c5098608aa9645c92
https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Endpoint/Abstracts/AbstractModelEndpoint.php#L232-L239
train
MichaelJ2324/PHP-REST-Client
src/Endpoint/Abstracts/AbstractModelEndpoint.php
AbstractModelEndpoint.configureAction
protected function configureAction($action,array $arguments = array()){ $this->setProperty(self::PROPERTY_HTTP_METHOD,$this->actions[$action]); }
php
protected function configureAction($action,array $arguments = array()){ $this->setProperty(self::PROPERTY_HTTP_METHOD,$this->actions[$action]); }
[ "protected", "function", "configureAction", "(", "$", "action", ",", "array", "$", "arguments", "=", "array", "(", ")", ")", "{", "$", "this", "->", "setProperty", "(", "self", "::", "PROPERTY_HTTP_METHOD", ",", "$", "this", "->", "actions", "[", "$", "action", "]", ")", ";", "}" ]
Update any properties or data based on the current action - Called when setting the Current Action @param $action @param array $arguments
[ "Update", "any", "properties", "or", "data", "based", "on", "the", "current", "action", "-", "Called", "when", "setting", "the", "Current", "Action" ]
b8a2caaf6456eccaa845ba5c5098608aa9645c92
https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Endpoint/Abstracts/AbstractModelEndpoint.php#L254-L256
train
MichaelJ2324/PHP-REST-Client
src/Endpoint/Abstracts/AbstractModelEndpoint.php
AbstractModelEndpoint.updateModel
protected function updateModel(){ $body = $this->Response->getBody(); switch ($this->action){ case self::MODEL_ACTION_CREATE: case self::MODEL_ACTION_UPDATE: case self::MODEL_ACTION_RETRIEVE: if (is_array($body)){ $this->update($body); } break; case self::MODEL_ACTION_DELETE: $this->clear(); } }
php
protected function updateModel(){ $body = $this->Response->getBody(); switch ($this->action){ case self::MODEL_ACTION_CREATE: case self::MODEL_ACTION_UPDATE: case self::MODEL_ACTION_RETRIEVE: if (is_array($body)){ $this->update($body); } break; case self::MODEL_ACTION_DELETE: $this->clear(); } }
[ "protected", "function", "updateModel", "(", ")", "{", "$", "body", "=", "$", "this", "->", "Response", "->", "getBody", "(", ")", ";", "switch", "(", "$", "this", "->", "action", ")", "{", "case", "self", "::", "MODEL_ACTION_CREATE", ":", "case", "self", "::", "MODEL_ACTION_UPDATE", ":", "case", "self", "::", "MODEL_ACTION_RETRIEVE", ":", "if", "(", "is_array", "(", "$", "body", ")", ")", "{", "$", "this", "->", "update", "(", "$", "body", ")", ";", "}", "break", ";", "case", "self", "::", "MODEL_ACTION_DELETE", ":", "$", "this", "->", "clear", "(", ")", ";", "}", "}" ]
Called after Execute if a Request Object exists, and Request returned 200 response
[ "Called", "after", "Execute", "if", "a", "Request", "Object", "exists", "and", "Request", "returned", "200", "response" ]
b8a2caaf6456eccaa845ba5c5098608aa9645c92
https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Endpoint/Abstracts/AbstractModelEndpoint.php#L294-L307
train
Dhii/iterator-abstract
src/IteratorTrait.php
IteratorTrait._rewind
protected function _rewind() { try { $this->_setIteration($this->_reset()); } catch (RootException $exception) { $this->_throwIteratorException( $this->__('An error occurred while rewinding'), null, $exception ); } }
php
protected function _rewind() { try { $this->_setIteration($this->_reset()); } catch (RootException $exception) { $this->_throwIteratorException( $this->__('An error occurred while rewinding'), null, $exception ); } }
[ "protected", "function", "_rewind", "(", ")", "{", "try", "{", "$", "this", "->", "_setIteration", "(", "$", "this", "->", "_reset", "(", ")", ")", ";", "}", "catch", "(", "RootException", "$", "exception", ")", "{", "$", "this", "->", "_throwIteratorException", "(", "$", "this", "->", "__", "(", "'An error occurred while rewinding'", ")", ",", "null", ",", "$", "exception", ")", ";", "}", "}" ]
Resets the iterator. @since [*next-version*] @see Iterator::rewind()
[ "Resets", "the", "iterator", "." ]
576484183865575ffc2a0d586132741329626fb8
https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorTrait.php#L22-L33
train
Dhii/iterator-abstract
src/IteratorTrait.php
IteratorTrait._next
protected function _next() { try { $this->_setIteration($this->_loop()); } catch (RootException $exception) { $this->_throwIteratorException( $this->__('An error occurred while iterating'), null, $exception ); } }
php
protected function _next() { try { $this->_setIteration($this->_loop()); } catch (RootException $exception) { $this->_throwIteratorException( $this->__('An error occurred while iterating'), null, $exception ); } }
[ "protected", "function", "_next", "(", ")", "{", "try", "{", "$", "this", "->", "_setIteration", "(", "$", "this", "->", "_loop", "(", ")", ")", ";", "}", "catch", "(", "RootException", "$", "exception", ")", "{", "$", "this", "->", "_throwIteratorException", "(", "$", "this", "->", "__", "(", "'An error occurred while iterating'", ")", ",", "null", ",", "$", "exception", ")", ";", "}", "}" ]
Advances the iterator to the next element. @since [*next-version*] @see Iterator::next() @throws IteratorExceptionInterface If an error occurred during iteration.
[ "Advances", "the", "iterator", "to", "the", "next", "element", "." ]
576484183865575ffc2a0d586132741329626fb8
https://github.com/Dhii/iterator-abstract/blob/576484183865575ffc2a0d586132741329626fb8/src/IteratorTrait.php#L43-L54
train
nirou8/php-multiple-saml
lib/Saml2/Settings.php
OneLogin_Saml2_Settings.checkIdPSettings
public function checkIdPSettings($settings) { assert('is_array($settings)'); if (!is_array($settings) || empty($settings)) { return array('invalid_syntax'); } $errors = array(); if (!isset($settings['idp']) || empty($settings['idp'])) { $errors[] = 'idp_not_found'; } else { $idp = $settings['idp']; if (!isset($idp['entityId']) || empty($idp['entityId'])) { $errors[] = 'idp_entityId_not_found'; } if (!isset($idp['singleSignOnService']) || !isset($idp['singleSignOnService']['url']) || empty($idp['singleSignOnService']['url']) ) { $errors[] = 'idp_sso_not_found'; } else if (!filter_var($idp['singleSignOnService']['url'], FILTER_VALIDATE_URL)) { $errors[] = 'idp_sso_url_invalid'; } if (isset($idp['singleLogoutService']) && isset($idp['singleLogoutService']['url']) && !empty($idp['singleLogoutService']['url']) && !filter_var($idp['singleLogoutService']['url'], FILTER_VALIDATE_URL) ) { $errors[] = 'idp_slo_url_invalid'; } if (isset($settings['security'])) { $security = $settings['security']; $existsX509 = isset($idp['x509cert']) && !empty($idp['x509cert']); $existsMultiX509Sign = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['signing']) && !empty($idp['x509certMulti']['signing']); $existsMultiX509Enc = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['encryption']) && !empty($idp['x509certMulti']['encryption']); $existsFingerprint = isset($idp['certFingerprint']) && !empty($idp['certFingerprint']); if (!($existsX509 || $existsFingerprint || $existsMultiX509Sign) ) { $errors[] = 'idp_cert_or_fingerprint_not_found_and_required'; } if ((isset($security['nameIdEncrypted']) && $security['nameIdEncrypted'] == true) && !($existsX509 || $existsMultiX509Enc) ) { $errors[] = 'idp_cert_not_found_and_required'; } } } return $errors; }
php
public function checkIdPSettings($settings) { assert('is_array($settings)'); if (!is_array($settings) || empty($settings)) { return array('invalid_syntax'); } $errors = array(); if (!isset($settings['idp']) || empty($settings['idp'])) { $errors[] = 'idp_not_found'; } else { $idp = $settings['idp']; if (!isset($idp['entityId']) || empty($idp['entityId'])) { $errors[] = 'idp_entityId_not_found'; } if (!isset($idp['singleSignOnService']) || !isset($idp['singleSignOnService']['url']) || empty($idp['singleSignOnService']['url']) ) { $errors[] = 'idp_sso_not_found'; } else if (!filter_var($idp['singleSignOnService']['url'], FILTER_VALIDATE_URL)) { $errors[] = 'idp_sso_url_invalid'; } if (isset($idp['singleLogoutService']) && isset($idp['singleLogoutService']['url']) && !empty($idp['singleLogoutService']['url']) && !filter_var($idp['singleLogoutService']['url'], FILTER_VALIDATE_URL) ) { $errors[] = 'idp_slo_url_invalid'; } if (isset($settings['security'])) { $security = $settings['security']; $existsX509 = isset($idp['x509cert']) && !empty($idp['x509cert']); $existsMultiX509Sign = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['signing']) && !empty($idp['x509certMulti']['signing']); $existsMultiX509Enc = isset($idp['x509certMulti']) && isset($idp['x509certMulti']['encryption']) && !empty($idp['x509certMulti']['encryption']); $existsFingerprint = isset($idp['certFingerprint']) && !empty($idp['certFingerprint']); if (!($existsX509 || $existsFingerprint || $existsMultiX509Sign) ) { $errors[] = 'idp_cert_or_fingerprint_not_found_and_required'; } if ((isset($security['nameIdEncrypted']) && $security['nameIdEncrypted'] == true) && !($existsX509 || $existsMultiX509Enc) ) { $errors[] = 'idp_cert_not_found_and_required'; } } } return $errors; }
[ "public", "function", "checkIdPSettings", "(", "$", "settings", ")", "{", "assert", "(", "'is_array($settings)'", ")", ";", "if", "(", "!", "is_array", "(", "$", "settings", ")", "||", "empty", "(", "$", "settings", ")", ")", "{", "return", "array", "(", "'invalid_syntax'", ")", ";", "}", "$", "errors", "=", "array", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "settings", "[", "'idp'", "]", ")", "||", "empty", "(", "$", "settings", "[", "'idp'", "]", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_not_found'", ";", "}", "else", "{", "$", "idp", "=", "$", "settings", "[", "'idp'", "]", ";", "if", "(", "!", "isset", "(", "$", "idp", "[", "'entityId'", "]", ")", "||", "empty", "(", "$", "idp", "[", "'entityId'", "]", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_entityId_not_found'", ";", "}", "if", "(", "!", "isset", "(", "$", "idp", "[", "'singleSignOnService'", "]", ")", "||", "!", "isset", "(", "$", "idp", "[", "'singleSignOnService'", "]", "[", "'url'", "]", ")", "||", "empty", "(", "$", "idp", "[", "'singleSignOnService'", "]", "[", "'url'", "]", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_sso_not_found'", ";", "}", "else", "if", "(", "!", "filter_var", "(", "$", "idp", "[", "'singleSignOnService'", "]", "[", "'url'", "]", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_sso_url_invalid'", ";", "}", "if", "(", "isset", "(", "$", "idp", "[", "'singleLogoutService'", "]", ")", "&&", "isset", "(", "$", "idp", "[", "'singleLogoutService'", "]", "[", "'url'", "]", ")", "&&", "!", "empty", "(", "$", "idp", "[", "'singleLogoutService'", "]", "[", "'url'", "]", ")", "&&", "!", "filter_var", "(", "$", "idp", "[", "'singleLogoutService'", "]", "[", "'url'", "]", ",", "FILTER_VALIDATE_URL", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_slo_url_invalid'", ";", "}", "if", "(", "isset", "(", "$", "settings", "[", "'security'", "]", ")", ")", "{", "$", "security", "=", "$", "settings", "[", "'security'", "]", ";", "$", "existsX509", "=", "isset", "(", "$", "idp", "[", "'x509cert'", "]", ")", "&&", "!", "empty", "(", "$", "idp", "[", "'x509cert'", "]", ")", ";", "$", "existsMultiX509Sign", "=", "isset", "(", "$", "idp", "[", "'x509certMulti'", "]", ")", "&&", "isset", "(", "$", "idp", "[", "'x509certMulti'", "]", "[", "'signing'", "]", ")", "&&", "!", "empty", "(", "$", "idp", "[", "'x509certMulti'", "]", "[", "'signing'", "]", ")", ";", "$", "existsMultiX509Enc", "=", "isset", "(", "$", "idp", "[", "'x509certMulti'", "]", ")", "&&", "isset", "(", "$", "idp", "[", "'x509certMulti'", "]", "[", "'encryption'", "]", ")", "&&", "!", "empty", "(", "$", "idp", "[", "'x509certMulti'", "]", "[", "'encryption'", "]", ")", ";", "$", "existsFingerprint", "=", "isset", "(", "$", "idp", "[", "'certFingerprint'", "]", ")", "&&", "!", "empty", "(", "$", "idp", "[", "'certFingerprint'", "]", ")", ";", "if", "(", "!", "(", "$", "existsX509", "||", "$", "existsFingerprint", "||", "$", "existsMultiX509Sign", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_cert_or_fingerprint_not_found_and_required'", ";", "}", "if", "(", "(", "isset", "(", "$", "security", "[", "'nameIdEncrypted'", "]", ")", "&&", "$", "security", "[", "'nameIdEncrypted'", "]", "==", "true", ")", "&&", "!", "(", "$", "existsX509", "||", "$", "existsMultiX509Enc", ")", ")", "{", "$", "errors", "[", "]", "=", "'idp_cert_not_found_and_required'", ";", "}", "}", "}", "return", "$", "errors", ";", "}" ]
Checks the IdP settings info. @param array $settings Array with settings data @return array $errors Errors found on the IdP settings data
[ "Checks", "the", "IdP", "settings", "info", "." ]
7eb5786e678db7d45459ce3441fa187946ae9a3b
https://github.com/nirou8/php-multiple-saml/blob/7eb5786e678db7d45459ce3441fa187946ae9a3b/lib/Saml2/Settings.php#L497-L553
train
nirou8/php-multiple-saml
lib/Saml2/Settings.php
OneLogin_Saml2_Settings.getSPMetadata
public function getSPMetadata() { $metadata = OneLogin_Saml2_Metadata::builder($this->_sp, $this->_security['authnRequestsSigned'], $this->_security['wantAssertionsSigned'], null, null, $this->getContacts(), $this->getOrganization()); $certNew = $this->getSPcertNew(); if (!empty($certNew)) { $metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors( $metadata, $certNew, $this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted'] ); } $cert = $this->getSPcert(); if (!empty($cert)) { $metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors( $metadata, $cert, $this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted'] ); } //Sign Metadata if (isset($this->_security['signMetadata']) && $this->_security['signMetadata'] !== false) { if ($this->_security['signMetadata'] === true) { $keyMetadata = $this->getSPkey(); $certMetadata = $cert; if (!$keyMetadata) { throw new OneLogin_Saml2_Error( 'SP Private key not found.', OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND ); } if (!$certMetadata) { throw new OneLogin_Saml2_Error( 'SP Public cert not found.', OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND ); } } else { if (!isset($this->_security['signMetadata']['keyFileName']) || !isset($this->_security['signMetadata']['certFileName']) ) { throw new OneLogin_Saml2_Error( 'Invalid Setting: signMetadata value of the sp is not valid', OneLogin_Saml2_Error::SETTINGS_INVALID_SYNTAX ); } $keyFileName = $this->_security['signMetadata']['keyFileName']; $certFileName = $this->_security['signMetadata']['certFileName']; $keyMetadataFile = $this->_paths['cert'].$keyFileName; $certMetadataFile = $this->_paths['cert'].$certFileName; if (!file_exists($keyMetadataFile)) { throw new OneLogin_Saml2_Error( 'SP Private key file not found: %s', OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND, array($keyMetadataFile) ); } if (!file_exists($certMetadataFile)) { throw new OneLogin_Saml2_Error( 'SP Public cert file not found: %s', OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND, array($certMetadataFile) ); } $keyMetadata = file_get_contents($keyMetadataFile); $certMetadata = file_get_contents($certMetadataFile); } $signatureAlgorithm = $this->_security['signatureAlgorithm']; $digestAlgorithm = $this->_security['digestAlgorithm']; $metadata = OneLogin_Saml2_Metadata::signMetadata($metadata, $keyMetadata, $certMetadata, $signatureAlgorithm, $digestAlgorithm); } return $metadata; }
php
public function getSPMetadata() { $metadata = OneLogin_Saml2_Metadata::builder($this->_sp, $this->_security['authnRequestsSigned'], $this->_security['wantAssertionsSigned'], null, null, $this->getContacts(), $this->getOrganization()); $certNew = $this->getSPcertNew(); if (!empty($certNew)) { $metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors( $metadata, $certNew, $this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted'] ); } $cert = $this->getSPcert(); if (!empty($cert)) { $metadata = OneLogin_Saml2_Metadata::addX509KeyDescriptors( $metadata, $cert, $this->_security['wantNameIdEncrypted'] || $this->_security['wantAssertionsEncrypted'] ); } //Sign Metadata if (isset($this->_security['signMetadata']) && $this->_security['signMetadata'] !== false) { if ($this->_security['signMetadata'] === true) { $keyMetadata = $this->getSPkey(); $certMetadata = $cert; if (!$keyMetadata) { throw new OneLogin_Saml2_Error( 'SP Private key not found.', OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND ); } if (!$certMetadata) { throw new OneLogin_Saml2_Error( 'SP Public cert not found.', OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND ); } } else { if (!isset($this->_security['signMetadata']['keyFileName']) || !isset($this->_security['signMetadata']['certFileName']) ) { throw new OneLogin_Saml2_Error( 'Invalid Setting: signMetadata value of the sp is not valid', OneLogin_Saml2_Error::SETTINGS_INVALID_SYNTAX ); } $keyFileName = $this->_security['signMetadata']['keyFileName']; $certFileName = $this->_security['signMetadata']['certFileName']; $keyMetadataFile = $this->_paths['cert'].$keyFileName; $certMetadataFile = $this->_paths['cert'].$certFileName; if (!file_exists($keyMetadataFile)) { throw new OneLogin_Saml2_Error( 'SP Private key file not found: %s', OneLogin_Saml2_Error::PRIVATE_KEY_FILE_NOT_FOUND, array($keyMetadataFile) ); } if (!file_exists($certMetadataFile)) { throw new OneLogin_Saml2_Error( 'SP Public cert file not found: %s', OneLogin_Saml2_Error::PUBLIC_CERT_FILE_NOT_FOUND, array($certMetadataFile) ); } $keyMetadata = file_get_contents($keyMetadataFile); $certMetadata = file_get_contents($certMetadataFile); } $signatureAlgorithm = $this->_security['signatureAlgorithm']; $digestAlgorithm = $this->_security['digestAlgorithm']; $metadata = OneLogin_Saml2_Metadata::signMetadata($metadata, $keyMetadata, $certMetadata, $signatureAlgorithm, $digestAlgorithm); } return $metadata; }
[ "public", "function", "getSPMetadata", "(", ")", "{", "$", "metadata", "=", "OneLogin_Saml2_Metadata", "::", "builder", "(", "$", "this", "->", "_sp", ",", "$", "this", "->", "_security", "[", "'authnRequestsSigned'", "]", ",", "$", "this", "->", "_security", "[", "'wantAssertionsSigned'", "]", ",", "null", ",", "null", ",", "$", "this", "->", "getContacts", "(", ")", ",", "$", "this", "->", "getOrganization", "(", ")", ")", ";", "$", "certNew", "=", "$", "this", "->", "getSPcertNew", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "certNew", ")", ")", "{", "$", "metadata", "=", "OneLogin_Saml2_Metadata", "::", "addX509KeyDescriptors", "(", "$", "metadata", ",", "$", "certNew", ",", "$", "this", "->", "_security", "[", "'wantNameIdEncrypted'", "]", "||", "$", "this", "->", "_security", "[", "'wantAssertionsEncrypted'", "]", ")", ";", "}", "$", "cert", "=", "$", "this", "->", "getSPcert", "(", ")", ";", "if", "(", "!", "empty", "(", "$", "cert", ")", ")", "{", "$", "metadata", "=", "OneLogin_Saml2_Metadata", "::", "addX509KeyDescriptors", "(", "$", "metadata", ",", "$", "cert", ",", "$", "this", "->", "_security", "[", "'wantNameIdEncrypted'", "]", "||", "$", "this", "->", "_security", "[", "'wantAssertionsEncrypted'", "]", ")", ";", "}", "//Sign Metadata", "if", "(", "isset", "(", "$", "this", "->", "_security", "[", "'signMetadata'", "]", ")", "&&", "$", "this", "->", "_security", "[", "'signMetadata'", "]", "!==", "false", ")", "{", "if", "(", "$", "this", "->", "_security", "[", "'signMetadata'", "]", "===", "true", ")", "{", "$", "keyMetadata", "=", "$", "this", "->", "getSPkey", "(", ")", ";", "$", "certMetadata", "=", "$", "cert", ";", "if", "(", "!", "$", "keyMetadata", ")", "{", "throw", "new", "OneLogin_Saml2_Error", "(", "'SP Private key not found.'", ",", "OneLogin_Saml2_Error", "::", "PRIVATE_KEY_FILE_NOT_FOUND", ")", ";", "}", "if", "(", "!", "$", "certMetadata", ")", "{", "throw", "new", "OneLogin_Saml2_Error", "(", "'SP Public cert not found.'", ",", "OneLogin_Saml2_Error", "::", "PUBLIC_CERT_FILE_NOT_FOUND", ")", ";", "}", "}", "else", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "_security", "[", "'signMetadata'", "]", "[", "'keyFileName'", "]", ")", "||", "!", "isset", "(", "$", "this", "->", "_security", "[", "'signMetadata'", "]", "[", "'certFileName'", "]", ")", ")", "{", "throw", "new", "OneLogin_Saml2_Error", "(", "'Invalid Setting: signMetadata value of the sp is not valid'", ",", "OneLogin_Saml2_Error", "::", "SETTINGS_INVALID_SYNTAX", ")", ";", "}", "$", "keyFileName", "=", "$", "this", "->", "_security", "[", "'signMetadata'", "]", "[", "'keyFileName'", "]", ";", "$", "certFileName", "=", "$", "this", "->", "_security", "[", "'signMetadata'", "]", "[", "'certFileName'", "]", ";", "$", "keyMetadataFile", "=", "$", "this", "->", "_paths", "[", "'cert'", "]", ".", "$", "keyFileName", ";", "$", "certMetadataFile", "=", "$", "this", "->", "_paths", "[", "'cert'", "]", ".", "$", "certFileName", ";", "if", "(", "!", "file_exists", "(", "$", "keyMetadataFile", ")", ")", "{", "throw", "new", "OneLogin_Saml2_Error", "(", "'SP Private key file not found: %s'", ",", "OneLogin_Saml2_Error", "::", "PRIVATE_KEY_FILE_NOT_FOUND", ",", "array", "(", "$", "keyMetadataFile", ")", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "certMetadataFile", ")", ")", "{", "throw", "new", "OneLogin_Saml2_Error", "(", "'SP Public cert file not found: %s'", ",", "OneLogin_Saml2_Error", "::", "PUBLIC_CERT_FILE_NOT_FOUND", ",", "array", "(", "$", "certMetadataFile", ")", ")", ";", "}", "$", "keyMetadata", "=", "file_get_contents", "(", "$", "keyMetadataFile", ")", ";", "$", "certMetadata", "=", "file_get_contents", "(", "$", "certMetadataFile", ")", ";", "}", "$", "signatureAlgorithm", "=", "$", "this", "->", "_security", "[", "'signatureAlgorithm'", "]", ";", "$", "digestAlgorithm", "=", "$", "this", "->", "_security", "[", "'digestAlgorithm'", "]", ";", "$", "metadata", "=", "OneLogin_Saml2_Metadata", "::", "signMetadata", "(", "$", "metadata", ",", "$", "keyMetadata", ",", "$", "certMetadata", ",", "$", "signatureAlgorithm", ",", "$", "digestAlgorithm", ")", ";", "}", "return", "$", "metadata", ";", "}" ]
Gets the SP metadata. The XML representation. @return string SP metadata (xml) @throws Exception @throws OneLogin_Saml2_Error
[ "Gets", "the", "SP", "metadata", ".", "The", "XML", "representation", "." ]
7eb5786e678db7d45459ce3441fa187946ae9a3b
https://github.com/nirou8/php-multiple-saml/blob/7eb5786e678db7d45459ce3441fa187946ae9a3b/lib/Saml2/Settings.php#L807-L888
train
marando/Units
src/Marando/Units/Time.php
Time.hms
public static function hms($h, $m = 0, $s = 0, $f = 0) { $sec = static::hmsf2sec($h, $m, $s, $f); return static::sec($sec); }
php
public static function hms($h, $m = 0, $s = 0, $f = 0) { $sec = static::hmsf2sec($h, $m, $s, $f); return static::sec($sec); }
[ "public", "static", "function", "hms", "(", "$", "h", ",", "$", "m", "=", "0", ",", "$", "s", "=", "0", ",", "$", "f", "=", "0", ")", "{", "$", "sec", "=", "static", "::", "hmsf2sec", "(", "$", "h", ",", "$", "m", ",", "$", "s", ",", "$", "f", ")", ";", "return", "static", "::", "sec", "(", "$", "sec", ")", ";", "}" ]
Creates a new Time instance from hour, minute and second components. @param $h Hour component @param int $m Minute component @param int|double $s Second component @param int|double $f Fractional second component @return Time
[ "Creates", "a", "new", "Time", "instance", "from", "hour", "minute", "and", "second", "components", "." ]
1721f16a2fdbd3fd8acb9061d393ce9ef1ce6e70
https://github.com/marando/Units/blob/1721f16a2fdbd3fd8acb9061d393ce9ef1ce6e70/src/Marando/Units/Time.php#L195-L200
train
Wedeto/FileFormats
src/YAML/Reader.php
Reader.readFile
public function readFile(string $file_name) { // yaml_read_file does not support stream wrappers $file_handle = @fopen($file_name, "r"); if (!is_resource($file_handle)) throw new IOException("Failed to read file: " . $file_name); return $this->readFileHandle($file_handle); }
php
public function readFile(string $file_name) { // yaml_read_file does not support stream wrappers $file_handle = @fopen($file_name, "r"); if (!is_resource($file_handle)) throw new IOException("Failed to read file: " . $file_name); return $this->readFileHandle($file_handle); }
[ "public", "function", "readFile", "(", "string", "$", "file_name", ")", "{", "// yaml_read_file does not support stream wrappers", "$", "file_handle", "=", "@", "fopen", "(", "$", "file_name", ",", "\"r\"", ")", ";", "if", "(", "!", "is_resource", "(", "$", "file_handle", ")", ")", "throw", "new", "IOException", "(", "\"Failed to read file: \"", ".", "$", "file_name", ")", ";", "return", "$", "this", "->", "readFileHandle", "(", "$", "file_handle", ")", ";", "}" ]
Read YAML from a file @param string filename The file to read from @return array The parsed data
[ "Read", "YAML", "from", "a", "file" ]
65b71fbd38a2ee6b504622aca4f4047ce9d31e9f
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/YAML/Reader.php#L46-L53
train
Wedeto/FileFormats
src/YAML/Reader.php
Reader.readFileHandle
public function readFileHandle($file_handle) { if (!is_resource($file_handle)) throw new \InvalidArgumentException("No file handle was provided"); $contents = ""; while (!feof($file_handle)) $contents .= fread($file_handle, 8192); return $this->readString($contents); }
php
public function readFileHandle($file_handle) { if (!is_resource($file_handle)) throw new \InvalidArgumentException("No file handle was provided"); $contents = ""; while (!feof($file_handle)) $contents .= fread($file_handle, 8192); return $this->readString($contents); }
[ "public", "function", "readFileHandle", "(", "$", "file_handle", ")", "{", "if", "(", "!", "is_resource", "(", "$", "file_handle", ")", ")", "throw", "new", "\\", "InvalidArgumentException", "(", "\"No file handle was provided\"", ")", ";", "$", "contents", "=", "\"\"", ";", "while", "(", "!", "feof", "(", "$", "file_handle", ")", ")", "$", "contents", ".=", "fread", "(", "$", "file_handle", ",", "8192", ")", ";", "return", "$", "this", "->", "readString", "(", "$", "contents", ")", ";", "}" ]
Read YAML from an open resource @param resource $file_handle The resource to read from @return array The parsed data
[ "Read", "YAML", "from", "an", "open", "resource" ]
65b71fbd38a2ee6b504622aca4f4047ce9d31e9f
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/YAML/Reader.php#L61-L71
train
Wedeto/FileFormats
src/YAML/Reader.php
Reader.readString
public function readString(string $data) { $interceptor = new ErrorInterceptor(function ($data) { return yaml_parse($data); }); $interceptor->registerError(E_WARNING, "yaml_parse"); $result = $interceptor->execute($data); foreach ($interceptor->getInterceptedErrors() as $error) throw new IOException("Failed to read YAML data", $error->getCode(), $error); return $result; }
php
public function readString(string $data) { $interceptor = new ErrorInterceptor(function ($data) { return yaml_parse($data); }); $interceptor->registerError(E_WARNING, "yaml_parse"); $result = $interceptor->execute($data); foreach ($interceptor->getInterceptedErrors() as $error) throw new IOException("Failed to read YAML data", $error->getCode(), $error); return $result; }
[ "public", "function", "readString", "(", "string", "$", "data", ")", "{", "$", "interceptor", "=", "new", "ErrorInterceptor", "(", "function", "(", "$", "data", ")", "{", "return", "yaml_parse", "(", "$", "data", ")", ";", "}", ")", ";", "$", "interceptor", "->", "registerError", "(", "E_WARNING", ",", "\"yaml_parse\"", ")", ";", "$", "result", "=", "$", "interceptor", "->", "execute", "(", "$", "data", ")", ";", "foreach", "(", "$", "interceptor", "->", "getInterceptedErrors", "(", ")", "as", "$", "error", ")", "throw", "new", "IOException", "(", "\"Failed to read YAML data\"", ",", "$", "error", "->", "getCode", "(", ")", ",", "$", "error", ")", ";", "return", "$", "result", ";", "}" ]
Read YAML from a string @param string $data The YAML data @return array The parsed data
[ "Read", "YAML", "from", "a", "string" ]
65b71fbd38a2ee6b504622aca4f4047ce9d31e9f
https://github.com/Wedeto/FileFormats/blob/65b71fbd38a2ee6b504622aca4f4047ce9d31e9f/src/YAML/Reader.php#L79-L93
train
CalderaWP/caldera-interop
src/ComplexEntity.php
ComplexEntity.addAttribute
public function addAttribute(Attribute $attribute): ComplexEntity { $this->attributesCollection = $this->getAttributes()->addAttribute($attribute); return $this; }
php
public function addAttribute(Attribute $attribute): ComplexEntity { $this->attributesCollection = $this->getAttributes()->addAttribute($attribute); return $this; }
[ "public", "function", "addAttribute", "(", "Attribute", "$", "attribute", ")", ":", "ComplexEntity", "{", "$", "this", "->", "attributesCollection", "=", "$", "this", "->", "getAttributes", "(", ")", "->", "addAttribute", "(", "$", "attribute", ")", ";", "return", "$", "this", ";", "}" ]
Add attribute definition @param Attribute $attribute @return ComplexEntity
[ "Add", "attribute", "definition" ]
d25c4bc930200b314fbd42d084080b5d85261c94
https://github.com/CalderaWP/caldera-interop/blob/d25c4bc930200b314fbd42d084080b5d85261c94/src/ComplexEntity.php#L26-L30
train
CalderaWP/caldera-interop
src/ComplexEntity.php
ComplexEntity.toRestResponse
public function toRestResponse(int$status = 200, array $headers = []): RestResponseContract { return (new Response())->setData($this->toArray())->setStatus($status)->setHeaders($headers); }
php
public function toRestResponse(int$status = 200, array $headers = []): RestResponseContract { return (new Response())->setData($this->toArray())->setStatus($status)->setHeaders($headers); }
[ "public", "function", "toRestResponse", "(", "int", "$", "status", "=", "200", ",", "array", "$", "headers", "=", "[", "]", ")", ":", "RestResponseContract", "{", "return", "(", "new", "Response", "(", ")", ")", "->", "setData", "(", "$", "this", "->", "toArray", "(", ")", ")", "->", "setStatus", "(", "$", "status", ")", "->", "setHeaders", "(", "$", "headers", ")", ";", "}" ]
Create REST response from entity @param int $status @param array $headers @return RestResponseContract
[ "Create", "REST", "response", "from", "entity" ]
d25c4bc930200b314fbd42d084080b5d85261c94
https://github.com/CalderaWP/caldera-interop/blob/d25c4bc930200b314fbd42d084080b5d85261c94/src/ComplexEntity.php#L53-L56
train