repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
garoevans/php-enum
src/Reflection/Enum.php
Enum.setEnum
protected function setEnum($enum) { if ($enum === null) { $enum = $this->default; } if (!\array_key_exists($enum, $this->enumsReversed)) { throw new \UnexpectedValueException("Enum '{$enum}' does not exist"); } $this->enum = $enum; return $this; }
php
protected function setEnum($enum) { if ($enum === null) { $enum = $this->default; } if (!\array_key_exists($enum, $this->enumsReversed)) { throw new \UnexpectedValueException("Enum '{$enum}' does not exist"); } $this->enum = $enum; return $this; }
[ "protected", "function", "setEnum", "(", "$", "enum", ")", "{", "if", "(", "$", "enum", "===", "null", ")", "{", "$", "enum", "=", "$", "this", "->", "default", ";", "}", "if", "(", "!", "\\", "array_key_exists", "(", "$", "enum", ",", "$", "this...
@param $enum @return Enum $this @throws \UnexpectedValueException
[ "@param", "$enum" ]
train
https://github.com/garoevans/php-enum/blob/ef76bbc711bf52f63556fb91904cea0d762343c4/src/Reflection/Enum.php#L79-L92
garoevans/php-enum
src/Reflection/Enum.php
Enum.getConstList
public function getConstList($includeDefault = false) { $constants = $this->enums; if ($includeDefault) { $constants = array_merge( array(self::$defaultKey => $this->default), $constants ); } return $constants; }
php
public function getConstList($includeDefault = false) { $constants = $this->enums; if ($includeDefault) { $constants = array_merge( array(self::$defaultKey => $this->default), $constants ); } return $constants; }
[ "public", "function", "getConstList", "(", "$", "includeDefault", "=", "false", ")", "{", "$", "constants", "=", "$", "this", "->", "enums", ";", "if", "(", "$", "includeDefault", ")", "{", "$", "constants", "=", "array_merge", "(", "array", "(", "self",...
@param bool $includeDefault @return array
[ "@param", "bool", "$includeDefault" ]
train
https://github.com/garoevans/php-enum/blob/ef76bbc711bf52f63556fb91904cea0d762343c4/src/Reflection/Enum.php#L104-L116
platformsh/console-form
src/Form.php
Form.addField
public function addField(Field $field, $key = null) { $this->fields[$key] = $field; return $this; }
php
public function addField(Field $field, $key = null) { $this->fields[$key] = $field; return $this; }
[ "public", "function", "addField", "(", "Field", "$", "field", ",", "$", "key", "=", "null", ")", "{", "$", "this", "->", "fields", "[", "$", "key", "]", "=", "$", "field", ";", "return", "$", "this", ";", "}" ]
Add a field to the form. @param Field $field @param string $key @return $this
[ "Add", "a", "field", "to", "the", "form", "." ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Form.php#L27-L32
platformsh/console-form
src/Form.php
Form.getField
public function getField($key) { if (!isset($this->fields[$key])) { return false; } return $this->fields[$key]; }
php
public function getField($key) { if (!isset($this->fields[$key])) { return false; } return $this->fields[$key]; }
[ "public", "function", "getField", "(", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "fields", "[", "$", "key", "]", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "fields", "[", "$", "key", "]...
Get a single form field. @param string $key @return Field|false
[ "Get", "a", "single", "form", "field", "." ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Form.php#L41-L48
platformsh/console-form
src/Form.php
Form.fromArray
public static function fromArray(array $fields) { $form = new static(); foreach ($fields as $key => $field) { $form->addField($field, $key); } return $form; }
php
public static function fromArray(array $fields) { $form = new static(); foreach ($fields as $key => $field) { $form->addField($field, $key); } return $form; }
[ "public", "static", "function", "fromArray", "(", "array", "$", "fields", ")", "{", "$", "form", "=", "new", "static", "(", ")", ";", "foreach", "(", "$", "fields", "as", "$", "key", "=>", "$", "field", ")", "{", "$", "form", "->", "addField", "(",...
Create a form from an array of fields. @param Field[] $fields @return static
[ "Create", "a", "form", "from", "an", "array", "of", "fields", "." ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Form.php#L57-L65
platformsh/console-form
src/Form.php
Form.configureInputDefinition
public function configureInputDefinition(InputDefinition $definition) { foreach ($this->fields as $field) { if ($field->includeAsOption()) { $definition->addOption($field->getAsOption()); } } }
php
public function configureInputDefinition(InputDefinition $definition) { foreach ($this->fields as $field) { if ($field->includeAsOption()) { $definition->addOption($field->getAsOption()); } } }
[ "public", "function", "configureInputDefinition", "(", "InputDefinition", "$", "definition", ")", "{", "foreach", "(", "$", "this", "->", "fields", "as", "$", "field", ")", "{", "if", "(", "$", "field", "->", "includeAsOption", "(", ")", ")", "{", "$", "...
Add options to a Symfony Console input definition. @param InputDefinition $definition
[ "Add", "options", "to", "a", "Symfony", "Console", "input", "definition", "." ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Form.php#L72-L79
platformsh/console-form
src/Form.php
Form.resolveOptions
public function resolveOptions(InputInterface $input, OutputInterface $output, QuestionHelper $helper) { $values = []; $stdErr = $output instanceof ConsoleOutput ? $output->getErrorOutput() : $output; foreach ($this->fields as $key => $field) { $field->onChange($values); if (!$this->includeField($field, $values)) { continue; } // Get the value from the command-line options. $value = $field->getValueFromInput($input, false); if ($value !== null) { $field->validate($value); } elseif ($input->isInteractive()) { // Get the value interactively. $value = $helper->ask($input, $stdErr, $field->getAsQuestion()); $stdErr->writeln(''); } elseif ($field->isRequired()) { throw new MissingValueException('--' . $field->getOptionName() . ' is required'); } self::setNestedArrayValue( $values, $field->getValueKeys() ?: [$key], $field->getFinalValue($value), true ); } return $values; }
php
public function resolveOptions(InputInterface $input, OutputInterface $output, QuestionHelper $helper) { $values = []; $stdErr = $output instanceof ConsoleOutput ? $output->getErrorOutput() : $output; foreach ($this->fields as $key => $field) { $field->onChange($values); if (!$this->includeField($field, $values)) { continue; } // Get the value from the command-line options. $value = $field->getValueFromInput($input, false); if ($value !== null) { $field->validate($value); } elseif ($input->isInteractive()) { // Get the value interactively. $value = $helper->ask($input, $stdErr, $field->getAsQuestion()); $stdErr->writeln(''); } elseif ($field->isRequired()) { throw new MissingValueException('--' . $field->getOptionName() . ' is required'); } self::setNestedArrayValue( $values, $field->getValueKeys() ?: [$key], $field->getFinalValue($value), true ); } return $values; }
[ "public", "function", "resolveOptions", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ",", "QuestionHelper", "$", "helper", ")", "{", "$", "values", "=", "[", "]", ";", "$", "stdErr", "=", "$", "output", "instanceof", "ConsoleOu...
Validate specified options, and ask questions for any missing values. Values can come from three sources at the moment: - command-line input - defaults - interactive questions @param InputInterface $input @param OutputInterface $output @param QuestionHelper $helper @throws InvalidValueException if any of the input was invalid. @return array An array of normalized field values. The array keys match those provided as the second argument to self::addField().
[ "Validate", "specified", "options", "and", "ask", "questions", "for", "any", "missing", "values", "." ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Form.php#L109-L141
platformsh/console-form
src/Form.php
Form.includeField
public function includeField(Field $field, array $previousValues) { foreach ($field->getConditions() as $previousField => $condition) { $previousFieldObject = $this->getField($previousField); if ($previousFieldObject === false || !isset($previousValues[$previousField]) || !$previousFieldObject->matchesCondition($previousValues[$previousField], $condition)) { return false; } } return true; }
php
public function includeField(Field $field, array $previousValues) { foreach ($field->getConditions() as $previousField => $condition) { $previousFieldObject = $this->getField($previousField); if ($previousFieldObject === false || !isset($previousValues[$previousField]) || !$previousFieldObject->matchesCondition($previousValues[$previousField], $condition)) { return false; } } return true; }
[ "public", "function", "includeField", "(", "Field", "$", "field", ",", "array", "$", "previousValues", ")", "{", "foreach", "(", "$", "field", "->", "getConditions", "(", ")", "as", "$", "previousField", "=>", "$", "condition", ")", "{", "$", "previousFiel...
Determine whether the field should be included. @param Field $field @param array $previousValues @return bool
[ "Determine", "whether", "the", "field", "should", "be", "included", "." ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Form.php#L151-L163
makinacorpus/drupal-ucms
ucms_site/src/Action/SiteActionProvider.php
SiteActionProvider.getActions
public function getActions($item, $primaryOnly = false, array $groups = []) { $ret = []; $account = $this->currentUser; $access = $this->manager->getAccess(); $canOverview = $this->isGranted(Permission::OVERVIEW, $item); $canView = $this->isGranted(Permission::VIEW, $item); $canManage = $this->isGranted(Permission::UPDATE, $item); $canManageUsers = $this->isGranted(Access::ACL_PERM_MANAGE_USERS, $item); if ($canOverview) { $ret[] = new Action($this->t("View"), 'admin/dashboard/site/' . $item->id, null, 'eye', -10); // We do not check site state, because if user cannot view site, it // should not end up being checked against here (since SQL query // alteration will forbid it). if ($canView) { $uri = $this->manager->getUrlGenerator()->generateUrl($item->id); $ret[] = new Action($this->t("Go to site"), $uri, null, 'external-link', -5, true); } if ($canManage) { $ret[] = new Action($this->t("Edit"), 'admin/dashboard/site/' . $item->id . '/edit', null, 'pencil', -2, false, true); } $ret[] = new Action($this->t("History"), 'admin/dashboard/site/' . $item->id . '/log', null, 'list-alt', -1, false); } // Append all possible state switch operations $i = 10; foreach ($access->getAllowedTransitions($account, $item) as $state => $name) { $ret[] = new Action($this->t("Switch to @state", ['@state' => $this->t($name)]), 'admin/dashboard/site/' . $item->id . '/switch/' . $state, 'dialog', 'refresh', ++$i, false, true, false, 'switch'); } // @todo Consider delete as a state if ($canManageUsers) { // 100 as priority is enough to be number of states there is ($i) $ret[] = new Action($this->t("Add existing user"), 'admin/dashboard/site/' . $item->id . '/webmaster/add-existing', 'dialog', 'user', 100, false, true, false, 'user'); $ret[] = new Action($this->t("Create new user"), 'admin/dashboard/site/' . $item->id . '/webmaster/add-new', null, 'user', 101, false, true, false, 'user'); $ret[] = new Action($this->t("Manage users"), 'admin/dashboard/site/' . $item->id . '/webmaster', null, 'user', 102, false, false, false, 'user'); } if ($this->isGranted(Permission::DELETE, $item)) { $ret[] = new Action($this->t("Delete"), 'admin/dashboard/site/' . $item->id . '/delete', 'dialog', 'trash', 1000, false, true, false, 'switch'); } return $ret; }
php
public function getActions($item, $primaryOnly = false, array $groups = []) { $ret = []; $account = $this->currentUser; $access = $this->manager->getAccess(); $canOverview = $this->isGranted(Permission::OVERVIEW, $item); $canView = $this->isGranted(Permission::VIEW, $item); $canManage = $this->isGranted(Permission::UPDATE, $item); $canManageUsers = $this->isGranted(Access::ACL_PERM_MANAGE_USERS, $item); if ($canOverview) { $ret[] = new Action($this->t("View"), 'admin/dashboard/site/' . $item->id, null, 'eye', -10); // We do not check site state, because if user cannot view site, it // should not end up being checked against here (since SQL query // alteration will forbid it). if ($canView) { $uri = $this->manager->getUrlGenerator()->generateUrl($item->id); $ret[] = new Action($this->t("Go to site"), $uri, null, 'external-link', -5, true); } if ($canManage) { $ret[] = new Action($this->t("Edit"), 'admin/dashboard/site/' . $item->id . '/edit', null, 'pencil', -2, false, true); } $ret[] = new Action($this->t("History"), 'admin/dashboard/site/' . $item->id . '/log', null, 'list-alt', -1, false); } // Append all possible state switch operations $i = 10; foreach ($access->getAllowedTransitions($account, $item) as $state => $name) { $ret[] = new Action($this->t("Switch to @state", ['@state' => $this->t($name)]), 'admin/dashboard/site/' . $item->id . '/switch/' . $state, 'dialog', 'refresh', ++$i, false, true, false, 'switch'); } // @todo Consider delete as a state if ($canManageUsers) { // 100 as priority is enough to be number of states there is ($i) $ret[] = new Action($this->t("Add existing user"), 'admin/dashboard/site/' . $item->id . '/webmaster/add-existing', 'dialog', 'user', 100, false, true, false, 'user'); $ret[] = new Action($this->t("Create new user"), 'admin/dashboard/site/' . $item->id . '/webmaster/add-new', null, 'user', 101, false, true, false, 'user'); $ret[] = new Action($this->t("Manage users"), 'admin/dashboard/site/' . $item->id . '/webmaster', null, 'user', 102, false, false, false, 'user'); } if ($this->isGranted(Permission::DELETE, $item)) { $ret[] = new Action($this->t("Delete"), 'admin/dashboard/site/' . $item->id . '/delete', 'dialog', 'trash', 1000, false, true, false, 'switch'); } return $ret; }
[ "public", "function", "getActions", "(", "$", "item", ",", "$", "primaryOnly", "=", "false", ",", "array", "$", "groups", "=", "[", "]", ")", "{", "$", "ret", "=", "[", "]", ";", "$", "account", "=", "$", "this", "->", "currentUser", ";", "$", "a...
{inheritdoc}
[ "{", "inheritdoc", "}" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Action/SiteActionProvider.php#L38-L84
makinacorpus/drupal-ucms
ucms_group/src/Controller/DashboardController.php
DashboardController.viewAction
public function viewAction(Group $group) { $table = $this->createAdminTable('ucms_group'); $table ->addHeader($this->t("Information"), 'basic') ->addRow($this->t("Title"), $group->getTitle()) ->addRow($this->t("Identifier"), $group->getId()) ; $this->addArbitraryAttributesToTable($table, $group->getAttributes()); return $table->render(); }
php
public function viewAction(Group $group) { $table = $this->createAdminTable('ucms_group'); $table ->addHeader($this->t("Information"), 'basic') ->addRow($this->t("Title"), $group->getTitle()) ->addRow($this->t("Identifier"), $group->getId()) ; $this->addArbitraryAttributesToTable($table, $group->getAttributes()); return $table->render(); }
[ "public", "function", "viewAction", "(", "Group", "$", "group", ")", "{", "$", "table", "=", "$", "this", "->", "createAdminTable", "(", "'ucms_group'", ")", ";", "$", "table", "->", "addHeader", "(", "$", "this", "->", "t", "(", "\"Information\"", ")", ...
Group details action
[ "Group", "details", "action" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Controller/DashboardController.php#L71-L84
makinacorpus/drupal-ucms
ucms_group/src/Controller/DashboardController.php
DashboardController.memberListAction
public function memberListAction(Request $request, Group $group) { return $this->renderPage('ucms_group.list_members', $request, [ 'base_query' => [ 'group' => $group->getId(), ] ]); }
php
public function memberListAction(Request $request, Group $group) { return $this->renderPage('ucms_group.list_members', $request, [ 'base_query' => [ 'group' => $group->getId(), ] ]); }
[ "public", "function", "memberListAction", "(", "Request", "$", "request", ",", "Group", "$", "group", ")", "{", "return", "$", "this", "->", "renderPage", "(", "'ucms_group.list_members'", ",", "$", "request", ",", "[", "'base_query'", "=>", "[", "'group'", ...
View members action
[ "View", "members", "action" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Controller/DashboardController.php#L89-L96
makinacorpus/drupal-ucms
ucms_group/src/Controller/DashboardController.php
DashboardController.siteAttachAction
public function siteAttachAction(Site $site) { if (!$this->isGranted(Access::PERM_GROUP_MANAGE_ALL)) { throw $this->createAccessDeniedException(); } return \Drupal::formBuilder()->getForm(SiteGroupAttach::class, $site); }
php
public function siteAttachAction(Site $site) { if (!$this->isGranted(Access::PERM_GROUP_MANAGE_ALL)) { throw $this->createAccessDeniedException(); } return \Drupal::formBuilder()->getForm(SiteGroupAttach::class, $site); }
[ "public", "function", "siteAttachAction", "(", "Site", "$", "site", ")", "{", "if", "(", "!", "$", "this", "->", "isGranted", "(", "Access", "::", "PERM_GROUP_MANAGE_ALL", ")", ")", "{", "throw", "$", "this", "->", "createAccessDeniedException", "(", ")", ...
Add site action
[ "Add", "site", "action" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Controller/DashboardController.php#L117-L124
makinacorpus/drupal-ucms
ucms_group/src/Controller/DashboardController.php
DashboardController.siteListAction
public function siteListAction(Request $request, Group $group) { return $this->renderPage('ucms_group.list_by_site', $request, [ 'base_query' => [ 'group' => $group->getId(), ] ]); }
php
public function siteListAction(Request $request, Group $group) { return $this->renderPage('ucms_group.list_by_site', $request, [ 'base_query' => [ 'group' => $group->getId(), ] ]); }
[ "public", "function", "siteListAction", "(", "Request", "$", "request", ",", "Group", "$", "group", ")", "{", "return", "$", "this", "->", "renderPage", "(", "'ucms_group.list_by_site'", ",", "$", "request", ",", "[", "'base_query'", "=>", "[", "'group'", "=...
Site list action for group
[ "Site", "list", "action", "for", "group" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Controller/DashboardController.php#L129-L136
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.ping
protected function ping() { // obfuscate data relevant for authentication $config = $this->config->toArray(); $config['customer_number'] = ShopgateLogger::OBFUSCATION_STRING; $config['shop_number'] = ShopgateLogger::OBFUSCATION_STRING; $config['apikey'] = ShopgateLogger::OBFUSCATION_STRING; $config['oauth_access_token'] = ShopgateLogger::OBFUSCATION_STRING; // prepare response data array $this->responseData['pong'] = 'OK'; $this->responseData['configuration'] = $config; $this->responseData['plugin_info'] = $this->plugin->createPluginInfo(); $this->responseData['permissions'] = $this->getPermissions(); $this->responseData['php_version'] = phpversion(); $this->responseData['php_config'] = $this->getPhpSettings(); $this->responseData['php_curl'] = function_exists('curl_version') ? curl_version() : 'No PHP-CURL installed'; $this->responseData['php_extensions'] = get_loaded_extensions(); $this->responseData['shopgate_library_version'] = SHOPGATE_LIBRARY_VERSION; $this->responseData['plugin_version'] = defined( 'SHOPGATE_PLUGIN_VERSION' ) ? SHOPGATE_PLUGIN_VERSION : 'UNKNOWN'; $this->responseData['shop_info'] = $this->plugin->createShopInfo(); // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } }
php
protected function ping() { // obfuscate data relevant for authentication $config = $this->config->toArray(); $config['customer_number'] = ShopgateLogger::OBFUSCATION_STRING; $config['shop_number'] = ShopgateLogger::OBFUSCATION_STRING; $config['apikey'] = ShopgateLogger::OBFUSCATION_STRING; $config['oauth_access_token'] = ShopgateLogger::OBFUSCATION_STRING; // prepare response data array $this->responseData['pong'] = 'OK'; $this->responseData['configuration'] = $config; $this->responseData['plugin_info'] = $this->plugin->createPluginInfo(); $this->responseData['permissions'] = $this->getPermissions(); $this->responseData['php_version'] = phpversion(); $this->responseData['php_config'] = $this->getPhpSettings(); $this->responseData['php_curl'] = function_exists('curl_version') ? curl_version() : 'No PHP-CURL installed'; $this->responseData['php_extensions'] = get_loaded_extensions(); $this->responseData['shopgate_library_version'] = SHOPGATE_LIBRARY_VERSION; $this->responseData['plugin_version'] = defined( 'SHOPGATE_PLUGIN_VERSION' ) ? SHOPGATE_PLUGIN_VERSION : 'UNKNOWN'; $this->responseData['shop_info'] = $this->plugin->createShopInfo(); // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } }
[ "protected", "function", "ping", "(", ")", "{", "// obfuscate data relevant for authentication", "$", "config", "=", "$", "this", "->", "config", "->", "toArray", "(", ")", ";", "$", "config", "[", "'customer_number'", "]", "=", "ShopgateLogger", "::", "OBFUSCAT...
Represents the "ping" action. @see http://wiki.shopgate.com/Shopgate_Plugin_API_ping
[ "Represents", "the", "ping", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L295-L327
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getDebugInfo
protected function getDebugInfo() { // prepare response data array $this->responseData = $this->plugin->getDebugInfo(); // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } }
php
protected function getDebugInfo() { // prepare response data array $this->responseData = $this->plugin->getDebugInfo(); // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } }
[ "protected", "function", "getDebugInfo", "(", ")", "{", "// prepare response data array", "$", "this", "->", "responseData", "=", "$", "this", "->", "plugin", "->", "getDebugInfo", "(", ")", ";", "// set data and return response", "if", "(", "empty", "(", "$", "...
Represents the "debug" action. @see http://wiki.shopgate.com/Shopgate_Plugin_API_ping
[ "Represents", "the", "debug", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L334-L343
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.cron
protected function cron() { if (empty($this->params['jobs']) || !is_array($this->params['jobs'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_CRON_NO_JOBS); } $unknownJobs = $this->getUnknownCronJobs($this->params['jobs']); if (!empty($unknownJobs)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_CRON_UNSUPPORTED_JOB, implode(', ', $unknownJobs), true ); } // time tracking $starttime = microtime(true); // references $message = ''; $errorcount = 0; // execute the jobs foreach ($this->params['jobs'] as $job) { if (empty($job['job_params'])) { $job['job_params'] = array(); } try { $jobErrorcount = 0; // job execution $this->plugin->cron($job['job_name'], $job['job_params'], $message, $jobErrorcount); // check error count if ($jobErrorcount > 0) { $message .= "{$jobErrorcount} errors occured while executing cron job '{$job['job_name']}'\n"; $errorcount += $jobErrorcount; } } catch (Exception $e) { $errorcount++; $message .= 'Job aborted: "' . $e->getMessage() . '"'; } } // time tracking $endtime = microtime(true); $runtime = $endtime - $starttime; $runtime = round($runtime, 4); // prepare response $responses = array(); $responses['message'] = $message; $responses['execution_error_count'] = $errorcount; $responses['execution_time'] = $runtime; if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData = $responses; }
php
protected function cron() { if (empty($this->params['jobs']) || !is_array($this->params['jobs'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_CRON_NO_JOBS); } $unknownJobs = $this->getUnknownCronJobs($this->params['jobs']); if (!empty($unknownJobs)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_CRON_UNSUPPORTED_JOB, implode(', ', $unknownJobs), true ); } // time tracking $starttime = microtime(true); // references $message = ''; $errorcount = 0; // execute the jobs foreach ($this->params['jobs'] as $job) { if (empty($job['job_params'])) { $job['job_params'] = array(); } try { $jobErrorcount = 0; // job execution $this->plugin->cron($job['job_name'], $job['job_params'], $message, $jobErrorcount); // check error count if ($jobErrorcount > 0) { $message .= "{$jobErrorcount} errors occured while executing cron job '{$job['job_name']}'\n"; $errorcount += $jobErrorcount; } } catch (Exception $e) { $errorcount++; $message .= 'Job aborted: "' . $e->getMessage() . '"'; } } // time tracking $endtime = microtime(true); $runtime = $endtime - $starttime; $runtime = round($runtime, 4); // prepare response $responses = array(); $responses['message'] = $message; $responses['execution_error_count'] = $errorcount; $responses['execution_time'] = $runtime; if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData = $responses; }
[ "protected", "function", "cron", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "params", "[", "'jobs'", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "params", "[", "'jobs'", "]", ")", ")", "{", "throw", "new", "ShopgateLibr...
Represents the "cron" action. @throws ShopgateLibraryException
[ "Represents", "the", "cron", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L350-L410
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getUnknownCronJobs
protected function getUnknownCronJobs(array $cronJobs) { $unknownCronJobs = array(); foreach ($cronJobs as $cronJob) { if (empty($cronJob['job_name'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_CRON_NO_JOB_NAME); } if (!in_array($cronJob['job_name'], $this->cronJobWhiteList, true)) { $unknownCronJobs[] = $cronJob['job_name']; } } return $unknownCronJobs; }
php
protected function getUnknownCronJobs(array $cronJobs) { $unknownCronJobs = array(); foreach ($cronJobs as $cronJob) { if (empty($cronJob['job_name'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_CRON_NO_JOB_NAME); } if (!in_array($cronJob['job_name'], $this->cronJobWhiteList, true)) { $unknownCronJobs[] = $cronJob['job_name']; } } return $unknownCronJobs; }
[ "protected", "function", "getUnknownCronJobs", "(", "array", "$", "cronJobs", ")", "{", "$", "unknownCronJobs", "=", "array", "(", ")", ";", "foreach", "(", "$", "cronJobs", "as", "$", "cronJob", ")", "{", "if", "(", "empty", "(", "$", "cronJob", "[", ...
@param array $cronJobs @return array @throws ShopgateLibraryException
[ "@param", "array", "$cronJobs" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L419-L434
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.addOrder
protected function addOrder() { if (!isset($this->params['order_number'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_ORDER_NUMBER); } /** @var ShopgateOrder[] $orders */ $orders = $this->merchantApi->getOrders( array( 'order_numbers[0]' => $this->params['order_number'], 'with_items' => 1, ) )->getData(); if (empty($orders)) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"orders" not set or empty. Response: ' . var_export($orders, true) ); } if (count($orders) > 1) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'more than one order in response. Response: ' . var_export($orders, true) ); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $orderData = $this->plugin->addOrder($orders[0]); if (is_array($orderData)) { $this->responseData = $orderData; } else { $this->responseData['external_order_id'] = $orderData; $this->responseData['external_order_number'] = null; } }
php
protected function addOrder() { if (!isset($this->params['order_number'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_ORDER_NUMBER); } /** @var ShopgateOrder[] $orders */ $orders = $this->merchantApi->getOrders( array( 'order_numbers[0]' => $this->params['order_number'], 'with_items' => 1, ) )->getData(); if (empty($orders)) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"orders" not set or empty. Response: ' . var_export($orders, true) ); } if (count($orders) > 1) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'more than one order in response. Response: ' . var_export($orders, true) ); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $orderData = $this->plugin->addOrder($orders[0]); if (is_array($orderData)) { $this->responseData = $orderData; } else { $this->responseData['external_order_id'] = $orderData; $this->responseData['external_order_number'] = null; } }
[ "protected", "function", "addOrder", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "'order_number'", "]", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "(", "ShopgateLibraryException", "::", "PLUGIN_API_NO_ORDER_NUMB...
Represents the "add_order" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_add_order
[ "Represents", "the", "add_order", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L442-L478
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.updateOrder
protected function updateOrder() { if (!isset($this->params['order_number'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_ORDER_NUMBER); } /** @var ShopgateOrder[] $orders */ $orders = $this->merchantApi->getOrders( array( 'order_numbers[0]' => $this->params['order_number'], 'with_items' => 1, ) )->getData(); if (empty($orders)) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"order" not set or empty. Response: ' . var_export($orders, true) ); } if (count($orders) > 1) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'more than one order in response. Response: ' . var_export($orders, true) ); } $payment = 0; $shipping = 0; if (isset($this->params['payment'])) { $payment = (int)$this->params['payment']; } if (isset($this->params['shipping'])) { $shipping = (int)$this->params['shipping']; } $orders[0]->setUpdatePayment($payment); $orders[0]->setUpdateShipping($shipping); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $orderData = $this->plugin->updateOrder($orders[0]); if (is_array($orderData)) { $this->responseData = $orderData; } else { $this->responseData['external_order_id'] = $orderData; $this->responseData['external_order_number'] = null; } }
php
protected function updateOrder() { if (!isset($this->params['order_number'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_ORDER_NUMBER); } /** @var ShopgateOrder[] $orders */ $orders = $this->merchantApi->getOrders( array( 'order_numbers[0]' => $this->params['order_number'], 'with_items' => 1, ) )->getData(); if (empty($orders)) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"order" not set or empty. Response: ' . var_export($orders, true) ); } if (count($orders) > 1) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'more than one order in response. Response: ' . var_export($orders, true) ); } $payment = 0; $shipping = 0; if (isset($this->params['payment'])) { $payment = (int)$this->params['payment']; } if (isset($this->params['shipping'])) { $shipping = (int)$this->params['shipping']; } $orders[0]->setUpdatePayment($payment); $orders[0]->setUpdateShipping($shipping); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $orderData = $this->plugin->updateOrder($orders[0]); if (is_array($orderData)) { $this->responseData = $orderData; } else { $this->responseData['external_order_id'] = $orderData; $this->responseData['external_order_number'] = null; } }
[ "protected", "function", "updateOrder", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "'order_number'", "]", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "(", "ShopgateLibraryException", "::", "PLUGIN_API_NO_ORDER_N...
Represents the "update_order" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_update_order
[ "Represents", "the", "update_order", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L486-L537
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.redeemCoupons
protected function redeemCoupons() { if (!isset($this->params['cart'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_CART); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $cart = new ShopgateCart($this->params['cart']); $couponData = $this->plugin->redeemCoupons($cart); if (!is_array($couponData)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, 'Plugin Response: ' . var_export($couponData, true) ); } // Workaround: // $couponData was specified to be a ShopgateExternalCoupon[]. // Now supports the same format as checkCart(), i.e. array('external_coupons' => ShopgateExternalCoupon[]). if (!empty($couponData['external_coupons']) && is_array($couponData['external_coupons'])) { $couponData = $couponData['external_coupons']; } $responseData = array("external_coupons" => array()); foreach ($couponData as $coupon) { if (!is_object($coupon) || !($coupon instanceof ShopgateExternalCoupon)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, 'Plugin Response: ' . var_export($coupon, true) ); } $coupon = $coupon->toArray(); unset($coupon["order_index"]); $responseData["external_coupons"][] = $coupon; } $this->responseData = $responseData; }
php
protected function redeemCoupons() { if (!isset($this->params['cart'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_CART); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $cart = new ShopgateCart($this->params['cart']); $couponData = $this->plugin->redeemCoupons($cart); if (!is_array($couponData)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, 'Plugin Response: ' . var_export($couponData, true) ); } // Workaround: // $couponData was specified to be a ShopgateExternalCoupon[]. // Now supports the same format as checkCart(), i.e. array('external_coupons' => ShopgateExternalCoupon[]). if (!empty($couponData['external_coupons']) && is_array($couponData['external_coupons'])) { $couponData = $couponData['external_coupons']; } $responseData = array("external_coupons" => array()); foreach ($couponData as $coupon) { if (!is_object($coupon) || !($coupon instanceof ShopgateExternalCoupon)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, 'Plugin Response: ' . var_export($coupon, true) ); } $coupon = $coupon->toArray(); unset($coupon["order_index"]); $responseData["external_coupons"][] = $coupon; } $this->responseData = $responseData; }
[ "protected", "function", "redeemCoupons", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "'cart'", "]", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "(", "ShopgateLibraryException", "::", "PLUGIN_API_NO_CART", ")",...
Represents the "redeem_coupons" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_redeem_coupons
[ "Represents", "the", "redeem_coupons", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L545-L588
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.checkCart
protected function checkCart() { if (!isset($this->params['cart'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_CART); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $cart = new ShopgateCart($this->params['cart']); $cartData = $this->plugin->checkCart($cart); $responseData = array(); $responseData['internal_cart_info'] = (isset($cartData['internal_cart_info'])) ? $cartData['internal_cart_info'] : null; if (!is_array($cartData)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartData is of type: ' . is_object($cartData) ? get_class($cartData) : gettype($cartData) ); } $responseData['currency'] = ''; if ($cart->getCurrency()) { $responseData['currency'] = $cart->getCurrency(); } if (!empty($cartData['currency'])) { $responseData['currency'] = $cartData['currency']; } if (!empty($cartData['customer']) && $cartCustomer = $cartData['customer']) { /** @var ShopgateCartCustomer $cartCustomer */ if (!is_object($cartCustomer) || !($cartCustomer instanceof ShopgateCartCustomer)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartCustomer is of type: ' . is_object($cartCustomer) ? get_class($cartCustomer) : gettype($cartCustomer) ); } foreach ($cartCustomer->getCustomerGroups() as $cartCustomerGroup) { /** @var ShopgateCartCustomerGroup $cartCustomerGroup */ if (!is_object($cartCustomerGroup) || !($cartCustomerGroup instanceof ShopgateCartCustomerGroup)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartCustomerGroup is of type: ' . is_object($cartCustomerGroup) ? get_class($cartCustomerGroup) : gettype($cartCustomerGroup) ); } } $responseData["customer"] = $cartCustomer->toArray(); } $shippingMethods = array(); if (!empty($cartData['shipping_methods'])) { foreach ($cartData["shipping_methods"] as $shippingMethod) { /** @var ShopgateShippingMethod $shippingMethod */ if (!is_object($shippingMethod) || !($shippingMethod instanceof ShopgateShippingMethod)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$shippingMethod is of type: ' . is_object($shippingMethod) ? get_class($shippingMethod) : gettype($shippingMethod) ); } $shippingMethods[] = $shippingMethod->toArray(); } } $responseData["shipping_methods"] = $shippingMethods; $paymentMethods = array(); if (!empty($cartData['payment_methods'])) { foreach ($cartData["payment_methods"] as $paymentMethod) { /** @var ShopgatePaymentMethod $paymentMethod */ if (!is_object($paymentMethod) || !($paymentMethod instanceof ShopgatePaymentMethod)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$paymentMethod is of type: ' . is_object($paymentMethod) ? get_class($paymentMethod) : gettype($paymentMethod) ); } $paymentMethods[] = $paymentMethod->toArray(); } } $responseData["payment_methods"] = $paymentMethods; $cartItems = array(); if (!empty($cartData['items'])) { foreach ($cartData["items"] as $cartItem) { /** @var ShopgateCartItem $cartItem */ if (!is_object($cartItem) || !($cartItem instanceof ShopgateCartItem)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartItem is of type: ' . is_object($cartItem) ? get_class($cartItem) : gettype($cartItem) ); } $cartItems[] = $cartItem->toArray(); } } $responseData["items"] = $cartItems; $coupons = array(); if (!empty($cartData['external_coupons'])) { foreach ($cartData["external_coupons"] as $coupon) { /** @var ShopgateExternalCoupon $coupon */ if (!is_object($coupon) || !($coupon instanceof ShopgateExternalCoupon)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$coupon is of type: ' . is_object($coupon) ? get_class($coupon) : gettype($coupon) ); } $coupon = $coupon->toArray(); unset($coupon["order_index"]); $coupons[] = $coupon; } } $responseData["external_coupons"] = $coupons; $this->responseData = $responseData; }
php
protected function checkCart() { if (!isset($this->params['cart'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_CART); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $cart = new ShopgateCart($this->params['cart']); $cartData = $this->plugin->checkCart($cart); $responseData = array(); $responseData['internal_cart_info'] = (isset($cartData['internal_cart_info'])) ? $cartData['internal_cart_info'] : null; if (!is_array($cartData)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartData is of type: ' . is_object($cartData) ? get_class($cartData) : gettype($cartData) ); } $responseData['currency'] = ''; if ($cart->getCurrency()) { $responseData['currency'] = $cart->getCurrency(); } if (!empty($cartData['currency'])) { $responseData['currency'] = $cartData['currency']; } if (!empty($cartData['customer']) && $cartCustomer = $cartData['customer']) { /** @var ShopgateCartCustomer $cartCustomer */ if (!is_object($cartCustomer) || !($cartCustomer instanceof ShopgateCartCustomer)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartCustomer is of type: ' . is_object($cartCustomer) ? get_class($cartCustomer) : gettype($cartCustomer) ); } foreach ($cartCustomer->getCustomerGroups() as $cartCustomerGroup) { /** @var ShopgateCartCustomerGroup $cartCustomerGroup */ if (!is_object($cartCustomerGroup) || !($cartCustomerGroup instanceof ShopgateCartCustomerGroup)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartCustomerGroup is of type: ' . is_object($cartCustomerGroup) ? get_class($cartCustomerGroup) : gettype($cartCustomerGroup) ); } } $responseData["customer"] = $cartCustomer->toArray(); } $shippingMethods = array(); if (!empty($cartData['shipping_methods'])) { foreach ($cartData["shipping_methods"] as $shippingMethod) { /** @var ShopgateShippingMethod $shippingMethod */ if (!is_object($shippingMethod) || !($shippingMethod instanceof ShopgateShippingMethod)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$shippingMethod is of type: ' . is_object($shippingMethod) ? get_class($shippingMethod) : gettype($shippingMethod) ); } $shippingMethods[] = $shippingMethod->toArray(); } } $responseData["shipping_methods"] = $shippingMethods; $paymentMethods = array(); if (!empty($cartData['payment_methods'])) { foreach ($cartData["payment_methods"] as $paymentMethod) { /** @var ShopgatePaymentMethod $paymentMethod */ if (!is_object($paymentMethod) || !($paymentMethod instanceof ShopgatePaymentMethod)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$paymentMethod is of type: ' . is_object($paymentMethod) ? get_class($paymentMethod) : gettype($paymentMethod) ); } $paymentMethods[] = $paymentMethod->toArray(); } } $responseData["payment_methods"] = $paymentMethods; $cartItems = array(); if (!empty($cartData['items'])) { foreach ($cartData["items"] as $cartItem) { /** @var ShopgateCartItem $cartItem */ if (!is_object($cartItem) || !($cartItem instanceof ShopgateCartItem)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartItem is of type: ' . is_object($cartItem) ? get_class($cartItem) : gettype($cartItem) ); } $cartItems[] = $cartItem->toArray(); } } $responseData["items"] = $cartItems; $coupons = array(); if (!empty($cartData['external_coupons'])) { foreach ($cartData["external_coupons"] as $coupon) { /** @var ShopgateExternalCoupon $coupon */ if (!is_object($coupon) || !($coupon instanceof ShopgateExternalCoupon)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$coupon is of type: ' . is_object($coupon) ? get_class($coupon) : gettype($coupon) ); } $coupon = $coupon->toArray(); unset($coupon["order_index"]); $coupons[] = $coupon; } } $responseData["external_coupons"] = $coupons; $this->responseData = $responseData; }
[ "protected", "function", "checkCart", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "'cart'", "]", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "(", "ShopgateLibraryException", "::", "PLUGIN_API_NO_CART", ")", "...
Represents the "check_cart" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_check_cart
[ "Represents", "the", "check_cart", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L596-L727
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.checkStock
protected function checkStock() { if (!isset($this->params['items'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_ITEMS); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $cart = new ShopgateCart(); $cart->setItems($this->params['items']); $items = $this->plugin->checkStock($cart); $responseData = array(); if (!is_array($items)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartData Is type of : ' . is_object($items) ? get_class($items) : gettype($items) ); } $cartItems = array(); if (!empty($items)) { foreach ($items as $cartItem) { /** @var ShopgateCartItem $cartItem */ if (!is_object($cartItem) || !($cartItem instanceof ShopgateCartItem)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartItem Is type of : ' . is_object($cartItem) ? get_class($cartItem) : gettype($cartItem) ); } $item = $cartItem->toArray(); $notNeededArrayKeys = array('qty_buyable', 'unit_amount', 'unit_amount_with_tax'); foreach ($notNeededArrayKeys as $key) { if (array_key_exists($key, $item)) { unset($item[$key]); } } $cartItems[] = $item; } } $responseData["items"] = $cartItems; $this->responseData = $responseData; }
php
protected function checkStock() { if (!isset($this->params['items'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_ITEMS); } if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $cart = new ShopgateCart(); $cart->setItems($this->params['items']); $items = $this->plugin->checkStock($cart); $responseData = array(); if (!is_array($items)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartData Is type of : ' . is_object($items) ? get_class($items) : gettype($items) ); } $cartItems = array(); if (!empty($items)) { foreach ($items as $cartItem) { /** @var ShopgateCartItem $cartItem */ if (!is_object($cartItem) || !($cartItem instanceof ShopgateCartItem)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$cartItem Is type of : ' . is_object($cartItem) ? get_class($cartItem) : gettype($cartItem) ); } $item = $cartItem->toArray(); $notNeededArrayKeys = array('qty_buyable', 'unit_amount', 'unit_amount_with_tax'); foreach ($notNeededArrayKeys as $key) { if (array_key_exists($key, $item)) { unset($item[$key]); } } $cartItems[] = $item; } } $responseData["items"] = $cartItems; $this->responseData = $responseData; }
[ "protected", "function", "checkStock", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "'items'", "]", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "(", "ShopgateLibraryException", "::", "PLUGIN_API_NO_ITEMS", ")", ...
Represents the "check_stock" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_check_stock
[ "Represents", "the", "check_stock", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L735-L786
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getSettings
protected function getSettings() { $this->responseData = $this->plugin->getSettings(); // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } }
php
protected function getSettings() { $this->responseData = $this->plugin->getSettings(); // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } }
[ "protected", "function", "getSettings", "(", ")", "{", "$", "this", "->", "responseData", "=", "$", "this", "->", "plugin", "->", "getSettings", "(", ")", ";", "// set data and return response", "if", "(", "empty", "(", "$", "this", "->", "response", ")", ...
Represents the "get_settings" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_settings
[ "Represents", "the", "get_settings", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L794-L802
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.setSettings
protected function setSettings() { if (empty($this->params['shopgate_settings']) || !is_array($this->params['shopgate_settings'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_NO_SHOPGATE_SETTINGS, 'Request: ' . var_export($this->params, true) ); } // settings that may never be changed: $shopgateSettingsBlacklist = array( 'shop_number', 'customer_number', 'apikey', 'plugin_name', 'export_folder_path', 'log_folder_path', 'cache_folder_path', 'items_csv_filename', 'categories_csv_filename', 'reviews_csv_filename', 'access_log_filename', 'error_log_filename', 'request_log_filename', 'debug_log_filename', 'redirect_keyword_cache_filename', 'redirect_skip_keyword_cache_filename', ); // filter the new settings $shopgateSettingsNew = array(); $shopgateSettingsOld = $this->config->toArray(); foreach ($this->params['shopgate_settings'] as $setting) { if (!isset($setting['name'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_NO_SHOPGATE_SETTINGS, 'Wrong format: ' . var_export($setting, true) ); } if (in_array($setting['name'], $shopgateSettingsBlacklist)) { continue; } if (!in_array($setting['name'], array_keys($shopgateSettingsOld))) { continue; } $shopgateSettingsNew[$setting['name']] = isset($setting['value']) ? $setting['value'] : null; } $this->config->load($shopgateSettingsNew); $this->config->save(array_keys($shopgateSettingsNew), true); $diff = array(); foreach ($shopgateSettingsNew as $setting => $value) { $diff[] = array('name' => $setting, 'old' => $shopgateSettingsOld[$setting], 'new' => $value); } // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData['shopgate_settings'] = $diff; }
php
protected function setSettings() { if (empty($this->params['shopgate_settings']) || !is_array($this->params['shopgate_settings'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_NO_SHOPGATE_SETTINGS, 'Request: ' . var_export($this->params, true) ); } // settings that may never be changed: $shopgateSettingsBlacklist = array( 'shop_number', 'customer_number', 'apikey', 'plugin_name', 'export_folder_path', 'log_folder_path', 'cache_folder_path', 'items_csv_filename', 'categories_csv_filename', 'reviews_csv_filename', 'access_log_filename', 'error_log_filename', 'request_log_filename', 'debug_log_filename', 'redirect_keyword_cache_filename', 'redirect_skip_keyword_cache_filename', ); // filter the new settings $shopgateSettingsNew = array(); $shopgateSettingsOld = $this->config->toArray(); foreach ($this->params['shopgate_settings'] as $setting) { if (!isset($setting['name'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_NO_SHOPGATE_SETTINGS, 'Wrong format: ' . var_export($setting, true) ); } if (in_array($setting['name'], $shopgateSettingsBlacklist)) { continue; } if (!in_array($setting['name'], array_keys($shopgateSettingsOld))) { continue; } $shopgateSettingsNew[$setting['name']] = isset($setting['value']) ? $setting['value'] : null; } $this->config->load($shopgateSettingsNew); $this->config->save(array_keys($shopgateSettingsNew), true); $diff = array(); foreach ($shopgateSettingsNew as $setting => $value) { $diff[] = array('name' => $setting, 'old' => $shopgateSettingsOld[$setting], 'new' => $value); } // set data and return response if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData['shopgate_settings'] = $diff; }
[ "protected", "function", "setSettings", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "params", "[", "'shopgate_settings'", "]", ")", "||", "!", "is_array", "(", "$", "this", "->", "params", "[", "'shopgate_settings'", "]", ")", ")", "{", ...
Represents the "set_settings" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_set_settings
[ "Represents", "the", "set_settings", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L810-L875
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getCustomer
protected function getCustomer() { if (!isset($this->params['user'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_USER); } if (!isset($this->params['pass'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_PASS); } $customer = $this->plugin->getCustomer($this->params['user'], $this->params['pass']); if (!is_object($customer) || !($customer instanceof ShopgateCustomer)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, 'Plugin Response: ' . var_export($customer, true) ); } foreach ($customer->getCustomerGroups() as $customerGroup) { /** @var ShopgateCustomerGroup $customerGroup */ if (!is_object($customerGroup) || !($customerGroup instanceof ShopgateCustomerGroup)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$customerGroup is of type: ' . is_object($customerGroup) ? get_class($customerGroup) : gettype($customerGroup) ); } } $customerData = $customer->toArray(); $addressList = $customerData['addresses']; unset($customerData['addresses']); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData["user_data"] = $customerData; $this->responseData["addresses"] = $addressList; }
php
protected function getCustomer() { if (!isset($this->params['user'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_USER); } if (!isset($this->params['pass'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_PASS); } $customer = $this->plugin->getCustomer($this->params['user'], $this->params['pass']); if (!is_object($customer) || !($customer instanceof ShopgateCustomer)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, 'Plugin Response: ' . var_export($customer, true) ); } foreach ($customer->getCustomerGroups() as $customerGroup) { /** @var ShopgateCustomerGroup $customerGroup */ if (!is_object($customerGroup) || !($customerGroup instanceof ShopgateCustomerGroup)) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_WRONG_RESPONSE_FORMAT, '$customerGroup is of type: ' . is_object($customerGroup) ? get_class($customerGroup) : gettype($customerGroup) ); } } $customerData = $customer->toArray(); $addressList = $customerData['addresses']; unset($customerData['addresses']); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData["user_data"] = $customerData; $this->responseData["addresses"] = $addressList; }
[ "protected", "function", "getCustomer", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "'user'", "]", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "(", "ShopgateLibraryException", "::", "PLUGIN_API_NO_USER", ")", ...
Represents the "get_customer" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_customer
[ "Represents", "the", "get_customer", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L990-L1029
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getMediaCsv
protected function getMediaCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update items csv file if requested $this->plugin->startGetMediaCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getMediaCsvPath(); }
php
protected function getMediaCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update items csv file if requested $this->plugin->startGetMediaCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getMediaCsvPath(); }
[ "protected", "function", "getMediaCsv", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "&&", "isset", "(", "$", "this", "->", "params", "[", "'offset'", "]", ")", ")", "{", "$", "this", "->", "plugin"...
Represents the "get_media_csv" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_media_csv
[ "Represents", "the", "get_media_csv", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1099-L1114
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getItemsCsv
protected function getItemsCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update items csv file if requested $this->plugin->startGetItemsCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getItemsCsvPath(); }
php
protected function getItemsCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update items csv file if requested $this->plugin->startGetItemsCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getItemsCsvPath(); }
[ "protected", "function", "getItemsCsv", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "&&", "isset", "(", "$", "this", "->", "params", "[", "'offset'", "]", ")", ")", "{", "$", "this", "->", "plugin"...
Represents the "get_items_csv" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_items_csv
[ "Represents", "the", "get_items_csv", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1122-L1137
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getItems
protected function getItems() { $limit = isset($this->params['limit']) ? (int)$this->params['limit'] : null; $offset = isset($this->params['offset']) ? (int)$this->params['offset'] : null; $uids = isset($this->params['uids']) ? (array)$this->params['uids'] : array(); $responseType = isset($this->params['response_type']) ? $this->params['response_type'] : false; $supportedResponseTypes = $this->config->getSupportedResponseTypes(); if (!empty($responseType) && !in_array($responseType, $supportedResponseTypes['get_items'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_UNSUPPORTED_RESPONSE_TYPE, 'Requested type: "' . $responseType . '"' ); } $this->plugin->startGetItems($limit, $offset, $uids, $responseType); switch ($responseType) { default: case 'xml': $response = new ShopgatePluginApiResponseAppXmlExport($this->trace_id); $responseData = $this->config->getItemsXmlPath(); break; case 'json': $response = new ShopgatePluginApiResponseAppJsonExport($this->trace_id); $responseData = $this->config->getItemsJsonPath(); break; } if (empty($this->response)) { $this->response = $response; } $this->responseData = $responseData; }
php
protected function getItems() { $limit = isset($this->params['limit']) ? (int)$this->params['limit'] : null; $offset = isset($this->params['offset']) ? (int)$this->params['offset'] : null; $uids = isset($this->params['uids']) ? (array)$this->params['uids'] : array(); $responseType = isset($this->params['response_type']) ? $this->params['response_type'] : false; $supportedResponseTypes = $this->config->getSupportedResponseTypes(); if (!empty($responseType) && !in_array($responseType, $supportedResponseTypes['get_items'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_UNSUPPORTED_RESPONSE_TYPE, 'Requested type: "' . $responseType . '"' ); } $this->plugin->startGetItems($limit, $offset, $uids, $responseType); switch ($responseType) { default: case 'xml': $response = new ShopgatePluginApiResponseAppXmlExport($this->trace_id); $responseData = $this->config->getItemsXmlPath(); break; case 'json': $response = new ShopgatePluginApiResponseAppJsonExport($this->trace_id); $responseData = $this->config->getItemsJsonPath(); break; } if (empty($this->response)) { $this->response = $response; } $this->responseData = $responseData; }
[ "protected", "function", "getItems", "(", ")", "{", "$", "limit", "=", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "?", "(", "int", ")", "$", "this", "->", "params", "[", "'limit'", "]", ":", "null", ";", "$", "offset", "...
Represents the "get_items" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_items
[ "Represents", "the", "get_items", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1145-L1188
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getCategories
protected function getCategories() { $limit = isset($this->params['limit']) ? (int)$this->params['limit'] : null; $offset = isset($this->params['offset']) ? (int)$this->params['offset'] : null; $uids = isset($this->params['uids']) ? (array)$this->params['uids'] : array(); $responseType = isset($this->params['response_type']) ? $this->params['response_type'] : false; $supportedResponseTypes = $this->config->getSupportedResponseTypes(); if (!empty($responseType) && !in_array($responseType, $supportedResponseTypes['get_categories'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_UNSUPPORTED_RESPONSE_TYPE, 'Requested type: "' . $responseType . '"' ); } $this->plugin->startGetCategories($limit, $offset, $uids, $responseType); switch ($responseType) { default: case 'xml': $response = new ShopgatePluginApiResponseAppXmlExport($this->trace_id); $responseData = $this->config->getCategoriesXmlPath(); break; case 'json': $response = new ShopgatePluginApiResponseAppJsonExport($this->trace_id); $responseData = $this->config->getCategoriesJsonPath(); break; } if (empty($this->response)) { $this->response = $response; } $this->responseData = $responseData; }
php
protected function getCategories() { $limit = isset($this->params['limit']) ? (int)$this->params['limit'] : null; $offset = isset($this->params['offset']) ? (int)$this->params['offset'] : null; $uids = isset($this->params['uids']) ? (array)$this->params['uids'] : array(); $responseType = isset($this->params['response_type']) ? $this->params['response_type'] : false; $supportedResponseTypes = $this->config->getSupportedResponseTypes(); if (!empty($responseType) && !in_array($responseType, $supportedResponseTypes['get_categories'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_UNSUPPORTED_RESPONSE_TYPE, 'Requested type: "' . $responseType . '"' ); } $this->plugin->startGetCategories($limit, $offset, $uids, $responseType); switch ($responseType) { default: case 'xml': $response = new ShopgatePluginApiResponseAppXmlExport($this->trace_id); $responseData = $this->config->getCategoriesXmlPath(); break; case 'json': $response = new ShopgatePluginApiResponseAppJsonExport($this->trace_id); $responseData = $this->config->getCategoriesJsonPath(); break; } if (empty($this->response)) { $this->response = $response; } $this->responseData = $responseData; }
[ "protected", "function", "getCategories", "(", ")", "{", "$", "limit", "=", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "?", "(", "int", ")", "$", "this", "->", "params", "[", "'limit'", "]", ":", "null", ";", "$", "offset"...
Represents the "get_categories" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_categories
[ "Represents", "the", "get_categories", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1196-L1239
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getCategoriesCsv
protected function getCategoriesCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update categories csv file $this->plugin->startGetCategoriesCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getCategoriesCsvPath(); }
php
protected function getCategoriesCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update categories csv file $this->plugin->startGetCategoriesCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getCategoriesCsvPath(); }
[ "protected", "function", "getCategoriesCsv", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "&&", "isset", "(", "$", "this", "->", "params", "[", "'offset'", "]", ")", ")", "{", "$", "this", "->", "pl...
Represents the "get_categories_csv" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_categories_csv
[ "Represents", "the", "get_categories_csv", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1247-L1262
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getReviewsCsv
protected function getReviewsCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update reviews csv file $this->plugin->startGetReviewsCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getReviewsCsvPath(); }
php
protected function getReviewsCsv() { if (isset($this->params['limit']) && isset($this->params['offset'])) { $this->plugin->setExportLimit((int)$this->params['limit']); $this->plugin->setExportOffset((int)$this->params['offset']); $this->plugin->setSplittedExport(true); } // generate / update reviews csv file $this->plugin->startGetReviewsCsv(); if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextCsvExport($this->trace_id); } $this->responseData = $this->config->getReviewsCsvPath(); }
[ "protected", "function", "getReviewsCsv", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "&&", "isset", "(", "$", "this", "->", "params", "[", "'offset'", "]", ")", ")", "{", "$", "this", "->", "plugi...
Represents the "get_reviews_csv" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_reviews_csv
[ "Represents", "the", "get_reviews_csv", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1270-L1285
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getReviews
protected function getReviews() { $limit = isset($this->params['limit']) ? (int)$this->params['limit'] : null; $offset = isset($this->params['offset']) ? (int)$this->params['offset'] : null; $uids = isset($this->params['uids']) ? (array)$this->params['uids'] : array(); $responseType = isset($this->params['response_type']) ? $this->params['response_type'] : false; $supportedResponseTypes = $this->config->getSupportedResponseTypes(); if (!empty($responseType) && !in_array($responseType, $supportedResponseTypes['get_reviews'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_UNSUPPORTED_RESPONSE_TYPE, 'Requested type: "' . $responseType . '"' ); } $this->plugin->startGetReviews($limit, $offset, $uids, $responseType); switch ($responseType) { default: case 'xml': $response = new ShopgatePluginApiResponseAppXmlExport($this->trace_id); $responseData = $this->config->getReviewsXmlPath(); break; case 'json': $response = new ShopgatePluginApiResponseAppJsonExport($this->trace_id); $responseData = $this->config->getReviewsJsonPath(); break; } if (empty($this->response)) { $this->response = $response; } $this->responseData = $responseData; }
php
protected function getReviews() { $limit = isset($this->params['limit']) ? (int)$this->params['limit'] : null; $offset = isset($this->params['offset']) ? (int)$this->params['offset'] : null; $uids = isset($this->params['uids']) ? (array)$this->params['uids'] : array(); $responseType = isset($this->params['response_type']) ? $this->params['response_type'] : false; $supportedResponseTypes = $this->config->getSupportedResponseTypes(); if (!empty($responseType) && !in_array($responseType, $supportedResponseTypes['get_reviews'])) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_UNSUPPORTED_RESPONSE_TYPE, 'Requested type: "' . $responseType . '"' ); } $this->plugin->startGetReviews($limit, $offset, $uids, $responseType); switch ($responseType) { default: case 'xml': $response = new ShopgatePluginApiResponseAppXmlExport($this->trace_id); $responseData = $this->config->getReviewsXmlPath(); break; case 'json': $response = new ShopgatePluginApiResponseAppJsonExport($this->trace_id); $responseData = $this->config->getReviewsJsonPath(); break; } if (empty($this->response)) { $this->response = $response; } $this->responseData = $responseData; }
[ "protected", "function", "getReviews", "(", ")", "{", "$", "limit", "=", "isset", "(", "$", "this", "->", "params", "[", "'limit'", "]", ")", "?", "(", "int", ")", "$", "this", "->", "params", "[", "'limit'", "]", ":", "null", ";", "$", "offset", ...
Represents the "get_categories" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_categories
[ "Represents", "the", "get_categories", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1293-L1336
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.getLogFile
protected function getLogFile() { // disable debug log for this action $logger = ShopgateLogger::getInstance(); $logger->disableDebug(); $logger->keepDebugLog(true); $type = (empty($this->params['log_type'])) ? ShopgateLogger::LOGTYPE_ERROR : $this->params['log_type']; $lines = (!isset($this->params['lines'])) ? null : $this->params['lines']; $log = $logger->tail($type, $lines); // return the requested log file content and end the script if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextPlain($this->trace_id); } $this->responseData = $log; }
php
protected function getLogFile() { // disable debug log for this action $logger = ShopgateLogger::getInstance(); $logger->disableDebug(); $logger->keepDebugLog(true); $type = (empty($this->params['log_type'])) ? ShopgateLogger::LOGTYPE_ERROR : $this->params['log_type']; $lines = (!isset($this->params['lines'])) ? null : $this->params['lines']; $log = $logger->tail($type, $lines); // return the requested log file content and end the script if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseTextPlain($this->trace_id); } $this->responseData = $log; }
[ "protected", "function", "getLogFile", "(", ")", "{", "// disable debug log for this action", "$", "logger", "=", "ShopgateLogger", "::", "getInstance", "(", ")", ";", "$", "logger", "->", "disableDebug", "(", ")", ";", "$", "logger", "->", "keepDebugLog", "(", ...
Represents the "get_log_file" action. @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_get_log_file
[ "Represents", "the", "get_log_file", "action", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1344-L1365
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.receiveAuthorization
protected function receiveAuthorization() { if ($this->config->getSmaAuthServiceClassName( ) != ShopgateConfigInterface::SHOPGATE_AUTH_SERVICE_CLASS_NAME_OAUTH) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_INVALID_ACTION, '=> "receive_authorization" action can only be called for plugins with SMA-AuthService set to "OAuth" type', true ); } if (empty($this->params['code'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_AUTHORIZATION_CODE); } $tokenRequestUrl = $this->buildShopgateOAuthUrl('token'); // the "receive_authorization" action url is needed (again) for requesting an access token $calledScriptUrl = $this->plugin->getActionUrl($this->params['action']); // Re-initialize the OAuth auth service object and the ShopgateMerchantAPI object $smaAuthService = new ShopgateAuthenticationServiceOAuth(); $smaAuthService->requestOAuthAccessToken($this->params['code'], $calledScriptUrl, $tokenRequestUrl); // at this Point there is a valid access token available, since this point would not be reached otherwise // -> get a new ShopgateMerchantApi object, containing a fully configured OAuth auth service including the access token $this->merchantApi = new ShopgateMerchantApi($smaAuthService, null, $this->config->getApiUrl()); // load all shop info via the MerchantAPI and store it in the config (via OAuth and a valid access token) $shopInfo = $this->merchantApi->getShopInfo()->getData(); if (empty($shopInfo)) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '-> "shop info" not set. Response data: ' . var_export($shopInfo, true) ); } // create a new settings array $shopgateSettingsNew = array( $field = 'oauth_access_token' => $shopInfo[$field], $field = 'customer_number' => $shopInfo[$field], $field = 'shop_number' => $shopInfo[$field], $field = 'apikey' => $shopInfo[$field], $field = 'alias' => $shopInfo[$field], $field = 'cname' => $shopInfo[$field], ); // save all shop config data to plugin-config using the configs save method $this->config->load($shopgateSettingsNew); $this->config->save(array_keys($shopgateSettingsNew), true); // no specific data needs to be returned if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData = array(); }
php
protected function receiveAuthorization() { if ($this->config->getSmaAuthServiceClassName( ) != ShopgateConfigInterface::SHOPGATE_AUTH_SERVICE_CLASS_NAME_OAUTH) { throw new ShopgateLibraryException( ShopgateLibraryException::PLUGIN_API_INVALID_ACTION, '=> "receive_authorization" action can only be called for plugins with SMA-AuthService set to "OAuth" type', true ); } if (empty($this->params['code'])) { throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_API_NO_AUTHORIZATION_CODE); } $tokenRequestUrl = $this->buildShopgateOAuthUrl('token'); // the "receive_authorization" action url is needed (again) for requesting an access token $calledScriptUrl = $this->plugin->getActionUrl($this->params['action']); // Re-initialize the OAuth auth service object and the ShopgateMerchantAPI object $smaAuthService = new ShopgateAuthenticationServiceOAuth(); $smaAuthService->requestOAuthAccessToken($this->params['code'], $calledScriptUrl, $tokenRequestUrl); // at this Point there is a valid access token available, since this point would not be reached otherwise // -> get a new ShopgateMerchantApi object, containing a fully configured OAuth auth service including the access token $this->merchantApi = new ShopgateMerchantApi($smaAuthService, null, $this->config->getApiUrl()); // load all shop info via the MerchantAPI and store it in the config (via OAuth and a valid access token) $shopInfo = $this->merchantApi->getShopInfo()->getData(); if (empty($shopInfo)) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '-> "shop info" not set. Response data: ' . var_export($shopInfo, true) ); } // create a new settings array $shopgateSettingsNew = array( $field = 'oauth_access_token' => $shopInfo[$field], $field = 'customer_number' => $shopInfo[$field], $field = 'shop_number' => $shopInfo[$field], $field = 'apikey' => $shopInfo[$field], $field = 'alias' => $shopInfo[$field], $field = 'cname' => $shopInfo[$field], ); // save all shop config data to plugin-config using the configs save method $this->config->load($shopgateSettingsNew); $this->config->save(array_keys($shopgateSettingsNew), true); // no specific data needs to be returned if (empty($this->response)) { $this->response = new ShopgatePluginApiResponseAppJson($this->trace_id); } $this->responseData = array(); }
[ "protected", "function", "receiveAuthorization", "(", ")", "{", "if", "(", "$", "this", "->", "config", "->", "getSmaAuthServiceClassName", "(", ")", "!=", "ShopgateConfigInterface", "::", "SHOPGATE_AUTH_SERVICE_CLASS_NAME_OAUTH", ")", "{", "throw", "new", "ShopgateLi...
Represents the "receive_authorization" action (OAUTH ONLY!). Please make sure to allow calls to this action only for admin users with proper rights (only call inside of the admin area or check for admin-login set when providing an action from outside of the admin area) @see ShopgatePlugin::checkAdminLogin method @throws ShopgateLibraryException @see http://wiki.shopgate.com/Shopgate_Plugin_API_receive_authorization
[ "Represents", "the", "receive_authorization", "action", "(", "OAUTH", "ONLY!", ")", ".", "Please", "make", "sure", "to", "allow", "calls", "to", "this", "action", "only", "for", "admin", "users", "with", "proper", "rights", "(", "only", "call", "inside", "of...
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1464-L1519
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi.buildShopgateOAuthUrl
public function buildShopgateOAuthUrl($shopgateOAuthActionName) { // based on the oauth action name the subdomain can differ switch ($shopgateOAuthActionName) { case 'authorize': $subdomain = 'admin'; break; case 'token': $subdomain = 'api'; break; default: $subdomain = 'www'; break; } // the access token needs to be requested first (compute a request target url for this) $merchantApiUrl = $this->config->getApiUrl(); if ($this->config->getServer() == 'custom') { // defaults to https://<subdomain>.<hostname>/api[controller]/<merchant-action-name> for custom server $requestServerHost = explode('/api/', $merchantApiUrl); $requestServerHost[0] = str_replace('://api.', "://{$subdomain}.", $requestServerHost[0]); $requestServerHost = trim($requestServerHost[0], '/'); } else { // defaults to https://<subdomain>.<hostname>/<merchant-action-name> for live, pg and sl server $matches = array(); preg_match( '/^(?P<protocol>http(s)?:\/\/)api.(?P<hostname>[^\/]+)\/merchant.*$/', $merchantApiUrl, $matches ); $protocol = (!empty($matches['protocol']) ? $matches['protocol'] : 'https://'); $hostname = (!empty($matches['hostname']) ? $matches['hostname'] : 'shopgate.com'); $requestServerHost = "{$protocol}{$subdomain}.{$hostname}"; } return $requestServerHost . '/oauth/' . $shopgateOAuthActionName; }
php
public function buildShopgateOAuthUrl($shopgateOAuthActionName) { // based on the oauth action name the subdomain can differ switch ($shopgateOAuthActionName) { case 'authorize': $subdomain = 'admin'; break; case 'token': $subdomain = 'api'; break; default: $subdomain = 'www'; break; } // the access token needs to be requested first (compute a request target url for this) $merchantApiUrl = $this->config->getApiUrl(); if ($this->config->getServer() == 'custom') { // defaults to https://<subdomain>.<hostname>/api[controller]/<merchant-action-name> for custom server $requestServerHost = explode('/api/', $merchantApiUrl); $requestServerHost[0] = str_replace('://api.', "://{$subdomain}.", $requestServerHost[0]); $requestServerHost = trim($requestServerHost[0], '/'); } else { // defaults to https://<subdomain>.<hostname>/<merchant-action-name> for live, pg and sl server $matches = array(); preg_match( '/^(?P<protocol>http(s)?:\/\/)api.(?P<hostname>[^\/]+)\/merchant.*$/', $merchantApiUrl, $matches ); $protocol = (!empty($matches['protocol']) ? $matches['protocol'] : 'https://'); $hostname = (!empty($matches['hostname']) ? $matches['hostname'] : 'shopgate.com'); $requestServerHost = "{$protocol}{$subdomain}.{$hostname}"; } return $requestServerHost . '/oauth/' . $shopgateOAuthActionName; }
[ "public", "function", "buildShopgateOAuthUrl", "(", "$", "shopgateOAuthActionName", ")", "{", "// based on the oauth action name the subdomain can differ", "switch", "(", "$", "shopgateOAuthActionName", ")", "{", "case", "'authorize'", ":", "$", "subdomain", "=", "'admin'",...
###############
[ "###############" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1525-L1565
shopgate/cart-integration-sdk
src/apis.php
ShopgatePluginApi._getFileMeta
private function _getFileMeta($file, $parentLevel = 0) { $meta = array('file' => $file); if ($meta['exist'] = (bool)file_exists($file)) { $meta['writeable'] = (bool)is_writable($file); $uid = fileowner($file); if (function_exists('posix_getpwuid')) { $uinfo = posix_getpwuid($uid); $uid = $uinfo['name']; } $gid = filegroup($file); if (function_exists('posix_getgrgid')) { $ginfo = posix_getgrgid($gid); $gid = $ginfo['name']; } $meta['owner'] = $uid; $meta['group'] = $gid; $meta['permission'] = substr(sprintf('%o', fileperms($file)), -4); $meta['last_modification_time'] = date('d.m.Y H:i:s', filemtime($file)); if (is_file($file)) { $meta['filesize'] = round(filesize($file) / (1024 * 1024), 4) . ' MB'; } } elseif ($parentLevel > 0) { $fInfo = pathinfo($file); if (file_exists($fInfo['dirname'])) { $meta['parent_dir'] = $this->_getFileMeta($fInfo['dirname'], --$parentLevel); } } return $meta; }
php
private function _getFileMeta($file, $parentLevel = 0) { $meta = array('file' => $file); if ($meta['exist'] = (bool)file_exists($file)) { $meta['writeable'] = (bool)is_writable($file); $uid = fileowner($file); if (function_exists('posix_getpwuid')) { $uinfo = posix_getpwuid($uid); $uid = $uinfo['name']; } $gid = filegroup($file); if (function_exists('posix_getgrgid')) { $ginfo = posix_getgrgid($gid); $gid = $ginfo['name']; } $meta['owner'] = $uid; $meta['group'] = $gid; $meta['permission'] = substr(sprintf('%o', fileperms($file)), -4); $meta['last_modification_time'] = date('d.m.Y H:i:s', filemtime($file)); if (is_file($file)) { $meta['filesize'] = round(filesize($file) / (1024 * 1024), 4) . ' MB'; } } elseif ($parentLevel > 0) { $fInfo = pathinfo($file); if (file_exists($fInfo['dirname'])) { $meta['parent_dir'] = $this->_getFileMeta($fInfo['dirname'], --$parentLevel); } } return $meta; }
[ "private", "function", "_getFileMeta", "(", "$", "file", ",", "$", "parentLevel", "=", "0", ")", "{", "$", "meta", "=", "array", "(", "'file'", "=>", "$", "file", ")", ";", "if", "(", "$", "meta", "[", "'exist'", "]", "=", "(", "bool", ")", "file...
get meta data for given file. if file doesn't exists, move up to parent directory @param string $file (max numbers of parent directory lookups) @param int $parentLevel @return array with file meta data
[ "get", "meta", "data", "for", "given", "file", ".", "if", "file", "doesn", "t", "exists", "move", "up", "to", "parent", "directory" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1642-L1677
shopgate/cart-integration-sdk
src/apis.php
ShopgateMerchantApi.getCurlOptArray
protected function getCurlOptArray($override = array()) { $opt = array(); $opt[CURLOPT_HEADER] = false; $opt[CURLOPT_USERAGENT] = 'ShopgatePlugin/' . (defined( 'SHOPGATE_PLUGIN_VERSION' ) ? SHOPGATE_PLUGIN_VERSION : 'called outside plugin'); $opt[CURLOPT_RETURNTRANSFER] = true; $opt[CURLOPT_SSL_VERIFYPEER] = true; // *always* verify peers, otherwise MITM attacks are trivial // Use value of CURL_SSLVERSION_TLSv1_2 for CURLOPT_SSLVERSION, because it is not available before PHP 5.5.19 / 5.6.3 // Actual usage of TLS 1.2 (which is required by PCI DSS) depends on PHP cURL extension and underlying SSL lib $opt[CURLOPT_SSLVERSION] = 6; $opt[CURLOPT_HTTPHEADER] = array( 'X-Shopgate-Library-Version: ' . SHOPGATE_LIBRARY_VERSION, 'X-Shopgate-Plugin-Version: ' . (defined( 'SHOPGATE_PLUGIN_VERSION' ) ? SHOPGATE_PLUGIN_VERSION : 'called outside plugin'), ); $opt[CURLOPT_HTTPHEADER] = !empty($opt[CURLOPT_HTTPHEADER]) ? ($this->authService->getAuthHttpHeaders() + $opt[CURLOPT_HTTPHEADER]) : $this->authService->getAuthHttpHeaders(); $opt[CURLOPT_TIMEOUT] = 30; // Default timeout 30sec $opt[CURLOPT_POST] = true; return ($override + $opt); }
php
protected function getCurlOptArray($override = array()) { $opt = array(); $opt[CURLOPT_HEADER] = false; $opt[CURLOPT_USERAGENT] = 'ShopgatePlugin/' . (defined( 'SHOPGATE_PLUGIN_VERSION' ) ? SHOPGATE_PLUGIN_VERSION : 'called outside plugin'); $opt[CURLOPT_RETURNTRANSFER] = true; $opt[CURLOPT_SSL_VERIFYPEER] = true; // *always* verify peers, otherwise MITM attacks are trivial // Use value of CURL_SSLVERSION_TLSv1_2 for CURLOPT_SSLVERSION, because it is not available before PHP 5.5.19 / 5.6.3 // Actual usage of TLS 1.2 (which is required by PCI DSS) depends on PHP cURL extension and underlying SSL lib $opt[CURLOPT_SSLVERSION] = 6; $opt[CURLOPT_HTTPHEADER] = array( 'X-Shopgate-Library-Version: ' . SHOPGATE_LIBRARY_VERSION, 'X-Shopgate-Plugin-Version: ' . (defined( 'SHOPGATE_PLUGIN_VERSION' ) ? SHOPGATE_PLUGIN_VERSION : 'called outside plugin'), ); $opt[CURLOPT_HTTPHEADER] = !empty($opt[CURLOPT_HTTPHEADER]) ? ($this->authService->getAuthHttpHeaders() + $opt[CURLOPT_HTTPHEADER]) : $this->authService->getAuthHttpHeaders(); $opt[CURLOPT_TIMEOUT] = 30; // Default timeout 30sec $opt[CURLOPT_POST] = true; return ($override + $opt); }
[ "protected", "function", "getCurlOptArray", "(", "$", "override", "=", "array", "(", ")", ")", "{", "$", "opt", "=", "array", "(", ")", ";", "$", "opt", "[", "CURLOPT_HEADER", "]", "=", "false", ";", "$", "opt", "[", "CURLOPT_USERAGENT", "]", "=", "'...
Returns an array of curl-options for requests @param mixed[] $override cURL options to override for this request. @return mixed[] The default cURL options for a Shopgate Merchant API request merged with the options in $override.
[ "Returns", "an", "array", "of", "curl", "-", "options", "for", "requests" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1743-L1773
shopgate/cart-integration-sdk
src/apis.php
ShopgateMerchantApi.sendRequest
protected function sendRequest($parameters = array(), $curlOptOverride = array()) { if (!empty($this->shopNumber)) { $parameters['shop_number'] = $this->shopNumber; } $parameters = !empty($parameters) ? array_merge($this->authService->getAuthPostParams(), $parameters) : $this->authService->getAuthPostParams(); $parameters['trace_id'] = 'spa-' . uniqid(); $this->log( 'Sending request to "' . $this->apiUrl . '": ' . ShopgateLogger::getInstance()->cleanParamsForLog( $parameters ), ShopgateLogger::LOGTYPE_REQUEST ); // init new auth session and generate cURL options $this->authService->startNewSession(); $curlOpt = $this->getCurlOptArray($curlOptOverride); // init cURL connection and send the request $curl = curl_init($this->apiUrl); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($parameters)); curl_setopt_array($curl, $curlOpt); $response = curl_exec($curl); curl_close($curl); // check the result if (!$response) { // exception without logging - this might cause spamming your logs and we will know when our API is offline anyways throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_NO_CONNECTION, null, false, false ); } $decodedResponse = $this->jsonDecode($response, true); if (empty($decodedResponse)) { // exception without logging - this might cause spamming your logs and we will know when our API is offline anyways throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'Response: ' . $response, true, false ); } $responseObject = new ShopgateMerchantApiResponse($decodedResponse); if ($decodedResponse['error'] != 0) { throw new ShopgateMerchantApiException( $decodedResponse['error'], $decodedResponse['error_text'], $responseObject ); } return $responseObject; }
php
protected function sendRequest($parameters = array(), $curlOptOverride = array()) { if (!empty($this->shopNumber)) { $parameters['shop_number'] = $this->shopNumber; } $parameters = !empty($parameters) ? array_merge($this->authService->getAuthPostParams(), $parameters) : $this->authService->getAuthPostParams(); $parameters['trace_id'] = 'spa-' . uniqid(); $this->log( 'Sending request to "' . $this->apiUrl . '": ' . ShopgateLogger::getInstance()->cleanParamsForLog( $parameters ), ShopgateLogger::LOGTYPE_REQUEST ); // init new auth session and generate cURL options $this->authService->startNewSession(); $curlOpt = $this->getCurlOptArray($curlOptOverride); // init cURL connection and send the request $curl = curl_init($this->apiUrl); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($parameters)); curl_setopt_array($curl, $curlOpt); $response = curl_exec($curl); curl_close($curl); // check the result if (!$response) { // exception without logging - this might cause spamming your logs and we will know when our API is offline anyways throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_NO_CONNECTION, null, false, false ); } $decodedResponse = $this->jsonDecode($response, true); if (empty($decodedResponse)) { // exception without logging - this might cause spamming your logs and we will know when our API is offline anyways throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, 'Response: ' . $response, true, false ); } $responseObject = new ShopgateMerchantApiResponse($decodedResponse); if ($decodedResponse['error'] != 0) { throw new ShopgateMerchantApiException( $decodedResponse['error'], $decodedResponse['error_text'], $responseObject ); } return $responseObject; }
[ "protected", "function", "sendRequest", "(", "$", "parameters", "=", "array", "(", ")", ",", "$", "curlOptOverride", "=", "array", "(", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "shopNumber", ")", ")", "{", "$", "parameters", "[...
Prepares the request and sends it to the configured Shopgate Merchant API. @param mixed[] $parameters The parameters to send. @param mixed[] $curlOptOverride cURL options to override for this request. @throws ShopgateLibraryException in case the connection can't be established, the response is invalid or an error occured. @throws ShopgateMerchantApiException @return ShopgateMerchantApiResponse The response object.
[ "Prepares", "the", "request", "and", "sends", "it", "to", "the", "configured", "Shopgate", "Merchant", "API", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1787-L1849
shopgate/cart-integration-sdk
src/apis.php
ShopgateMerchantApi.getShopInfo
public function getShopInfo($parameters = array()) { $request = array( 'action' => 'get_shop_info', ); $request = array_merge($request, $parameters); return $this->sendRequest($request); }
php
public function getShopInfo($parameters = array()) { $request = array( 'action' => 'get_shop_info', ); $request = array_merge($request, $parameters); return $this->sendRequest($request); }
[ "public", "function", "getShopInfo", "(", "$", "parameters", "=", "array", "(", ")", ")", "{", "$", "request", "=", "array", "(", "'action'", "=>", "'get_shop_info'", ",", ")", ";", "$", "request", "=", "array_merge", "(", "$", "request", ",", "$", "pa...
######################################################################
[ "######################################################################" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1858-L1867
shopgate/cart-integration-sdk
src/apis.php
ShopgateMerchantApi.getOrders
public function getOrders($parameters) { $request = array( 'action' => 'get_orders', ); $request = array_merge($request, $parameters); $response = $this->sendRequest($request); // check and reorganize the data of the SMA response $data = $response->getData(); if (!isset($data['orders']) || !is_array($data['orders'])) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"orders" is not set or not an array. Response: ' . var_export($data, true) ); } $orders = array(); foreach ($data['orders'] as $order) { $orders[] = new ShopgateOrder($order); } // put the reorganized data into the response object and return ist $response->setData($orders); return $response; }
php
public function getOrders($parameters) { $request = array( 'action' => 'get_orders', ); $request = array_merge($request, $parameters); $response = $this->sendRequest($request); // check and reorganize the data of the SMA response $data = $response->getData(); if (!isset($data['orders']) || !is_array($data['orders'])) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"orders" is not set or not an array. Response: ' . var_export($data, true) ); } $orders = array(); foreach ($data['orders'] as $order) { $orders[] = new ShopgateOrder($order); } // put the reorganized data into the response object and return ist $response->setData($orders); return $response; }
[ "public", "function", "getOrders", "(", "$", "parameters", ")", "{", "$", "request", "=", "array", "(", "'action'", "=>", "'get_orders'", ",", ")", ";", "$", "request", "=", "array_merge", "(", "$", "request", ",", "$", "parameters", ")", ";", "$", "re...
######################################################################
[ "######################################################################" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1872-L1899
shopgate/cart-integration-sdk
src/apis.php
ShopgateMerchantApi.getItems
public function getItems($parameters) { $parameters['action'] = 'get_items'; $response = $this->sendRequest($parameters); // check and reorganize the data of the SMA response $data = $response->getData(); if (!isset($data['items']) || !is_array($data['items'])) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"items" is not set or not an array. Response: ' . var_export($data, true) ); } $items = array(); foreach ($data['items'] as $item) { $items[] = new ShopgateItem($item); } // put the reorganized data into the response object and return ist $response->setData($items); return $response; }
php
public function getItems($parameters) { $parameters['action'] = 'get_items'; $response = $this->sendRequest($parameters); // check and reorganize the data of the SMA response $data = $response->getData(); if (!isset($data['items']) || !is_array($data['items'])) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"items" is not set or not an array. Response: ' . var_export($data, true) ); } $items = array(); foreach ($data['items'] as $item) { $items[] = new ShopgateItem($item); } // put the reorganized data into the response object and return ist $response->setData($items); return $response; }
[ "public", "function", "getItems", "(", "$", "parameters", ")", "{", "$", "parameters", "[", "'action'", "]", "=", "'get_items'", ";", "$", "response", "=", "$", "this", "->", "sendRequest", "(", "$", "parameters", ")", ";", "// check and reorganize the data of...
######################################################################
[ "######################################################################" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L1992-L2016
shopgate/cart-integration-sdk
src/apis.php
ShopgateMerchantApi.getCategories
public function getCategories($parameters) { $parameters['action'] = 'get_categories'; $response = $this->sendRequest($parameters); // check and reorganize the data of the SMA response $data = $response->getData(); if (!isset($data['categories']) || !is_array($data['categories'])) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"categories" is not set or not an array. Response: ' . var_export($data, true) ); } $categories = array(); foreach ($data['categories'] as $category) { $categories[] = new ShopgateCategory($category); } // put the reorganized data into the response object and return ist $response->setData($categories); return $response; }
php
public function getCategories($parameters) { $parameters['action'] = 'get_categories'; $response = $this->sendRequest($parameters); // check and reorganize the data of the SMA response $data = $response->getData(); if (!isset($data['categories']) || !is_array($data['categories'])) { throw new ShopgateLibraryException( ShopgateLibraryException::MERCHANT_API_INVALID_RESPONSE, '"categories" is not set or not an array. Response: ' . var_export($data, true) ); } $categories = array(); foreach ($data['categories'] as $category) { $categories[] = new ShopgateCategory($category); } // put the reorganized data into the response object and return ist $response->setData($categories); return $response; }
[ "public", "function", "getCategories", "(", "$", "parameters", ")", "{", "$", "parameters", "[", "'action'", "]", "=", "'get_categories'", ";", "$", "response", "=", "$", "this", "->", "sendRequest", "(", "$", "parameters", ")", ";", "// check and reorganize t...
######################################################################
[ "######################################################################" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L2085-L2109
shopgate/cart-integration-sdk
src/apis.php
ShopgateAuthenticationServiceShopgate.buildCustomAuthToken
protected function buildCustomAuthToken($prefix, $customerNumber, $timestamp, $apiKey) { if (empty($customerNumber) || empty($apiKey)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_INVALID_VALUE, 'Shopgate customer number or API key not set.', true, false ); } return sha1("{$prefix}-{$customerNumber}-{$timestamp}-{$apiKey}"); }
php
protected function buildCustomAuthToken($prefix, $customerNumber, $timestamp, $apiKey) { if (empty($customerNumber) || empty($apiKey)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_INVALID_VALUE, 'Shopgate customer number or API key not set.', true, false ); } return sha1("{$prefix}-{$customerNumber}-{$timestamp}-{$apiKey}"); }
[ "protected", "function", "buildCustomAuthToken", "(", "$", "prefix", ",", "$", "customerNumber", ",", "$", "timestamp", ",", "$", "apiKey", ")", "{", "if", "(", "empty", "(", "$", "customerNumber", ")", "||", "empty", "(", "$", "apiKey", ")", ")", "{", ...
Generates the auth token with the given parameters. @param string $prefix @param string $customerNumber @param int $timestamp @param string $apiKey @throws ShopgateLibraryException when no customer number or API key is set @return string The SHA-1 hash Auth Token for Shopgate's Authentication
[ "Generates", "the", "auth", "token", "with", "the", "given", "parameters", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/apis.php#L2319-L2331
someline/starter-framework
src/Someline/Api/Middleware/AutoRenewJwtToken.php
AutoRenewJwtToken.handle
public function handle($request, Closure $next) { $response = $next($request); // verify only if token present if ($token = $this->auth->setRequest($request)->getToken()) { // valid for refresh if (is_jwt_token_valid_for_refresh($token)) { $newToken = refresh_jwt_token(); if (!empty($newToken)) { // send the refreshed token back to the client $response->headers->set('Authorization', $newToken); } } } return $response; }
php
public function handle($request, Closure $next) { $response = $next($request); // verify only if token present if ($token = $this->auth->setRequest($request)->getToken()) { // valid for refresh if (is_jwt_token_valid_for_refresh($token)) { $newToken = refresh_jwt_token(); if (!empty($newToken)) { // send the refreshed token back to the client $response->headers->set('Authorization', $newToken); } } } return $response; }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ")", "{", "$", "response", "=", "$", "next", "(", "$", "request", ")", ";", "// verify only if token present", "if", "(", "$", "token", "=", "$", "this", "->", "auth", "-...
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Api/Middleware/AutoRenewJwtToken.php#L17-L34
makinacorpus/drupal-ucms
ucms_label/src/EventDispatcher/NodeEventSubscriber.php
NodeEventSubscriber.onNodeNewLabels
public function onNodeNewLabels(ResourceEvent $event) { $event->ignoreDefaultChan(); foreach ($event->getArgument('new_labels') as $labelId) { $event->addResourceChanId('label', $labelId); } }
php
public function onNodeNewLabels(ResourceEvent $event) { $event->ignoreDefaultChan(); foreach ($event->getArgument('new_labels') as $labelId) { $event->addResourceChanId('label', $labelId); } }
[ "public", "function", "onNodeNewLabels", "(", "ResourceEvent", "$", "event", ")", "{", "$", "event", "->", "ignoreDefaultChan", "(", ")", ";", "foreach", "(", "$", "event", "->", "getArgument", "(", "'new_labels'", ")", "as", "$", "labelId", ")", "{", "$",...
node:new_labels events handler method. @param ResourceEvent $event
[ "node", ":", "new_labels", "events", "handler", "method", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/EventDispatcher/NodeEventSubscriber.php#L94-L100
makinacorpus/drupal-ucms
ucms_label/src/EventDispatcher/NodeEventSubscriber.php
NodeEventSubscriber.addLabelChannels
protected function addLabelChannels(ResourceEvent $event) { $nodeId = $event->getResourceIdList()[0]; $node = $this->entityManager->getStorage('node')->load($nodeId); $items = field_get_items('node', $node, 'labels'); if ($items) { foreach ($items as $item) { $event->addResourceChanId('label', $item['tid']); } } }
php
protected function addLabelChannels(ResourceEvent $event) { $nodeId = $event->getResourceIdList()[0]; $node = $this->entityManager->getStorage('node')->load($nodeId); $items = field_get_items('node', $node, 'labels'); if ($items) { foreach ($items as $item) { $event->addResourceChanId('label', $item['tid']); } } }
[ "protected", "function", "addLabelChannels", "(", "ResourceEvent", "$", "event", ")", "{", "$", "nodeId", "=", "$", "event", "->", "getResourceIdList", "(", ")", "[", "0", "]", ";", "$", "node", "=", "$", "this", "->", "entityManager", "->", "getStorage", ...
Adds specific channels of the node's labels to the event. @param ResourceEvent $event
[ "Adds", "specific", "channels", "of", "the", "node", "s", "labels", "to", "the", "event", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_label/src/EventDispatcher/NodeEventSubscriber.php#L108-L119
pomirleanu/gif-create
src/GifCreate.php
GifCreate.create
public function create($frames, $durations = 10, $loop = null) { if (count($frames) < 2) { throw new \Exception(sprintf($this->errors[ 'ERR06' ])); } // Update loop value if passed in. $this->mergeConfigIfSet('loop', $loop); // Check if $frames is a dir; get all files in ascending order if yes (else die): if (! is_array($frames)) { if (is_dir($frames)) { $this->frames_dir = $frames; if ($frames = scandir($this->frames_dir)) { $frames = array_filter($frames, function ($dir) { return $dir[ 0 ] != "."; }); array_walk($frames, function (&$dir) { $dir = $this->frames_dir.DIRECTORY_SEPARATOR."$dir"; }); } } if (! is_array($frames)) { throw new \Exception(sprintf($this->errors[ 'ERR05' ], $this->frames_dir)); } } assert(is_array($frames)); if (sizeof($frames) < 2) { throw new \Exception($this->errors[ 'ERR00' ]); } return $this->buildFrameSources($frames, $durations); }
php
public function create($frames, $durations = 10, $loop = null) { if (count($frames) < 2) { throw new \Exception(sprintf($this->errors[ 'ERR06' ])); } // Update loop value if passed in. $this->mergeConfigIfSet('loop', $loop); // Check if $frames is a dir; get all files in ascending order if yes (else die): if (! is_array($frames)) { if (is_dir($frames)) { $this->frames_dir = $frames; if ($frames = scandir($this->frames_dir)) { $frames = array_filter($frames, function ($dir) { return $dir[ 0 ] != "."; }); array_walk($frames, function (&$dir) { $dir = $this->frames_dir.DIRECTORY_SEPARATOR."$dir"; }); } } if (! is_array($frames)) { throw new \Exception(sprintf($this->errors[ 'ERR05' ], $this->frames_dir)); } } assert(is_array($frames)); if (sizeof($frames) < 2) { throw new \Exception($this->errors[ 'ERR00' ]); } return $this->buildFrameSources($frames, $durations); }
[ "public", "function", "create", "(", "$", "frames", ",", "$", "durations", "=", "10", ",", "$", "loop", "=", "null", ")", "{", "if", "(", "count", "(", "$", "frames", ")", "<", "2", ")", "{", "throw", "new", "\\", "Exception", "(", "sprintf", "("...
Creates a gif from the given array images sources @param $frames @param int $durations @param null $loop @return \Pomirleanu\GifCreate\GifCreate @throws \Exception
[ "Creates", "a", "gif", "from", "the", "given", "array", "images", "sources" ]
train
https://github.com/pomirleanu/gif-create/blob/84a840fb53285b8531d2d6e020434f6c501bf5bc/src/GifCreate.php#L115-L149
pomirleanu/gif-create
src/GifCreate.php
GifCreate.buildFrameSources
private function buildFrameSources($frames, $durations) { $i = 0; foreach ($frames as $frame) { $resourceImage = $frame; if (is_resource($frame)) { // in-memory image resource (hopefully) $resourceImg = $frame; ob_start(); imagegif($frame); $this->sources[] = ob_get_contents(); ob_end_clean(); if (substr($this->sources[ $i ], 0, 6) != 'GIF87a' && substr($this->sources[ $i ], 0, 6) != 'GIF89a') { throw new \Exception($i.' '.$this->errors[ 'ERR01' ]); } } elseif (is_string($frame)) { // file path, URL or binary data if (@is_readable($frame)) { // file path $bin = file_get_contents($frame); } else { if (filter_var($frame, FILTER_VALIDATE_URL)) { if (ini_get('allow_url_fopen')) { $bin = @file_get_contents($frame); } else { throw new \Exception($i.' '.$this->errors[ 'ERR04' ]); } } else { $bin = $frame; } } if (! ($bin && ($resourceImage = imagecreatefromstring($bin)))) { throw new \Exception($i.' '.sprintf($this->errors[ 'ERR05' ], substr($frame, 0, 200))); } ob_start(); imagegif($resourceImage); $this->sources[] = ob_get_contents(); ob_end_clean(); } else { // Fail throw new \Exception($this->errors[ 'ERR02' ]); } if ($i == 0) { $this->transparent_color = imagecolortransparent($resourceImage); } for ($j = (13 + 3 * (2 << (ord($this->sources[ $i ]{10}) & 0x07))), $k = true; $k; $j++) { switch ($this->sources[ $i ]{$j}) { case '!': if ((substr($this->sources[ $i ], ($j + 3), 8)) == 'NETSCAPE') { throw new \Exception($this->errors[ 'ERR03' ].' ('.($i + 1).' source).'); } break; case ';': $k = false; break; } } unset($resourceImg); ++$i; }//foreach $this->gifAddHeader(); for ($i = 0; $i < count($this->sources); $i++) { // Use the last delay, if none has been specified for the current frame if (is_array($durations)) { $d = (empty($durations[ $i ]) ? $this->config[ 'duration' ] : $durations[ $i ]); $this->config[ 'duration' ] = $d; } else { $d = $durations; } $this->addFrame($i, $d); } $this->gif .= ';'; return $this; }
php
private function buildFrameSources($frames, $durations) { $i = 0; foreach ($frames as $frame) { $resourceImage = $frame; if (is_resource($frame)) { // in-memory image resource (hopefully) $resourceImg = $frame; ob_start(); imagegif($frame); $this->sources[] = ob_get_contents(); ob_end_clean(); if (substr($this->sources[ $i ], 0, 6) != 'GIF87a' && substr($this->sources[ $i ], 0, 6) != 'GIF89a') { throw new \Exception($i.' '.$this->errors[ 'ERR01' ]); } } elseif (is_string($frame)) { // file path, URL or binary data if (@is_readable($frame)) { // file path $bin = file_get_contents($frame); } else { if (filter_var($frame, FILTER_VALIDATE_URL)) { if (ini_get('allow_url_fopen')) { $bin = @file_get_contents($frame); } else { throw new \Exception($i.' '.$this->errors[ 'ERR04' ]); } } else { $bin = $frame; } } if (! ($bin && ($resourceImage = imagecreatefromstring($bin)))) { throw new \Exception($i.' '.sprintf($this->errors[ 'ERR05' ], substr($frame, 0, 200))); } ob_start(); imagegif($resourceImage); $this->sources[] = ob_get_contents(); ob_end_clean(); } else { // Fail throw new \Exception($this->errors[ 'ERR02' ]); } if ($i == 0) { $this->transparent_color = imagecolortransparent($resourceImage); } for ($j = (13 + 3 * (2 << (ord($this->sources[ $i ]{10}) & 0x07))), $k = true; $k; $j++) { switch ($this->sources[ $i ]{$j}) { case '!': if ((substr($this->sources[ $i ], ($j + 3), 8)) == 'NETSCAPE') { throw new \Exception($this->errors[ 'ERR03' ].' ('.($i + 1).' source).'); } break; case ';': $k = false; break; } } unset($resourceImg); ++$i; }//foreach $this->gifAddHeader(); for ($i = 0; $i < count($this->sources); $i++) { // Use the last delay, if none has been specified for the current frame if (is_array($durations)) { $d = (empty($durations[ $i ]) ? $this->config[ 'duration' ] : $durations[ $i ]); $this->config[ 'duration' ] = $d; } else { $d = $durations; } $this->addFrame($i, $d); } $this->gif .= ';'; return $this; }
[ "private", "function", "buildFrameSources", "(", "$", "frames", ",", "$", "durations", ")", "{", "$", "i", "=", "0", ";", "foreach", "(", "$", "frames", "as", "$", "frame", ")", "{", "$", "resourceImage", "=", "$", "frame", ";", "if", "(", "is_resour...
Building the frame sources for the given images @param $frames @param $durations @return $this @throws \Exception
[ "Building", "the", "frame", "sources", "for", "the", "given", "images" ]
train
https://github.com/pomirleanu/gif-create/blob/84a840fb53285b8531d2d6e020434f6c501bf5bc/src/GifCreate.php#L173-L254
pomirleanu/gif-create
src/GifCreate.php
GifCreate.gifAddHeader
protected function gifAddHeader() { $cmap = 0; if (ord($this->sources[ 0 ]{10}) & 0x80) { $cmap = 3 * (2 << (ord($this->sources[ 0 ]{10}) & 0x07)); $this->gif .= substr($this->sources[ 0 ], 6, 7); $this->gif .= substr($this->sources[ 0 ], 13, $cmap); $this->gif .= "!\377\13NETSCAPE2.0\3\1".$this->word2bin($this->config[ 'loop' ])."\0"; } }
php
protected function gifAddHeader() { $cmap = 0; if (ord($this->sources[ 0 ]{10}) & 0x80) { $cmap = 3 * (2 << (ord($this->sources[ 0 ]{10}) & 0x07)); $this->gif .= substr($this->sources[ 0 ], 6, 7); $this->gif .= substr($this->sources[ 0 ], 13, $cmap); $this->gif .= "!\377\13NETSCAPE2.0\3\1".$this->word2bin($this->config[ 'loop' ])."\0"; } }
[ "protected", "function", "gifAddHeader", "(", ")", "{", "$", "cmap", "=", "0", ";", "if", "(", "ord", "(", "$", "this", "->", "sources", "[", "0", "]", "{", "10", "}", ")", "&", "0x80", ")", "{", "$", "cmap", "=", "3", "*", "(", "2", "<<", ...
Add the header gif string in its source
[ "Add", "the", "header", "gif", "string", "in", "its", "source" ]
train
https://github.com/pomirleanu/gif-create/blob/84a840fb53285b8531d2d6e020434f6c501bf5bc/src/GifCreate.php#L260-L270
pomirleanu/gif-create
src/GifCreate.php
GifCreate.gifBlockCompare
private function gifBlockCompare($globalBlock, $localBlock, $length) { for ($i = 0; $i < $length; $i++) { if ($globalBlock [ 3 * $i + 0 ] != $localBlock [ 3 * $i + 0 ] || $globalBlock [ 3 * $i + 1 ] != $localBlock [ 3 * $i + 1 ] || $globalBlock [ 3 * $i + 2 ] != $localBlock [ 3 * $i + 2 ]) { return 0; } } return 1; }
php
private function gifBlockCompare($globalBlock, $localBlock, $length) { for ($i = 0; $i < $length; $i++) { if ($globalBlock [ 3 * $i + 0 ] != $localBlock [ 3 * $i + 0 ] || $globalBlock [ 3 * $i + 1 ] != $localBlock [ 3 * $i + 1 ] || $globalBlock [ 3 * $i + 2 ] != $localBlock [ 3 * $i + 2 ]) { return 0; } } return 1; }
[ "private", "function", "gifBlockCompare", "(", "$", "globalBlock", ",", "$", "localBlock", ",", "$", "length", ")", "{", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", "{", "if", "(", "$", "globalBloc...
Compare two block and return the version @param string $globalBlock @param string $localBlock @param integer $length @return integer
[ "Compare", "two", "block", "and", "return", "the", "version" ]
train
https://github.com/pomirleanu/gif-create/blob/84a840fb53285b8531d2d6e020434f6c501bf5bc/src/GifCreate.php#L381-L392
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.redirect
public function redirect($url, $autoRedirect = true) { if (!$this->config->getShopNumber()) { return ''; } $url .= $this->processQueryString($url); if ( !$this->isRedirectAllowed() || !$this->isMobileRequest() || !$autoRedirect || (($this->redirectType == 'default') && !$this->enableDefaultRedirect) ) { return $this->getJsHeader($url); } // validate url if (!preg_match('#^(http|https)\://#', $url)) { return $this->getJsHeader(); } // perform redirect header("Location: " . $url, true, 301); exit; }
php
public function redirect($url, $autoRedirect = true) { if (!$this->config->getShopNumber()) { return ''; } $url .= $this->processQueryString($url); if ( !$this->isRedirectAllowed() || !$this->isMobileRequest() || !$autoRedirect || (($this->redirectType == 'default') && !$this->enableDefaultRedirect) ) { return $this->getJsHeader($url); } // validate url if (!preg_match('#^(http|https)\://#', $url)) { return $this->getJsHeader(); } // perform redirect header("Location: " . $url, true, 301); exit; }
[ "public", "function", "redirect", "(", "$", "url", ",", "$", "autoRedirect", "=", "true", ")", "{", "if", "(", "!", "$", "this", "->", "config", "->", "getShopNumber", "(", ")", ")", "{", "return", "''", ";", "}", "$", "url", ".=", "$", "this", "...
@param string $url @param bool $autoRedirect @return string @post ends script execution in case of http redirect
[ "@param", "string", "$url", "@param", "bool", "$autoRedirect" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L355-L378
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.loadTemplate
protected function loadTemplate($filePath) { if (!file_exists($filePath)) { return ''; } $html = @file_get_contents($filePath); if (empty($html)) { return ''; } return $html; }
php
protected function loadTemplate($filePath) { if (!file_exists($filePath)) { return ''; } $html = @file_get_contents($filePath); if (empty($html)) { return ''; } return $html; }
[ "protected", "function", "loadTemplate", "(", "$", "filePath", ")", "{", "if", "(", "!", "file_exists", "(", "$", "filePath", ")", ")", "{", "return", "''", ";", "}", "$", "html", "=", "@", "file_get_contents", "(", "$", "filePath", ")", ";", "if", "...
###############
[ "###############" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L583-L595
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.getMobileUrl
protected function getMobileUrl() { if (!empty($this->cname)) { return $this->cname; } elseif (!empty($this->alias)) { return 'http://' . $this->alias . $this->getShopgateUrl(); } }
php
protected function getMobileUrl() { if (!empty($this->cname)) { return $this->cname; } elseif (!empty($this->alias)) { return 'http://' . $this->alias . $this->getShopgateUrl(); } }
[ "protected", "function", "getMobileUrl", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "cname", ")", ")", "{", "return", "$", "this", "->", "cname", ";", "}", "elseif", "(", "!", "empty", "(", "$", "this", "->", "alias", ")", ")...
Generates the root mobile Url for the redirect
[ "Generates", "the", "root", "mobile", "Url", "for", "the", "redirect" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L600-L607
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.getShopgateUrl
protected function getShopgateUrl() { switch ($this->config->getServer()) { default: // fall through to "live" case 'live': return ShopgateMobileRedirectInterface::SHOPGATE_LIVE_ALIAS; case 'sl': return ShopgateMobileRedirectInterface::SHOPGATE_SL_ALIAS; case 'pg': return ShopgateMobileRedirectInterface::SHOPGATE_PG_ALIAS; case 'custom': return '.localdev.cc/php/shopgate/index.php'; // for Shopgate development & testing } }
php
protected function getShopgateUrl() { switch ($this->config->getServer()) { default: // fall through to "live" case 'live': return ShopgateMobileRedirectInterface::SHOPGATE_LIVE_ALIAS; case 'sl': return ShopgateMobileRedirectInterface::SHOPGATE_SL_ALIAS; case 'pg': return ShopgateMobileRedirectInterface::SHOPGATE_PG_ALIAS; case 'custom': return '.localdev.cc/php/shopgate/index.php'; // for Shopgate development & testing } }
[ "protected", "function", "getShopgateUrl", "(", ")", "{", "switch", "(", "$", "this", "->", "config", "->", "getServer", "(", ")", ")", "{", "default", ":", "// fall through to \"live\"", "case", "'live'", ":", "return", "ShopgateMobileRedirectInterface", "::", ...
Returns the URL to be appended to the alias of a shop. The method determines this by the "server" setting in ShopgateConfig. If it's set to "custom", localdev.cc will be used for Shopgate local development and testing. @return string The URL that can be appended to the alias, e.g. ".shopgate.com"
[ "Returns", "the", "URL", "to", "be", "appended", "to", "the", "alias", "of", "a", "shop", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L617-L630
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.updateRedirectKeywords
protected function updateRedirectKeywords() { // load the keywords try { $redirectKeywordsFromFile = $this->loadKeywordsFromFile($this->config->getRedirectKeywordCachePath()); $skipRedirectKeywordsFromFile = $this->loadKeywordsFromFile( $this->config->getRedirectSkipKeywordCachePath() ); } catch (ShopgateLibraryException $e) { // if reading the files fails DO NOT UPDATE return; } // conditions for updating keywords $updateDesired = ( $this->updateRedirectKeywords && (!empty($this->merchantApi)) && ( (time() - ($redirectKeywordsFromFile['timestamp'] + ($this->redirectKeywordCacheTime * 3600)) > 0) || (time() - ($skipRedirectKeywordsFromFile['timestamp'] + ($this->redirectKeywordCacheTime * 3600)) > 0) ) ); // strip timestamp, it's not needed anymore $redirectKeywords = $redirectKeywordsFromFile['keywords']; $skipRedirectKeywords = $skipRedirectKeywordsFromFile['keywords']; // perform update if ($updateDesired) { try { // fetch keywords from Shopgate Merchant API $keywordsFromApi = $this->merchantApi->getMobileRedirectUserAgents(); $redirectKeywords = $keywordsFromApi['keywords']; $skipRedirectKeywords = $keywordsFromApi['skip_keywords']; // save keywords to their files $this->saveKeywordsToFile($redirectKeywords, $this->config->getRedirectKeywordCachePath()); $this->saveKeywordsToFile($skipRedirectKeywords, $this->config->getRedirectSkipKeywordCachePath()); } catch (Exception $e) { /* do not abort */ $newTimestamp = (time() - ($this->redirectKeywordCacheTime * 3600)) + 300; // save old keywords $this->saveKeywordsToFile( $redirectKeywords, $this->config->getRedirectKeywordCachePath(), $newTimestamp ); $this->saveKeywordsToFile( $skipRedirectKeywords, $this->config->getRedirectSkipKeywordCachePath(), $newTimestamp ); } } // set keywords $this->setRedirectKeywords($redirectKeywords); $this->setSkipRedirectKeywords($skipRedirectKeywords); }
php
protected function updateRedirectKeywords() { // load the keywords try { $redirectKeywordsFromFile = $this->loadKeywordsFromFile($this->config->getRedirectKeywordCachePath()); $skipRedirectKeywordsFromFile = $this->loadKeywordsFromFile( $this->config->getRedirectSkipKeywordCachePath() ); } catch (ShopgateLibraryException $e) { // if reading the files fails DO NOT UPDATE return; } // conditions for updating keywords $updateDesired = ( $this->updateRedirectKeywords && (!empty($this->merchantApi)) && ( (time() - ($redirectKeywordsFromFile['timestamp'] + ($this->redirectKeywordCacheTime * 3600)) > 0) || (time() - ($skipRedirectKeywordsFromFile['timestamp'] + ($this->redirectKeywordCacheTime * 3600)) > 0) ) ); // strip timestamp, it's not needed anymore $redirectKeywords = $redirectKeywordsFromFile['keywords']; $skipRedirectKeywords = $skipRedirectKeywordsFromFile['keywords']; // perform update if ($updateDesired) { try { // fetch keywords from Shopgate Merchant API $keywordsFromApi = $this->merchantApi->getMobileRedirectUserAgents(); $redirectKeywords = $keywordsFromApi['keywords']; $skipRedirectKeywords = $keywordsFromApi['skip_keywords']; // save keywords to their files $this->saveKeywordsToFile($redirectKeywords, $this->config->getRedirectKeywordCachePath()); $this->saveKeywordsToFile($skipRedirectKeywords, $this->config->getRedirectSkipKeywordCachePath()); } catch (Exception $e) { /* do not abort */ $newTimestamp = (time() - ($this->redirectKeywordCacheTime * 3600)) + 300; // save old keywords $this->saveKeywordsToFile( $redirectKeywords, $this->config->getRedirectKeywordCachePath(), $newTimestamp ); $this->saveKeywordsToFile( $skipRedirectKeywords, $this->config->getRedirectSkipKeywordCachePath(), $newTimestamp ); } } // set keywords $this->setRedirectKeywords($redirectKeywords); $this->setSkipRedirectKeywords($skipRedirectKeywords); }
[ "protected", "function", "updateRedirectKeywords", "(", ")", "{", "// load the keywords", "try", "{", "$", "redirectKeywordsFromFile", "=", "$", "this", "->", "loadKeywordsFromFile", "(", "$", "this", "->", "config", "->", "getRedirectKeywordCachePath", "(", ")", ")...
Updates the (skip) keywords array from cache file or Shopgate Merchant API if enabled.
[ "Updates", "the", "(", "skip", ")", "keywords", "array", "from", "cache", "file", "or", "Shopgate", "Merchant", "API", "if", "enabled", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L635-L692
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.saveKeywordsToFile
protected function saveKeywordsToFile($keywords, $file, $timestamp = null) { if (is_null($timestamp)) { $timestamp = time(); } array_unshift($keywords, $timestamp); // add timestamp to first line if (!@file_put_contents($file, implode("\n", $keywords))) { // no logging - this could end up in spamming the logs // $this->log(ShopgateLibraryException::buildLogMessageFor(ShopgateLibraryException::FILE_READ_WRITE_ERROR, 'Could not write to "'.$file.'".')); } }
php
protected function saveKeywordsToFile($keywords, $file, $timestamp = null) { if (is_null($timestamp)) { $timestamp = time(); } array_unshift($keywords, $timestamp); // add timestamp to first line if (!@file_put_contents($file, implode("\n", $keywords))) { // no logging - this could end up in spamming the logs // $this->log(ShopgateLibraryException::buildLogMessageFor(ShopgateLibraryException::FILE_READ_WRITE_ERROR, 'Could not write to "'.$file.'".')); } }
[ "protected", "function", "saveKeywordsToFile", "(", "$", "keywords", ",", "$", "file", ",", "$", "timestamp", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "timestamp", ")", ")", "{", "$", "timestamp", "=", "time", "(", ")", ";", "}", "array...
Saves redirect keywords to file. @param string[] $keywords The list of keywords to write to the file. @param string $file The path to the file. @param null $timestamp
[ "Saves", "redirect", "keywords", "to", "file", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L701-L711
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.loadKeywordsFromFile
protected function loadKeywordsFromFile($file) { $defaultReturn = array( 'timestamp' => 0, 'keywords' => array(), ); $cacheFile = @fopen($file, 'a+'); if (empty($cacheFile)) { // exception without logging throw new ShopgateLibraryException( ShopgateLibraryException::FILE_READ_WRITE_ERROR, 'Could not read file "' . $file . '".', false, false ); } $keywordsFromFile = explode("\n", @fread($cacheFile, filesize($file))); @fclose($cacheFile); return (empty($keywordsFromFile)) ? $defaultReturn : array( 'timestamp' => (int)array_shift($keywordsFromFile), // strip timestamp in first line 'keywords' => $keywordsFromFile, ); }
php
protected function loadKeywordsFromFile($file) { $defaultReturn = array( 'timestamp' => 0, 'keywords' => array(), ); $cacheFile = @fopen($file, 'a+'); if (empty($cacheFile)) { // exception without logging throw new ShopgateLibraryException( ShopgateLibraryException::FILE_READ_WRITE_ERROR, 'Could not read file "' . $file . '".', false, false ); } $keywordsFromFile = explode("\n", @fread($cacheFile, filesize($file))); @fclose($cacheFile); return (empty($keywordsFromFile)) ? $defaultReturn : array( 'timestamp' => (int)array_shift($keywordsFromFile), // strip timestamp in first line 'keywords' => $keywordsFromFile, ); }
[ "protected", "function", "loadKeywordsFromFile", "(", "$", "file", ")", "{", "$", "defaultReturn", "=", "array", "(", "'timestamp'", "=>", "0", ",", "'keywords'", "=>", "array", "(", ")", ",", ")", ";", "$", "cacheFile", "=", "@", "fopen", "(", "$", "f...
Reads redirect keywords from file. @param string $file The file to read the keywords from. @return array<'timestamp' => int, 'keywords' => string[]) An array with the 'timestamp' of the last update and the list of 'keywords'. @throws ShopgateLibraryException in case the file cannot be opened.
[ "Reads", "redirect", "keywords", "from", "file", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L722-L747
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.processQueryString
protected function processQueryString($url) { $queryDataKeys = array_intersect($this->config->getRedirectableGetParams(), array_keys($_GET)); $queryData = array_intersect_key($_GET, array_flip($queryDataKeys)); $connector = preg_match('/\?/', $url) ? "&" : "?"; return count($queryData) ? $connector . http_build_query($queryData) : ""; }
php
protected function processQueryString($url) { $queryDataKeys = array_intersect($this->config->getRedirectableGetParams(), array_keys($_GET)); $queryData = array_intersect_key($_GET, array_flip($queryDataKeys)); $connector = preg_match('/\?/', $url) ? "&" : "?"; return count($queryData) ? $connector . http_build_query($queryData) : ""; }
[ "protected", "function", "processQueryString", "(", "$", "url", ")", "{", "$", "queryDataKeys", "=", "array_intersect", "(", "$", "this", "->", "config", "->", "getRedirectableGetParams", "(", ")", ",", "array_keys", "(", "$", "_GET", ")", ")", ";", "$", "...
Passes allowed get params to the url as querystring @param string $url @return string $url
[ "Passes", "allowed", "get", "params", "to", "the", "url", "as", "querystring" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L766-L778
shopgate/cart-integration-sdk
src/redirect.php
ShopgateMobileRedirect.buildScriptDefault
public function buildScriptDefault($autoRedirect = true) { $this->redirectType = 'default'; return $this->redirect($this->getShopUrl(), $autoRedirect); }
php
public function buildScriptDefault($autoRedirect = true) { $this->redirectType = 'default'; return $this->redirect($this->getShopUrl(), $autoRedirect); }
[ "public", "function", "buildScriptDefault", "(", "$", "autoRedirect", "=", "true", ")", "{", "$", "this", "->", "redirectType", "=", "'default'", ";", "return", "$", "this", "->", "redirect", "(", "$", "this", "->", "getShopUrl", "(", ")", ",", "$", "aut...
#############################
[ "#############################" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/redirect.php#L784-L789
NicolasMahe/Laravel-SlackOutput
src/Command/SlackPost.php
SlackPost.handle
public function handle() { $this->line('Processing...'); //get command arguments $message = $this->argument('message'); $to = $this->argument('to'); $attach = $this->argument('attach'); //init client $this->initClient(); //attach data $this->addAttachment($attach); //add to $this->addTo($to); //send $this->send($message); $this->info('Message sent'); }
php
public function handle() { $this->line('Processing...'); //get command arguments $message = $this->argument('message'); $to = $this->argument('to'); $attach = $this->argument('attach'); //init client $this->initClient(); //attach data $this->addAttachment($attach); //add to $this->addTo($to); //send $this->send($message); $this->info('Message sent'); }
[ "public", "function", "handle", "(", ")", "{", "$", "this", "->", "line", "(", "'Processing...'", ")", ";", "//get command arguments", "$", "message", "=", "$", "this", "->", "argument", "(", "'message'", ")", ";", "$", "to", "=", "$", "this", "->", "a...
Execute the console command. @return mixed @throws Exception
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Command/SlackPost.php#L43-L65
NicolasMahe/Laravel-SlackOutput
src/Command/SlackPost.php
SlackPost.initClient
protected function initClient() { //get slack config $slack_config = config('slack-output'); if (empty( $slack_config["endpoint"] )) { throw new Exception("The endpoint url is not set in the config"); } //init client $this->client = new Client($slack_config["endpoint"], [ "username" => $slack_config["username"], "icon" => $slack_config["icon"] ]); }
php
protected function initClient() { //get slack config $slack_config = config('slack-output'); if (empty( $slack_config["endpoint"] )) { throw new Exception("The endpoint url is not set in the config"); } //init client $this->client = new Client($slack_config["endpoint"], [ "username" => $slack_config["username"], "icon" => $slack_config["icon"] ]); }
[ "protected", "function", "initClient", "(", ")", "{", "//get slack config", "$", "slack_config", "=", "config", "(", "'slack-output'", ")", ";", "if", "(", "empty", "(", "$", "slack_config", "[", "\"endpoint\"", "]", ")", ")", "{", "throw", "new", "Exception...
Init the slack client @return Client @throws Exception
[ "Init", "the", "slack", "client" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Command/SlackPost.php#L74-L88
NicolasMahe/Laravel-SlackOutput
src/Command/SlackPost.php
SlackPost.addAttachment
protected function addAttachment($attach) { if (is_array($attach)) { if ($this->is_assoc($attach)) { $attach = [ $attach ]; } foreach ($attach as $attachElement) { $this->client = $this->client->attach($attachElement); } } }
php
protected function addAttachment($attach) { if (is_array($attach)) { if ($this->is_assoc($attach)) { $attach = [ $attach ]; } foreach ($attach as $attachElement) { $this->client = $this->client->attach($attachElement); } } }
[ "protected", "function", "addAttachment", "(", "$", "attach", ")", "{", "if", "(", "is_array", "(", "$", "attach", ")", ")", "{", "if", "(", "$", "this", "->", "is_assoc", "(", "$", "attach", ")", ")", "{", "$", "attach", "=", "[", "$", "attach", ...
Add the attachments @param $attach
[ "Add", "the", "attachments" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Command/SlackPost.php#L96-L107
NicolasMahe/Laravel-SlackOutput
src/Command/SlackPost.php
SlackPost.addTo
protected function addTo($to) { if ( ! empty( $to )) { $this->client = $this->client->to($to); } }
php
protected function addTo($to) { if ( ! empty( $to )) { $this->client = $this->client->to($to); } }
[ "protected", "function", "addTo", "(", "$", "to", ")", "{", "if", "(", "!", "empty", "(", "$", "to", ")", ")", "{", "$", "this", "->", "client", "=", "$", "this", "->", "client", "->", "to", "(", "$", "to", ")", ";", "}", "}" ]
Add the receiver @param $to
[ "Add", "the", "receiver" ]
train
https://github.com/NicolasMahe/Laravel-SlackOutput/blob/fc3722ba64a0ce4d833555bb1a27513e13959b34/src/Command/SlackPost.php#L115-L120
evercode1/trait-maker
src/MakeTrait.php
MakeTrait.handle
public function handle() { $this->setInputsFromArtisan(); if ( $this->makeTraitDirectory()->makeTraitFile() ) { $this->sendSuccessMessage(); return; } $this->error('Oops, something went wrong!'); }
php
public function handle() { $this->setInputsFromArtisan(); if ( $this->makeTraitDirectory()->makeTraitFile() ) { $this->sendSuccessMessage(); return; } $this->error('Oops, something went wrong!'); }
[ "public", "function", "handle", "(", ")", "{", "$", "this", "->", "setInputsFromArtisan", "(", ")", ";", "if", "(", "$", "this", "->", "makeTraitDirectory", "(", ")", "->", "makeTraitFile", "(", ")", ")", "{", "$", "this", "->", "sendSuccessMessage", "("...
Execute the console command. @return mixed
[ "Execute", "the", "console", "command", "." ]
train
https://github.com/evercode1/trait-maker/blob/22636ad24439608a9dcd20ec20cd82a10cab0bbe/src/MakeTrait.php#L49-L65
despark/ignicms
app/Http/Requests/UserUpdateRequest.php
UserUpdateRequest.rules
public function rules() { $model = new User(); $rules = $model->getRulesUpdate(); $rules['email'] = str_replace('{id}', $this->route()->getParameter('user'), $rules['email']); return $rules; }
php
public function rules() { $model = new User(); $rules = $model->getRulesUpdate(); $rules['email'] = str_replace('{id}', $this->route()->getParameter('user'), $rules['email']); return $rules; }
[ "public", "function", "rules", "(", ")", "{", "$", "model", "=", "new", "User", "(", ")", ";", "$", "rules", "=", "$", "model", "->", "getRulesUpdate", "(", ")", ";", "$", "rules", "[", "'email'", "]", "=", "str_replace", "(", "'{id}'", ",", "$", ...
Get the validation rules that apply to the request. @return array
[ "Get", "the", "validation", "rules", "that", "apply", "to", "the", "request", "." ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/app/Http/Requests/UserUpdateRequest.php#L33-L40
makinacorpus/drupal-ucms
ucms_cart/src/Cart/CartStorage.php
CartStorage.addFor
public function addFor($uid, $nid) { $exists = (bool)$this ->db ->query("SELECT 1 FROM {ucms_cart} WHERE nid = :nid AND uid = :uid", [ ':nid' => $nid, ':uid' => $uid, ]) ->fetchField() ; if ($exists) { return false; } $this ->db ->merge('ucms_cart') ->key([ 'nid' => $nid, 'uid' => $uid, 'ts_added' => (new \DateTime())->format('Y-m-d H:i:s'), ]) ->execute() ; return true; }
php
public function addFor($uid, $nid) { $exists = (bool)$this ->db ->query("SELECT 1 FROM {ucms_cart} WHERE nid = :nid AND uid = :uid", [ ':nid' => $nid, ':uid' => $uid, ]) ->fetchField() ; if ($exists) { return false; } $this ->db ->merge('ucms_cart') ->key([ 'nid' => $nid, 'uid' => $uid, 'ts_added' => (new \DateTime())->format('Y-m-d H:i:s'), ]) ->execute() ; return true; }
[ "public", "function", "addFor", "(", "$", "uid", ",", "$", "nid", ")", "{", "$", "exists", "=", "(", "bool", ")", "$", "this", "->", "db", "->", "query", "(", "\"SELECT 1 FROM {ucms_cart} WHERE nid = :nid AND uid = :uid\"", ",", "[", "':nid'", "=>", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_cart/src/Cart/CartStorage.php#L30-L57
makinacorpus/drupal-ucms
ucms_cart/src/Cart/CartStorage.php
CartStorage.has
public function has($uid, $nid) { return (bool)$this ->db ->query( "SELECT 1 FROM {ucms_cart} WHERE nid = ? AND uid = ?", [$nid, $uid] ) ->fetchField() ; }
php
public function has($uid, $nid) { return (bool)$this ->db ->query( "SELECT 1 FROM {ucms_cart} WHERE nid = ? AND uid = ?", [$nid, $uid] ) ->fetchField() ; }
[ "public", "function", "has", "(", "$", "uid", ",", "$", "nid", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "db", "->", "query", "(", "\"SELECT 1 FROM {ucms_cart} WHERE nid = ? AND uid = ?\"", ",", "[", "$", "nid", ",", "$", "uid", "]", ")", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_cart/src/Cart/CartStorage.php#L62-L72
makinacorpus/drupal-ucms
ucms_cart/src/Cart/CartStorage.php
CartStorage.removeFor
public function removeFor($uid, $nid) { $this ->db ->delete('ucms_cart') ->condition('nid', $nid) ->condition('uid', $uid) ->execute() ; }
php
public function removeFor($uid, $nid) { $this ->db ->delete('ucms_cart') ->condition('nid', $nid) ->condition('uid', $uid) ->execute() ; }
[ "public", "function", "removeFor", "(", "$", "uid", ",", "$", "nid", ")", "{", "$", "this", "->", "db", "->", "delete", "(", "'ucms_cart'", ")", "->", "condition", "(", "'nid'", ",", "$", "nid", ")", "->", "condition", "(", "'uid'", ",", "$", "uid"...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_cart/src/Cart/CartStorage.php#L77-L86
makinacorpus/drupal-ucms
ucms_cart/src/Cart/CartStorage.php
CartStorage.listFor
public function listFor($uid, $limit = 14, $offset = 0) { $q = $this ->db ->select('ucms_cart', 'c') ->condition('c.uid', $uid) ; $q->addField('c', 'nid'); $q->addField('c', 'uid'); $q->addField('c', 'ts_added', 'added'); $q->join('node', 'n', "n.nid = c.nid"); $q->range($offset, $limit); return $q //->extend('PagerDefault') //->limit(12) // @todo Restore me! //->addTag('node_access') ->orderBy('c.ts_added', 'desc') ->addTag(Access::QUERY_TAG_CONTEXT_OPT_OUT) ->execute() ->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, CartItem::class) ; }
php
public function listFor($uid, $limit = 14, $offset = 0) { $q = $this ->db ->select('ucms_cart', 'c') ->condition('c.uid', $uid) ; $q->addField('c', 'nid'); $q->addField('c', 'uid'); $q->addField('c', 'ts_added', 'added'); $q->join('node', 'n', "n.nid = c.nid"); $q->range($offset, $limit); return $q //->extend('PagerDefault') //->limit(12) // @todo Restore me! //->addTag('node_access') ->orderBy('c.ts_added', 'desc') ->addTag(Access::QUERY_TAG_CONTEXT_OPT_OUT) ->execute() ->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, CartItem::class) ; }
[ "public", "function", "listFor", "(", "$", "uid", ",", "$", "limit", "=", "14", ",", "$", "offset", "=", "0", ")", "{", "$", "q", "=", "$", "this", "->", "db", "->", "select", "(", "'ucms_cart'", ",", "'c'", ")", "->", "condition", "(", "'c.uid'"...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_cart/src/Cart/CartStorage.php#L91-L115
saxulum/saxulum-elasticsearch-querybuilder
src/Converter/IteratableToNodeConverter.php
IteratableToNodeConverter.convert
public function convert($data, string $path = '', bool $allowSerializeEmpty = false): AbstractParentNode { if (!is_array($data) && !$data instanceof \Traversable) { throw new \InvalidArgumentException(sprintf('Params need to be array or %s', \Traversable::class)); } $isArray = $this->isArray($data); $parentNode = $this->getParentNode($isArray, $allowSerializeEmpty); foreach ($data as $key => $value) { $this->addChildNode($parentNode, $key, $value, $path, $isArray, $allowSerializeEmpty); } return $parentNode; }
php
public function convert($data, string $path = '', bool $allowSerializeEmpty = false): AbstractParentNode { if (!is_array($data) && !$data instanceof \Traversable) { throw new \InvalidArgumentException(sprintf('Params need to be array or %s', \Traversable::class)); } $isArray = $this->isArray($data); $parentNode = $this->getParentNode($isArray, $allowSerializeEmpty); foreach ($data as $key => $value) { $this->addChildNode($parentNode, $key, $value, $path, $isArray, $allowSerializeEmpty); } return $parentNode; }
[ "public", "function", "convert", "(", "$", "data", ",", "string", "$", "path", "=", "''", ",", "bool", "$", "allowSerializeEmpty", "=", "false", ")", ":", "AbstractParentNode", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", "&&", "!", "$", "...
@param array|\Traversable $data @param string $path @param bool $allowSerializeEmpty @return AbstractParentNode @throws \InvalidArgumentException
[ "@param", "array|", "\\", "Traversable", "$data", "@param", "string", "$path", "@param", "bool", "$allowSerializeEmpty" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Converter/IteratableToNodeConverter.php#L36-L50
saxulum/saxulum-elasticsearch-querybuilder
src/Converter/IteratableToNodeConverter.php
IteratableToNodeConverter.isArray
private function isArray($data): bool { $counter = 0; foreach ($data as $key => $value) { if ($key !== $counter) { return false; } ++$counter; } return true; }
php
private function isArray($data): bool { $counter = 0; foreach ($data as $key => $value) { if ($key !== $counter) { return false; } ++$counter; } return true; }
[ "private", "function", "isArray", "(", "$", "data", ")", ":", "bool", "{", "$", "counter", "=", "0", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "$", "key", "!==", "$", "counter", ")", "{", "retu...
@param array|\Traversable $data @return bool
[ "@param", "array|", "\\", "Traversable", "$data" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Converter/IteratableToNodeConverter.php#L57-L69
saxulum/saxulum-elasticsearch-querybuilder
src/Converter/IteratableToNodeConverter.php
IteratableToNodeConverter.getParentNode
private function getParentNode(bool $isArray, bool $allowSerializeEmpty): AbstractParentNode { if ($isArray) { return ArrayNode::create($allowSerializeEmpty); } return ObjectNode::create($allowSerializeEmpty); }
php
private function getParentNode(bool $isArray, bool $allowSerializeEmpty): AbstractParentNode { if ($isArray) { return ArrayNode::create($allowSerializeEmpty); } return ObjectNode::create($allowSerializeEmpty); }
[ "private", "function", "getParentNode", "(", "bool", "$", "isArray", ",", "bool", "$", "allowSerializeEmpty", ")", ":", "AbstractParentNode", "{", "if", "(", "$", "isArray", ")", "{", "return", "ArrayNode", "::", "create", "(", "$", "allowSerializeEmpty", ")",...
@param bool $isArray @param bool $allowSerializeEmpty @return AbstractParentNode
[ "@param", "bool", "$isArray", "@param", "bool", "$allowSerializeEmpty" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Converter/IteratableToNodeConverter.php#L77-L84
saxulum/saxulum-elasticsearch-querybuilder
src/Converter/IteratableToNodeConverter.php
IteratableToNodeConverter.getSubPath
private function getSubPath(string $path, $key, bool $isArray): string { $key = (string) $key; if ($isArray) { return $path.'['.$key.']'; } return '' !== $path ? $path.'.'.$key : $key; }
php
private function getSubPath(string $path, $key, bool $isArray): string { $key = (string) $key; if ($isArray) { return $path.'['.$key.']'; } return '' !== $path ? $path.'.'.$key : $key; }
[ "private", "function", "getSubPath", "(", "string", "$", "path", ",", "$", "key", ",", "bool", "$", "isArray", ")", ":", "string", "{", "$", "key", "=", "(", "string", ")", "$", "key", ";", "if", "(", "$", "isArray", ")", "{", "return", "$", "pat...
@param string $path @param string|int $key @param bool $isArray @return string
[ "@param", "string", "$path", "@param", "string|int", "$key", "@param", "bool", "$isArray" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Converter/IteratableToNodeConverter.php#L119-L128
saxulum/saxulum-elasticsearch-querybuilder
src/Converter/IteratableToNodeConverter.php
IteratableToNodeConverter.getNode
private function getNode($value, string $path, bool $allowSerializeEmpty): AbstractNode { if (is_array($value) || $value instanceof \Traversable) { return $this->convert($value, $path, $allowSerializeEmpty); } return $this->scalarToNodeConverter->convert($value, $path, $allowSerializeEmpty); }
php
private function getNode($value, string $path, bool $allowSerializeEmpty): AbstractNode { if (is_array($value) || $value instanceof \Traversable) { return $this->convert($value, $path, $allowSerializeEmpty); } return $this->scalarToNodeConverter->convert($value, $path, $allowSerializeEmpty); }
[ "private", "function", "getNode", "(", "$", "value", ",", "string", "$", "path", ",", "bool", "$", "allowSerializeEmpty", ")", ":", "AbstractNode", "{", "if", "(", "is_array", "(", "$", "value", ")", "||", "$", "value", "instanceof", "\\", "Traversable", ...
@param mixed $value @param string $path @param bool $allowSerializeEmpty @return AbstractNode
[ "@param", "mixed", "$value", "@param", "string", "$path", "@param", "bool", "$allowSerializeEmpty" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Converter/IteratableToNodeConverter.php#L137-L144
ondrs/upload-manager
src/ondrs/UploadManager/Storages/S3Storage.php
S3Storage.buildPattern
private static function buildPattern($masks) { $pattern = array(); $masks = is_array($masks) ? $masks : [$masks]; foreach ($masks as $mask) { $mask = rtrim(strtr($mask, '\\', '/'), '/'); $prefix = ''; if ($mask === '') { continue; } elseif ($mask === '*') { return NULL; } elseif ($mask[0] === '/') { // absolute fixing $mask = ltrim($mask, '/'); $prefix = '(?<=^/)'; } $pattern[] = $prefix . strtr(preg_quote($mask, '#'), array('\*\*' => '.*', '\*' => '[^/]*', '\?' => '[^/]', '\[\!' => '[^', '\[' => '[', '\]' => ']', '\-' => '-')); } return $pattern ? '#/(' . implode('|', $pattern) . ')\z#i' : NULL; }
php
private static function buildPattern($masks) { $pattern = array(); $masks = is_array($masks) ? $masks : [$masks]; foreach ($masks as $mask) { $mask = rtrim(strtr($mask, '\\', '/'), '/'); $prefix = ''; if ($mask === '') { continue; } elseif ($mask === '*') { return NULL; } elseif ($mask[0] === '/') { // absolute fixing $mask = ltrim($mask, '/'); $prefix = '(?<=^/)'; } $pattern[] = $prefix . strtr(preg_quote($mask, '#'), array('\*\*' => '.*', '\*' => '[^/]*', '\?' => '[^/]', '\[\!' => '[^', '\[' => '[', '\]' => ']', '\-' => '-')); } return $pattern ? '#/(' . implode('|', $pattern) . ')\z#i' : NULL; }
[ "private", "static", "function", "buildPattern", "(", "$", "masks", ")", "{", "$", "pattern", "=", "array", "(", ")", ";", "$", "masks", "=", "is_array", "(", "$", "masks", ")", "?", "$", "masks", ":", "[", "$", "masks", "]", ";", "foreach", "(", ...
Converts Finder pattern to regular expression. @param array @return string
[ "Converts", "Finder", "pattern", "to", "regular", "expression", "." ]
train
https://github.com/ondrs/upload-manager/blob/81538fe956b4f173fd9b1d0d371c2f1563b1ea99/src/ondrs/UploadManager/Storages/S3Storage.php#L150-L172
oasmobile/php-aws-wrappers
src/Logging/AwsSnsHandler.php
AwsSnsHandler.write
protected function write(array $record) { if (!$this->isBatchHandling) { $this->contentBuffer = $record['formatted']; $this->publishContent(); } else { $this->contentBuffer = $record['formatted'] . $this->contentBuffer; } }
php
protected function write(array $record) { if (!$this->isBatchHandling) { $this->contentBuffer = $record['formatted']; $this->publishContent(); } else { $this->contentBuffer = $record['formatted'] . $this->contentBuffer; } }
[ "protected", "function", "write", "(", "array", "$", "record", ")", "{", "if", "(", "!", "$", "this", "->", "isBatchHandling", ")", "{", "$", "this", "->", "contentBuffer", "=", "$", "record", "[", "'formatted'", "]", ";", "$", "this", "->", "publishCo...
Writes the record down to the log of the implementing handler @param array $record @return void
[ "Writes", "the", "record", "down", "to", "the", "log", "of", "the", "implementing", "handler" ]
train
https://github.com/oasmobile/php-aws-wrappers/blob/0f756dc60ef6f51e9a99f67c9125289e40f19e3f/src/Logging/AwsSnsHandler.php#L92-L101
qloog/yaf-library
src/Upload/Upload.php
Upload.upload
public function upload($files = '') { if ('' === $files) { $files = $_FILES; } if (empty($files)) { $this->error = '没有上传的文件!'; return false; } /* 检测上传根目录 */ if (!$this->uploader->checkRootPath($this->rootPath)) { $this->error = $this->uploader->getError(); return false; } /* 检查上传目录 */ if (!$this->uploader->checkSavePath($this->savePath)) { $this->error = $this->uploader->getError(); return false; } /* 逐个检测并上传文件 */ $info = []; if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); } // 对上传文件数组信息处理 $files = $this->dealFiles($files); foreach ($files as $key => $file) { $file['name'] = strip_tags($file['name']); if (!isset($file['key'])) { $file['key'] = $key; } /* 通过扩展获取文件类型,可解决FLASH上传$FILES数组返回文件类型错误的问题 */ if (isset($finfo)) { $file['type'] = finfo_file($finfo, $file['tmp_name']); } /* 获取上传文件后缀,允许上传无后缀文件 */ $file['ext'] = pathinfo($file['name'], PATHINFO_EXTENSION); /* 文件上传检测 */ if (!$this->check($file)) { continue; } /* 获取文件hash */ if ($this->hash) { $file['md5'] = md5_file($file['tmp_name']); $file['sha1'] = sha1_file($file['tmp_name']); } /* 调用回调函数检测文件是否存在 */ if ($this->callback) { $data = call_user_func($this->callback, $file); } if ($this->callback && $data) { if (file_exists('.' . $data['path'])) { $info[$key] = $data; continue; } elseif ($this->removeTrash) { call_user_func($this->removeTrash, $data); //删除垃圾据 } } /* 生成保存文件名 */ $savename = $this->getSaveName($file); if (false == $savename) { continue; } else { $file['savename'] = $savename; } /* 检测并创建子目录 */ $subpath = $this->getSubPath($file['name']); if (false === $subpath) { continue; } else { $file['savepath'] = $this->savePath . $subpath; } /* 对图像文件进行严格检测 */ $ext = strtolower($file['ext']); if (in_array($ext, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) { $imginfo = getimagesize($file['tmp_name']); if (empty($imginfo) || ('gif' == $ext && empty($imginfo['bits']))) { $this->error = '非法图像文件!'; continue; } } /* 保存文件 并记录保存成功的文件 */ if ($this->uploader->save($file, $this->replace)) { unset($file['error'], $file['tmp_name']); $info[$key] = $file; } else { $this->error = $this->uploader->getError(); } } if (isset($finfo)) { finfo_close($finfo); } return empty($info) ? false : $info; }
php
public function upload($files = '') { if ('' === $files) { $files = $_FILES; } if (empty($files)) { $this->error = '没有上传的文件!'; return false; } /* 检测上传根目录 */ if (!$this->uploader->checkRootPath($this->rootPath)) { $this->error = $this->uploader->getError(); return false; } /* 检查上传目录 */ if (!$this->uploader->checkSavePath($this->savePath)) { $this->error = $this->uploader->getError(); return false; } /* 逐个检测并上传文件 */ $info = []; if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); } // 对上传文件数组信息处理 $files = $this->dealFiles($files); foreach ($files as $key => $file) { $file['name'] = strip_tags($file['name']); if (!isset($file['key'])) { $file['key'] = $key; } /* 通过扩展获取文件类型,可解决FLASH上传$FILES数组返回文件类型错误的问题 */ if (isset($finfo)) { $file['type'] = finfo_file($finfo, $file['tmp_name']); } /* 获取上传文件后缀,允许上传无后缀文件 */ $file['ext'] = pathinfo($file['name'], PATHINFO_EXTENSION); /* 文件上传检测 */ if (!$this->check($file)) { continue; } /* 获取文件hash */ if ($this->hash) { $file['md5'] = md5_file($file['tmp_name']); $file['sha1'] = sha1_file($file['tmp_name']); } /* 调用回调函数检测文件是否存在 */ if ($this->callback) { $data = call_user_func($this->callback, $file); } if ($this->callback && $data) { if (file_exists('.' . $data['path'])) { $info[$key] = $data; continue; } elseif ($this->removeTrash) { call_user_func($this->removeTrash, $data); //删除垃圾据 } } /* 生成保存文件名 */ $savename = $this->getSaveName($file); if (false == $savename) { continue; } else { $file['savename'] = $savename; } /* 检测并创建子目录 */ $subpath = $this->getSubPath($file['name']); if (false === $subpath) { continue; } else { $file['savepath'] = $this->savePath . $subpath; } /* 对图像文件进行严格检测 */ $ext = strtolower($file['ext']); if (in_array($ext, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) { $imginfo = getimagesize($file['tmp_name']); if (empty($imginfo) || ('gif' == $ext && empty($imginfo['bits']))) { $this->error = '非法图像文件!'; continue; } } /* 保存文件 并记录保存成功的文件 */ if ($this->uploader->save($file, $this->replace)) { unset($file['error'], $file['tmp_name']); $info[$key] = $file; } else { $this->error = $this->uploader->getError(); } } if (isset($finfo)) { finfo_close($finfo); } return empty($info) ? false : $info; }
[ "public", "function", "upload", "(", "$", "files", "=", "''", ")", "{", "if", "(", "''", "===", "$", "files", ")", "{", "$", "files", "=", "$", "_FILES", ";", "}", "if", "(", "empty", "(", "$", "files", ")", ")", "{", "$", "this", "->", "erro...
上传文件 @param string $files ,通常是 $_FILES数组 @return array|bool
[ "上传文件" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L121-L218
qloog/yaf-library
src/Upload/Upload.php
Upload.dealFiles
private function dealFiles($files) { $fileArray = []; $n = 0; foreach ($files as $key => $file) { if (is_array($file['name'])) { $keys = array_keys($file); $count = count($file['name']); for ($i = 0; $i < $count; $i++) { $fileArray[$n]['key'] = $key; foreach ($keys as $_key) { $fileArray[$n][$_key] = $file[$_key][$i]; } $n++; } } else { $fileArray = $files; break; } } return $fileArray; }
php
private function dealFiles($files) { $fileArray = []; $n = 0; foreach ($files as $key => $file) { if (is_array($file['name'])) { $keys = array_keys($file); $count = count($file['name']); for ($i = 0; $i < $count; $i++) { $fileArray[$n]['key'] = $key; foreach ($keys as $_key) { $fileArray[$n][$_key] = $file[$_key][$i]; } $n++; } } else { $fileArray = $files; break; } } return $fileArray; }
[ "private", "function", "dealFiles", "(", "$", "files", ")", "{", "$", "fileArray", "=", "[", "]", ";", "$", "n", "=", "0", ";", "foreach", "(", "$", "files", "as", "$", "key", "=>", "$", "file", ")", "{", "if", "(", "is_array", "(", "$", "file"...
转换上传文件数组变量为正确的方式 @access private @param array $files 上传的文件变量 @return array
[ "转换上传文件数组变量为正确的方式" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L226-L248
qloog/yaf-library
src/Upload/Upload.php
Upload.setDriver
private function setDriver($driver = null, $config = null) { $driver = $driver ?: ($this->driver ?: 'Local'); $config = $config ?: ($this->driverConfig ?: 'Local'); $class = strpos($driver, '\\') ? $driver : 'PHPCasts\\Uploads\\Driver\\' . ucfirst(strtolower($driver)); $this->uploader = new $class($config); if (!$this->uploader) { throw new ConfigException('upload driver not exist!'); } }
php
private function setDriver($driver = null, $config = null) { $driver = $driver ?: ($this->driver ?: 'Local'); $config = $config ?: ($this->driverConfig ?: 'Local'); $class = strpos($driver, '\\') ? $driver : 'PHPCasts\\Uploads\\Driver\\' . ucfirst(strtolower($driver)); $this->uploader = new $class($config); if (!$this->uploader) { throw new ConfigException('upload driver not exist!'); } }
[ "private", "function", "setDriver", "(", "$", "driver", "=", "null", ",", "$", "config", "=", "null", ")", "{", "$", "driver", "=", "$", "driver", "?", ":", "(", "$", "this", "->", "driver", "?", ":", "'Local'", ")", ";", "$", "config", "=", "$",...
设置上传驱动 @param string $driver 驱动名称 @param array $config 驱动配置 @throws ConfigException
[ "设置上传驱动" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L256-L265
qloog/yaf-library
src/Upload/Upload.php
Upload.check
private function check($file) { /* 文件上传失败,捕获错误代码 */ if ($file['error']) { $this->error($file['error']); return false; } /* 无效上传 */ if (empty($file['name'])) { $this->error = '未知上传错误!'; } /* 检查是否合法上传 */ if (!is_uploaded_file($file['tmp_name'])) { $this->error = '非法上传文件!'; return false; } /* 检查文件大小 */ if (!$this->checkSize($file['size'])) { $this->error = '上传文件大小不符!'; return false; } /* 检查文件Mime类型 */ //TODO:FLASH上传的文件获取到的mime类型都为application/octet-stream if (!$this->checkMime($file['type'])) { $this->error = '上传文件MIME类型不允许!'; return false; } /* 检查文件后缀 */ if (!$this->checkExt($file['ext'])) { $this->error = '上传文件后缀不允许'; return false; } /* 通过检测 */ return true; }
php
private function check($file) { /* 文件上传失败,捕获错误代码 */ if ($file['error']) { $this->error($file['error']); return false; } /* 无效上传 */ if (empty($file['name'])) { $this->error = '未知上传错误!'; } /* 检查是否合法上传 */ if (!is_uploaded_file($file['tmp_name'])) { $this->error = '非法上传文件!'; return false; } /* 检查文件大小 */ if (!$this->checkSize($file['size'])) { $this->error = '上传文件大小不符!'; return false; } /* 检查文件Mime类型 */ //TODO:FLASH上传的文件获取到的mime类型都为application/octet-stream if (!$this->checkMime($file['type'])) { $this->error = '上传文件MIME类型不允许!'; return false; } /* 检查文件后缀 */ if (!$this->checkExt($file['ext'])) { $this->error = '上传文件后缀不允许'; return false; } /* 通过检测 */ return true; }
[ "private", "function", "check", "(", "$", "file", ")", "{", "/* 文件上传失败,捕获错误代码 */", "if", "(", "$", "file", "[", "'error'", "]", ")", "{", "$", "this", "->", "error", "(", "$", "file", "[", "'error'", "]", ")", ";", "return", "false", ";", "}", "/* ...
检查上传的文件 @param array $file 文件信息 @return bool
[ "检查上传的文件" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L272-L313
qloog/yaf-library
src/Upload/Upload.php
Upload.checkMime
private function checkMime($mime) { return empty($this->config['mimes']) ? true : in_array(strtolower($mime), $this->mimes); }
php
private function checkMime($mime) { return empty($this->config['mimes']) ? true : in_array(strtolower($mime), $this->mimes); }
[ "private", "function", "checkMime", "(", "$", "mime", ")", "{", "return", "empty", "(", "$", "this", "->", "config", "[", "'mimes'", "]", ")", "?", "true", ":", "in_array", "(", "strtolower", "(", "$", "mime", ")", ",", "$", "this", "->", "mimes", ...
检查上传的文件MIME类型是否合法 @param string $mime 数据 @return bool
[ "检查上传的文件MIME类型是否合法" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L360-L363
qloog/yaf-library
src/Upload/Upload.php
Upload.checkExt
private function checkExt($ext) { return empty($this->config['exts']) ? true : in_array(strtolower($ext), $this->exts); }
php
private function checkExt($ext) { return empty($this->config['exts']) ? true : in_array(strtolower($ext), $this->exts); }
[ "private", "function", "checkExt", "(", "$", "ext", ")", "{", "return", "empty", "(", "$", "this", "->", "config", "[", "'exts'", "]", ")", "?", "true", ":", "in_array", "(", "strtolower", "(", "$", "ext", ")", ",", "$", "this", "->", "exts", ")", ...
检查上传的文件后缀是否合法 @param string $ext 后缀 @return bool
[ "检查上传的文件后缀是否合法" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L370-L373
qloog/yaf-library
src/Upload/Upload.php
Upload.getSaveName
private function getSaveName($file) { $rule = $this->saveName; if (empty($rule)) { //保持文件名不变 /* 解决pathinfo中文文件名BUG */ $filename = substr(pathinfo("_{$file['name']}", PATHINFO_FILENAME), 1); $savename = $filename; } else { $savename = $this->getName($rule, $file['name']); if (empty($savename)) { $this->error = '文件命名规则错误!'; return false; } } /* 文件保存后缀,支持强制更改文件后缀 */ $ext = empty($this->config['saveExt']) ? $file['ext'] : $this->saveExt; return $savename . '.' . $ext; }
php
private function getSaveName($file) { $rule = $this->saveName; if (empty($rule)) { //保持文件名不变 /* 解决pathinfo中文文件名BUG */ $filename = substr(pathinfo("_{$file['name']}", PATHINFO_FILENAME), 1); $savename = $filename; } else { $savename = $this->getName($rule, $file['name']); if (empty($savename)) { $this->error = '文件命名规则错误!'; return false; } } /* 文件保存后缀,支持强制更改文件后缀 */ $ext = empty($this->config['saveExt']) ? $file['ext'] : $this->saveExt; return $savename . '.' . $ext; }
[ "private", "function", "getSaveName", "(", "$", "file", ")", "{", "$", "rule", "=", "$", "this", "->", "saveName", ";", "if", "(", "empty", "(", "$", "rule", ")", ")", "{", "//保持文件名不变", "/* 解决pathinfo中文文件名BUG */", "$", "filename", "=", "substr", "(", "...
根据上传文件命名规则取得保存文件名 @param string $file 文件信息 @return bool|string
[ "根据上传文件命名规则取得保存文件名" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L380-L400
qloog/yaf-library
src/Upload/Upload.php
Upload.getSubPath
private function getSubPath($filename) { $subpath = ''; $rule = $this->subName; if ($this->autoSub && !empty($rule)) { $subpath = $this->getName($rule, $filename) . '/'; if (!empty($subpath) && !$this->uploader->mkdir($this->savePath . $subpath)) { $this->error = $this->uploader->getError(); return false; } } return $subpath; }
php
private function getSubPath($filename) { $subpath = ''; $rule = $this->subName; if ($this->autoSub && !empty($rule)) { $subpath = $this->getName($rule, $filename) . '/'; if (!empty($subpath) && !$this->uploader->mkdir($this->savePath . $subpath)) { $this->error = $this->uploader->getError(); return false; } } return $subpath; }
[ "private", "function", "getSubPath", "(", "$", "filename", ")", "{", "$", "subpath", "=", "''", ";", "$", "rule", "=", "$", "this", "->", "subName", ";", "if", "(", "$", "this", "->", "autoSub", "&&", "!", "empty", "(", "$", "rule", ")", ")", "{"...
获取子目录的名称 @param array $file 上传的文件信息 @return bool|string
[ "获取子目录的名称" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L407-L421
qloog/yaf-library
src/Upload/Upload.php
Upload.getName
private function getName($rule, $filename) { $name = ''; if (is_array($rule)) { //数组规则 $func = $rule[0]; $param = (array)$rule[1]; foreach ($param as &$value) { $value = str_replace('__FILE__', $filename, $value); } $name = call_user_func_array($func, $param); } elseif (is_string($rule)) { //字符串规则 if (function_exists($rule)) { $name = call_user_func($rule); } else { $name = $rule; } } return $name; }
php
private function getName($rule, $filename) { $name = ''; if (is_array($rule)) { //数组规则 $func = $rule[0]; $param = (array)$rule[1]; foreach ($param as &$value) { $value = str_replace('__FILE__', $filename, $value); } $name = call_user_func_array($func, $param); } elseif (is_string($rule)) { //字符串规则 if (function_exists($rule)) { $name = call_user_func($rule); } else { $name = $rule; } } return $name; }
[ "private", "function", "getName", "(", "$", "rule", ",", "$", "filename", ")", "{", "$", "name", "=", "''", ";", "if", "(", "is_array", "(", "$", "rule", ")", ")", "{", "//数组规则", "$", "func", "=", "$", "rule", "[", "0", "]", ";", "$", "param", ...
根据指定的规则获取文件或目录名称 @param array $rule 规则 @param string $filename 原文件名 @return string 文件或目录名称
[ "根据指定的规则获取文件或目录名称" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Upload/Upload.php#L429-L450
amphp/loop
lib/Loop.php
Loop.run
public function run() { $previous = $this->running; ++$this->running; try { while ($this->running > $previous) { if ($this->isEmpty()) { return; } $this->tick(); } } finally { $this->running = $previous; } }
php
public function run() { $previous = $this->running; ++$this->running; try { while ($this->running > $previous) { if ($this->isEmpty()) { return; } $this->tick(); } } finally { $this->running = $previous; } }
[ "public", "function", "run", "(", ")", "{", "$", "previous", "=", "$", "this", "->", "running", ";", "++", "$", "this", "->", "running", ";", "try", "{", "while", "(", "$", "this", "->", "running", ">", "$", "previous", ")", "{", "if", "(", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L38-L52
amphp/loop
lib/Loop.php
Loop.tick
private function tick() { $this->deferQueue = \array_merge($this->deferQueue, $this->nextTickQueue); $this->nextTickQueue = []; $this->activate($this->enableQueue); $this->enableQueue = []; try { foreach ($this->deferQueue as $watcher) { if (!isset($this->deferQueue[$watcher->id])) { continue; // Watcher disabled by another defer watcher. } unset($this->watchers[$watcher->id], $this->deferQueue[$watcher->id]); $callback = $watcher->callback; $callback($watcher->id, $watcher->data); } $this->dispatch(empty($this->nextTickQueue) && empty($this->enableQueue) && $this->running); } catch (\Throwable $exception) { if (null === $this->errorHandler) { throw $exception; } $errorHandler = $this->errorHandler; $errorHandler($exception); } catch (\Exception $exception) { // @todo Remove when PHP 5.x support is no longer needed. if (null === $this->errorHandler) { throw $exception; } $errorHandler = $this->errorHandler; $errorHandler($exception); } }
php
private function tick() { $this->deferQueue = \array_merge($this->deferQueue, $this->nextTickQueue); $this->nextTickQueue = []; $this->activate($this->enableQueue); $this->enableQueue = []; try { foreach ($this->deferQueue as $watcher) { if (!isset($this->deferQueue[$watcher->id])) { continue; // Watcher disabled by another defer watcher. } unset($this->watchers[$watcher->id], $this->deferQueue[$watcher->id]); $callback = $watcher->callback; $callback($watcher->id, $watcher->data); } $this->dispatch(empty($this->nextTickQueue) && empty($this->enableQueue) && $this->running); } catch (\Throwable $exception) { if (null === $this->errorHandler) { throw $exception; } $errorHandler = $this->errorHandler; $errorHandler($exception); } catch (\Exception $exception) { // @todo Remove when PHP 5.x support is no longer needed. if (null === $this->errorHandler) { throw $exception; } $errorHandler = $this->errorHandler; $errorHandler($exception); } }
[ "private", "function", "tick", "(", ")", "{", "$", "this", "->", "deferQueue", "=", "\\", "array_merge", "(", "$", "this", "->", "deferQueue", ",", "$", "this", "->", "nextTickQueue", ")", ";", "$", "this", "->", "nextTickQueue", "=", "[", "]", ";", ...
Executes a single tick of the event loop.
[ "Executes", "a", "single", "tick", "of", "the", "event", "loop", "." ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L77-L113
amphp/loop
lib/Loop.php
Loop.repeat
public function repeat($interval, callable $callback, $data = null) { $interval = (int) $interval; if ($interval < 0) { throw new \InvalidArgumentException("Interval must be greater than or equal to zero"); } $watcher = new Watcher; $watcher->type = Watcher::REPEAT; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $interval; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
php
public function repeat($interval, callable $callback, $data = null) { $interval = (int) $interval; if ($interval < 0) { throw new \InvalidArgumentException("Interval must be greater than or equal to zero"); } $watcher = new Watcher; $watcher->type = Watcher::REPEAT; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $interval; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
[ "public", "function", "repeat", "(", "$", "interval", ",", "callable", "$", "callback", ",", "$", "data", "=", "null", ")", "{", "$", "interval", "=", "(", "int", ")", "$", "interval", ";", "if", "(", "$", "interval", "<", "0", ")", "{", "throw", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L178-L196
amphp/loop
lib/Loop.php
Loop.onReadable
public function onReadable($stream, callable $callback, $data = null) { $watcher = new Watcher; $watcher->type = Watcher::READABLE; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $stream; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
php
public function onReadable($stream, callable $callback, $data = null) { $watcher = new Watcher; $watcher->type = Watcher::READABLE; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $stream; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
[ "public", "function", "onReadable", "(", "$", "stream", ",", "callable", "$", "callback", ",", "$", "data", "=", "null", ")", "{", "$", "watcher", "=", "new", "Watcher", ";", "$", "watcher", "->", "type", "=", "Watcher", "::", "READABLE", ";", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L201-L213
amphp/loop
lib/Loop.php
Loop.onWritable
public function onWritable($stream, callable $callback, $data = null) { $watcher = new Watcher; $watcher->type = Watcher::WRITABLE; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $stream; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
php
public function onWritable($stream, callable $callback, $data = null) { $watcher = new Watcher; $watcher->type = Watcher::WRITABLE; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $stream; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
[ "public", "function", "onWritable", "(", "$", "stream", ",", "callable", "$", "callback", ",", "$", "data", "=", "null", ")", "{", "$", "watcher", "=", "new", "Watcher", ";", "$", "watcher", "->", "type", "=", "Watcher", "::", "WRITABLE", ";", "$", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L218-L230
amphp/loop
lib/Loop.php
Loop.onSignal
public function onSignal($signo, callable $callback, $data = null) { $watcher = new Watcher; $watcher->type = Watcher::SIGNAL; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $signo; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
php
public function onSignal($signo, callable $callback, $data = null) { $watcher = new Watcher; $watcher->type = Watcher::SIGNAL; $watcher->id = $this->nextId++; $watcher->callback = $callback; $watcher->value = $signo; $watcher->data = $data; $this->watchers[$watcher->id] = $watcher; $this->enableQueue[$watcher->id] = $watcher; return $watcher->id; }
[ "public", "function", "onSignal", "(", "$", "signo", ",", "callable", "$", "callback", ",", "$", "data", "=", "null", ")", "{", "$", "watcher", "=", "new", "Watcher", ";", "$", "watcher", "->", "type", "=", "Watcher", "::", "SIGNAL", ";", "$", "watch...
{@inheritdoc} @throws \AsyncInterop\Loop\UnsupportedFeatureException If the pcntl extension is not available. @throws \RuntimeException If creating the backend signal handler fails.
[ "{", "@inheritdoc", "}" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L238-L250
amphp/loop
lib/Loop.php
Loop.enable
public function enable($watcherIdentifier) { if (!isset($this->watchers[$watcherIdentifier])) { throw new InvalidWatcherException($watcherIdentifier, "Cannot enable an invalid watcher identifier: '{$watcherIdentifier}'"); } $watcher = $this->watchers[$watcherIdentifier]; if ($watcher->enabled) { return; // Watcher already enabled. } $watcher->enabled = true; switch ($watcher->type) { case Watcher::DEFER: $this->nextTickQueue[$watcher->id] = $watcher; break; default: $this->enableQueue[$watcher->id] = $watcher; break; } }
php
public function enable($watcherIdentifier) { if (!isset($this->watchers[$watcherIdentifier])) { throw new InvalidWatcherException($watcherIdentifier, "Cannot enable an invalid watcher identifier: '{$watcherIdentifier}'"); } $watcher = $this->watchers[$watcherIdentifier]; if ($watcher->enabled) { return; // Watcher already enabled. } $watcher->enabled = true; switch ($watcher->type) { case Watcher::DEFER: $this->nextTickQueue[$watcher->id] = $watcher; break; default: $this->enableQueue[$watcher->id] = $watcher; break; } }
[ "public", "function", "enable", "(", "$", "watcherIdentifier", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "watchers", "[", "$", "watcherIdentifier", "]", ")", ")", "{", "throw", "new", "InvalidWatcherException", "(", "$", "watcherIdentifier",...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L255-L277
amphp/loop
lib/Loop.php
Loop.reference
public function reference($watcherIdentifier) { if (!isset($this->watchers[$watcherIdentifier])) { throw new InvalidWatcherException($watcherIdentifier, "Cannot reference an invalid watcher identifier: '{$watcherIdentifier}'"); } $this->watchers[$watcherIdentifier]->referenced = true; }
php
public function reference($watcherIdentifier) { if (!isset($this->watchers[$watcherIdentifier])) { throw new InvalidWatcherException($watcherIdentifier, "Cannot reference an invalid watcher identifier: '{$watcherIdentifier}'"); } $this->watchers[$watcherIdentifier]->referenced = true; }
[ "public", "function", "reference", "(", "$", "watcherIdentifier", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "watchers", "[", "$", "watcherIdentifier", "]", ")", ")", "{", "throw", "new", "InvalidWatcherException", "(", "$", "watcherIdentifie...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L328-L334
amphp/loop
lib/Loop.php
Loop.unreference
public function unreference($watcherIdentifier) { if (!isset($this->watchers[$watcherIdentifier])) { throw new InvalidWatcherException($watcherIdentifier, "Cannot unreference an invalid watcher identifier: '{$watcherIdentifier}'"); } $this->watchers[$watcherIdentifier]->referenced = false; }
php
public function unreference($watcherIdentifier) { if (!isset($this->watchers[$watcherIdentifier])) { throw new InvalidWatcherException($watcherIdentifier, "Cannot unreference an invalid watcher identifier: '{$watcherIdentifier}'"); } $this->watchers[$watcherIdentifier]->referenced = false; }
[ "public", "function", "unreference", "(", "$", "watcherIdentifier", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "watchers", "[", "$", "watcherIdentifier", "]", ")", ")", "{", "throw", "new", "InvalidWatcherException", "(", "$", "watcherIdentif...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/Loop.php#L339-L345
stephweb/daw-php-orm
src/DawPhpOrm/Database/Collection.php
Collection.setPropertiesAndAddCollectionToItems
private function setPropertiesAndAddCollectionToItems() { foreach ($this->sqlQuery as $ligneQuery) { $object = new $this->model; foreach ($ligneQuery as $property => $value) { if (property_exists($this->model, $property)) { $object->$property = $value; } } $this->items[] = $object; } }
php
private function setPropertiesAndAddCollectionToItems() { foreach ($this->sqlQuery as $ligneQuery) { $object = new $this->model; foreach ($ligneQuery as $property => $value) { if (property_exists($this->model, $property)) { $object->$property = $value; } } $this->items[] = $object; } }
[ "private", "function", "setPropertiesAndAddCollectionToItems", "(", ")", "{", "foreach", "(", "$", "this", "->", "sqlQuery", "as", "$", "ligneQuery", ")", "{", "$", "object", "=", "new", "$", "this", "->", "model", ";", "foreach", "(", "$", "ligneQuery", "...
Pour hydrater des objets à partir d'une requete SQL qui récupère plusieurs lignes
[ "Pour", "hydrater", "des", "objets", "à", "partir", "d", "une", "requete", "SQL", "qui", "récupère", "plusieurs", "lignes" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/Collection.php#L56-L69
makinacorpus/drupal-ucms
ucms_layout/src/Form/LayoutContextEditForm.php
LayoutContextEditForm.buildForm
public function buildForm(array $form, FormStateInterface $form_state) { $pageLayout = $this->manager->getPageContext()->getCurrentLayout(); $siteLayout = $this->manager->getSiteContext()->getCurrentLayout(); if ($pageLayout instanceof Layout || $siteLayout instanceof Layout) { $form['actions']['#type'] = 'actions'; if ($this->manager->getPageContext()->isTemporary()) { $form['actions']['save_page'] = [ '#type' => 'submit', '#value' => $this->t("Save composition"), '#submit' => ['::saveSubmit'] ]; $form['actions']['cancel_page'] = [ '#type' => 'submit', '#value' => $this->t("Cancel"), '#submit' => ['::cancelSubmit'] ]; } elseif ($this->manager->getSiteContext()->isTemporary()) { $form['actions']['save_site'] = [ '#type' => 'submit', '#value' => $this->t("Save transversal composition"), '#submit' => ['::saveTransversalSubmit'] ]; $form['actions']['cancel_site'] = [ '#type' => 'submit', '#value' => $this->t("Cancel"), '#submit' => ['::cancelTransversalSubmit'] ]; } else { $form['actions']['edit_page'] = [ '#type' => 'submit', '#value' => $this->t("Edit composition"), '#submit' => ['::editSubmit'] ]; $form['actions']['edit_site'] = [ '#type' => 'submit', '#value' => $this->t("Edit transversal composition"), '#submit' => ['::editTransversalSubmit'] ]; } } return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state) { $pageLayout = $this->manager->getPageContext()->getCurrentLayout(); $siteLayout = $this->manager->getSiteContext()->getCurrentLayout(); if ($pageLayout instanceof Layout || $siteLayout instanceof Layout) { $form['actions']['#type'] = 'actions'; if ($this->manager->getPageContext()->isTemporary()) { $form['actions']['save_page'] = [ '#type' => 'submit', '#value' => $this->t("Save composition"), '#submit' => ['::saveSubmit'] ]; $form['actions']['cancel_page'] = [ '#type' => 'submit', '#value' => $this->t("Cancel"), '#submit' => ['::cancelSubmit'] ]; } elseif ($this->manager->getSiteContext()->isTemporary()) { $form['actions']['save_site'] = [ '#type' => 'submit', '#value' => $this->t("Save transversal composition"), '#submit' => ['::saveTransversalSubmit'] ]; $form['actions']['cancel_site'] = [ '#type' => 'submit', '#value' => $this->t("Cancel"), '#submit' => ['::cancelTransversalSubmit'] ]; } else { $form['actions']['edit_page'] = [ '#type' => 'submit', '#value' => $this->t("Edit composition"), '#submit' => ['::editSubmit'] ]; $form['actions']['edit_site'] = [ '#type' => 'submit', '#value' => $this->t("Edit transversal composition"), '#submit' => ['::editTransversalSubmit'] ]; } } return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "pageLayout", "=", "$", "this", "->", "manager", "->", "getPageContext", "(", ")", "->", "getCurrentLayout", "(", ")", ";", "$", "sit...
{inheritdoc}
[ "{", "inheritdoc", "}" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Form/LayoutContextEditForm.php#L50-L97
makinacorpus/drupal-ucms
ucms_layout/src/Form/LayoutContextEditForm.php
LayoutContextEditForm.saveSubmit
public function saveSubmit(array &$form, FormStateInterface $form_state) { if ($this->manager->getPageContext()->isTemporary()) { $this->manager->getPageContext()->commit(); drupal_set_message($this->t("Changed have been saved")); $form_state->setRedirect( current_path(), ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_PAGE_TOKEN])] ); } }
php
public function saveSubmit(array &$form, FormStateInterface $form_state) { if ($this->manager->getPageContext()->isTemporary()) { $this->manager->getPageContext()->commit(); drupal_set_message($this->t("Changed have been saved")); $form_state->setRedirect( current_path(), ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_PAGE_TOKEN])] ); } }
[ "public", "function", "saveSubmit", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "if", "(", "$", "this", "->", "manager", "->", "getPageContext", "(", ")", "->", "isTemporary", "(", ")", ")", "{", "$", "this", ...
Save form submit
[ "Save", "form", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Form/LayoutContextEditForm.php#L102-L114
makinacorpus/drupal-ucms
ucms_layout/src/Form/LayoutContextEditForm.php
LayoutContextEditForm.cancelSubmit
public function cancelSubmit(array &$form, FormStateInterface $form_state) { if ($this->manager->getPageContext()->isTemporary()) { $this->manager->getPageContext()->rollback(); drupal_set_message($this->t("Changes have been dropped"), 'error'); $form_state->setRedirect( current_path(), ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_PAGE_TOKEN])] ); } }
php
public function cancelSubmit(array &$form, FormStateInterface $form_state) { if ($this->manager->getPageContext()->isTemporary()) { $this->manager->getPageContext()->rollback(); drupal_set_message($this->t("Changes have been dropped"), 'error'); $form_state->setRedirect( current_path(), ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_PAGE_TOKEN])] ); } }
[ "public", "function", "cancelSubmit", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "if", "(", "$", "this", "->", "manager", "->", "getPageContext", "(", ")", "->", "isTemporary", "(", ")", ")", "{", "$", "this",...
Cancel form submit
[ "Cancel", "form", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Form/LayoutContextEditForm.php#L119-L131
makinacorpus/drupal-ucms
ucms_layout/src/Form/LayoutContextEditForm.php
LayoutContextEditForm.editSubmit
public function editSubmit(array &$form, FormStateInterface $form_state) { if (!$this->manager->getPageContext()->isTemporary()) { // @todo Generate a better token (random). $token = drupal_get_token(); $layout = $this->manager->getPageContext()->getCurrentLayout(); $this->manager->getPageContext()->setToken($token); // Saving the layout will force it be saved in the temporary storage. $this->manager->getPageContext()->getStorage()->save($layout); $form_state->setRedirect( current_path(), ['query' => [ContextManager::PARAM_PAGE_TOKEN => $token] + drupal_get_query_parameters()] ); } }
php
public function editSubmit(array &$form, FormStateInterface $form_state) { if (!$this->manager->getPageContext()->isTemporary()) { // @todo Generate a better token (random). $token = drupal_get_token(); $layout = $this->manager->getPageContext()->getCurrentLayout(); $this->manager->getPageContext()->setToken($token); // Saving the layout will force it be saved in the temporary storage. $this->manager->getPageContext()->getStorage()->save($layout); $form_state->setRedirect( current_path(), ['query' => [ContextManager::PARAM_PAGE_TOKEN => $token] + drupal_get_query_parameters()] ); } }
[ "public", "function", "editSubmit", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "if", "(", "!", "$", "this", "->", "manager", "->", "getPageContext", "(", ")", "->", "isTemporary", "(", ")", ")", "{", "// @todo...
Edit form submit
[ "Edit", "form", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Form/LayoutContextEditForm.php#L136-L153
makinacorpus/drupal-ucms
ucms_layout/src/Form/LayoutContextEditForm.php
LayoutContextEditForm.saveTransversalSubmit
public function saveTransversalSubmit(array &$form, FormStateInterface $form_state) { if ($this->manager->getSiteContext()->isTemporary()) { $this->manager->getSiteContext()->commit(); drupal_set_message(t("Changed have been saved")); $form_state->setRedirect( current_path(), ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_SITE_TOKEN])] ); } }
php
public function saveTransversalSubmit(array &$form, FormStateInterface $form_state) { if ($this->manager->getSiteContext()->isTemporary()) { $this->manager->getSiteContext()->commit(); drupal_set_message(t("Changed have been saved")); $form_state->setRedirect( current_path(), ['query' => drupal_get_query_parameters(null, ['q', ContextManager::PARAM_SITE_TOKEN])] ); } }
[ "public", "function", "saveTransversalSubmit", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "if", "(", "$", "this", "->", "manager", "->", "getSiteContext", "(", ")", "->", "isTemporary", "(", ")", ")", "{", "$", ...
Save form submit
[ "Save", "form", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_layout/src/Form/LayoutContextEditForm.php#L158-L170