sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private static function comment_block($text, $char = ' ') { $text = wordwrap($text, self::MAX_LINE_LEN - 3); return self::prepend_each_line($text, "#$char "); }
Prepare a text as a comment -- wraps the lines and prepends # and a special character to each line. @param string $text the comment text @param string $char character to denote a special PO comment, like :, default is a space @return string The modified string
entailment
public static function export_entry(EntryTranslations &$entry) { if (null === $entry->singular || '' === $entry->singular) { return false; } $po = array(); if (!empty($entry->translator_comments)) { $po[] = self::comment_block($entry->translator_comments); } if (!empty($entry->extracted_comments)) { $po[] = self::comment_block($entry->extracted_comments, '.'); } if (!empty($entry->references)) { $po[] = self::comment_block(implode(' ', $entry->references), ':'); } if (!empty($entry->flags)) { $po[] = self::comment_block(implode(', ', $entry->flags), ','); } if (!is_null($entry->context)) { $po[] = 'msgctxt ' . self::poify($entry->context); } $po[] = 'msgid ' . self::poify($entry->singular); if (!$entry->is_plural) { $translation = empty($entry->translations) ? '' : $entry->translations[0]; $translation = self::match_begin_and_end_newlines($translation, $entry->singular); $po[] = 'msgstr ' . self::poify($translation); } else { $po[] = 'msgid_plural ' . self::poify($entry->plural); $translations = empty($entry->translations) ? array('', '') : $entry->translations; foreach ($translations as $i => $translation) { $translation = self::match_begin_and_end_newlines($translation, $entry->plural); $po[] = "msgstr[$i] " . self::poify($translation); } } return implode("\n", $po); }
Builds a string from the entry for inclusion in PO file. @static @param EntryTranslations &$entry the entry to convert to po string @return false|string PO-style formatted string for the entry or false if the entry is empty
entailment
public static function match_begin_and_end_newlines($translation, $original) { if ('' === $translation) { return $translation; } $original_begin = "\n" === substr($original, 0, 1); $original_end = "\n" === substr($original, -1); $translation_begin = "\n" === substr($translation, 0, 1); $translation_end = "\n" === substr($translation, -1); if ($original_begin) { if (!$translation_begin) { $translation = "\n" . $translation; } } elseif ($translation_begin) { $translation = ltrim($translation, "\n"); } if ($original_end) { if (!$translation_end) { $translation .= "\n"; } } elseif ($translation_end) { $translation = rtrim($translation, "\n"); } return $translation; }
@param $translation @param $original @return string
entailment
public function import_from_file($filename) { $f = fopen($filename, 'r'); if (!$f) { return false; } $lineno = 0; $res = false; while (true) { $res = $this->read_entry($f, $lineno); if (!$res) { break; } if ($res['entry']->singular == '') { $this->set_headers( $this->make_headers($res['entry']->translations[0]) ); } else { $this->add_entry($res['entry']); } } self::read_line($f, 'clear'); if (false === $res) { return false; } if (!$this->headers && !$this->entries) { return false; } return true; }
@param string $filename @return bool
entailment
public function read_entry($f, $lineno = 0) { $entry = new EntryTranslations(); // where were we in the last step // can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural $context = ''; $msgstr_index = 0; while (true) { $lineno++; $line = self::read_line($f); if (!$line) { if (feof($f)) { if (self::is_final($context)) { break; } elseif (!$context) { // we haven't read a line and eof came return; } else { return false; } } else { return false; } } if ($line == "\n") { continue; } $line = trim($line); if (preg_match('/^#/', $line, $m)) { // the comment is the start of a new entry if (self::is_final($context)) { self::read_line($f, 'put-back'); $lineno--; break; } // comments have to be at the beginning if ($context && $context != 'comment') { return false; } // add comment $this->add_comment_to_entry($entry, $line); } elseif (preg_match('/^msgctxt\s+(".*")/', $line, $m)) { if (self::is_final($context)) { self::read_line($f, 'put-back'); $lineno--; break; } if ($context && $context != 'comment') { return false; } $context = 'msgctxt'; $entry->context .= self::unpoify($m[1]); } elseif (preg_match('/^msgid\s+(".*")/', $line, $m)) { if (self::is_final($context)) { self::read_line($f, 'put-back'); $lineno--; break; } if ($context && $context != 'msgctxt' && $context != 'comment') { return false; } $context = 'msgid'; $entry->singular .= self::unpoify($m[1]); } elseif (preg_match('/^msgid_plural\s+(".*")/', $line, $m)) { if ($context != 'msgid') { return false; } $context = 'msgid_plural'; $entry->is_plural = true; $entry->plural .= self::unpoify($m[1]); } elseif (preg_match('/^msgstr\s+(".*")/', $line, $m)) { if ($context != 'msgid') { return false; } $context = 'msgstr'; $entry->translations = array(self::unpoify($m[1])); } elseif (preg_match('/^msgstr\[(\d+)\]\s+(".*")/', $line, $m)) { if ($context != 'msgid_plural' && $context != 'msgstr_plural') { return false; } $context = 'msgstr_plural'; $msgstr_index = $m[1]; $entry->translations[$m[1]] = self::unpoify($m[2]); } elseif (preg_match('/^".*"$/', $line)) { $unpoified = self::unpoify($line); switch ($context) { case 'msgid': $entry->singular .= $unpoified; break; case 'msgctxt': $entry->context .= $unpoified; break; case 'msgid_plural': $entry->plural .= $unpoified; break; case 'msgstr': $entry->translations[0] .= $unpoified; break; case 'msgstr_plural': $entry->translations[$msgstr_index] .= $unpoified; break; default: return false; } } else { return false; } } $have_translations = false; foreach ($entry->translations as $t) { if ($t || ('0' === $t)) { $have_translations = true; break; } } if (false === $have_translations) { $entry->translations = array(); } return array('entry' => $entry, 'lineno' => $lineno); }
@param resource $f @param int $lineno @return null|false|array
entailment
public static function read_line($f, $action = 'read') { static $last_line = ''; static $use_last_line = false; if ('clear' == $action) { $last_line = ''; return true; } if ('put-back' == $action) { $use_last_line = true; return true; } $line = $use_last_line ? $last_line : fgets($f); $line = ("\r\n" == substr($line, -2)) ? rtrim($line, "\r\n") . "\n" : $line; $last_line = $line; $use_last_line = false; return $line; }
@param resource $f @param string $action @return bool
entailment
public static function trim_quotes($s) { if (substr($s, 0, 1) == '"') { $s = substr($s, 1); } if (substr($s, -1, 1) == '"') { $s = substr($s, 0, -1); } return $s; }
@param string $s @return string
entailment
public function loginAndRegisterVia($provider) { $this->authenticationService = $this->authenticationServiceFactory->getInstance($provider); $isUserLoggedIn = $this->accountService->checkUser(); // active sw login session if ($isUserLoggedIn) { return $isUserLoggedIn; } if ($this->authenticationService !== null) { // sso login $isAuthenticated = $this->authenticationService->login(); $customer = null; if ($isAuthenticated) { // get user data from sso provider $user = $this->authenticationService->getUser(); if ($user !== null && $user->getEmail() !== '') { // get sw customer $customer = $this->customerService->getCustomerByIdentity($provider, $user->getId()); if ($customer !== null) { // new login $isUserLoggedIn = $this->tryLoginCustomer($customer); } else { $customer = $this->customerService->getCustomerByEmail($user->getEmail()); if ($customer !== null) { // connect $customer = $this->registerService->connectUserWithExistingCustomer($user, $customer); } else { // register $customer = $this->registerService->registerCustomerByUser($user); } $isUserLoggedIn = $this->tryLoginCustomer($customer); } } } else { $isUserLoggedIn = false; } $this->container->get('events')->notify( 'Port1HybridAuth_Service_SingleSignOn_CustomerLoggedIn', [ 'customer' => $customer, 'isUserLoggedIn' => $isUserLoggedIn ] ); } return $isUserLoggedIn; }
the overall method for the SSO workflow login + register @param $provider string the authsource string (e.g.: linkedin, ...) @return bool
entailment
protected function tryLoginCustomer($customer = null) { $result = false; if ($customer !== null) { $checkUser = $this->accountService->loginUser($customer); if (empty($checkUser['sErrorMessages'])) { $result = true; } } else { /** * this could happen because we do not get all the data from the SSO Provider * and cannot create a valid user via RegisterService */ $result = false; } return $result; }
@param Customer $customer @return bool true if the customer is successfully logged in, false if not
entailment
public function setCheckbox(): ColumnInterface { return $this->setKey('checkbox') ->setValue('<input type="checkbox" class="js_adminSelectAll">') ->setSort(false) ->setScreening(true) ->setHandler(function ($data) { if ($data && $data->id) { return '<input type="checkbox" class="js_adminCheckboxRow" value="' . $data->id . '">'; } return ''; }); }
template for checkbox @return $this
entailment
public function getValues(\Illuminate\Database\Eloquent\Model $instance = null) { if ($instance) { $this->setInstance($instance); } if ($this->isHandler()) { return $this->getHandler(); } if ($this->instance) { return $this->getValueColumn($this->instance, $this->key); } return null; }
@param \Illuminate\Database\Eloquent\Model|null $instance @return mixed|null
entailment
public function getValueColumn($instance, string $name) { if (!$instance) { return null; } $parts = explode('.', $name); $part = array_shift($parts); if ($instance instanceof \Illuminate\Database\Eloquent\Collection) { $instance = $instance->pluck($part)->first(); } else { $instance = $instance->{$part}; } if (!empty($parts) && !is_null($instance)) { return $this->getValueColumn($instance, implode('.', $parts)); } if ($instance instanceof \DateTimeInterface) { $instance = $this->getDateActive() ? $instance->format($this->getDateFormat()) : $instance; } return $instance; }
@param mixed $instance @param string $name @return mixed
entailment
public function setInstance(\Illuminate\Database\Eloquent\Model $instance): ColumnInterface { $this->instance = $instance; return $this; }
Необходимо устанавливать только в момент когда приходит инстанс модели! @param \Illuminate\Database\Eloquent\Model $instance @return ColumnInterface
entailment
public function setKeyAction(): ColumnInterface { $this->key = self::ACTION_NAME; $this->setValue(''); $this->setSort(false); $this->setScreening(true); return $this; }
Method for a single column with actions @return ColumnInterface
entailment
public function setFilter( string $field, $data, string $mode = null, array $selected = [], string $class = '', string $style = '', string $placeholder = '', string $url = '' ): ColumnInterface { $mode = $mode ? $mode : self::FILTER_TYPE_SELECT; $this->filter = [ self::FILTER_KEY_NAME => $field, self::FILTER_KEY_DATA => $data, self::FILTER_KEY_MODE => $mode, self::FILTER_KEY_SELECTED => $selected, self::FILTER_KEY_CLASS => $class, self::FILTER_KEY_STYLE => $style, self::FILTER_KEY_PLACEHOLDER => $placeholder, self::FILTER_KEY_WIDTH => '180px', self::FILTER_KEY_FORMAT => 'DD MMM YY', ]; $this->setUrl($url); return $this; }
@param string $field @param string|array $data @param string|null $mode @param array $selected @param string $class @param string $style @param string $placeholder @param string $url @return ColumnInterface
entailment
public function setFilterFormat(string $format = 'DD MMM YY'): ColumnInterface { $this->filter[self::FILTER_KEY_FORMAT] = $format; return $this; }
@param string $width @return ColumnInterface
entailment
public function setFilterWidth(string $width = '180px'): ColumnInterface { $this->filter[self::FILTER_KEY_WIDTH] = $width; return $this; }
@param string $width @return ColumnInterface
entailment
public function setFilterSelect( string $field, array $array, string $class = '', string $style = '', string $placeholder = '' ): ColumnInterface { return $this->setFilter($field, $array, self::FILTER_TYPE_SELECT, [], $class, $style, $placeholder); }
@param string $field @param array $array @param string $class @param string $style @param string $placeholder @return ColumnInterface
entailment
public function setFilterSelectAjax( string $field, array $array, array $selected, string $url, string $class = '', string $style = '', string $placeholder = '' ): ColumnInterface { return $this->setFilter($field, $array, self::FILTER_TYPE_SELECT_AJAX, $selected, $class, $style, $placeholder, $url); }
@param string $field @param array $array @param string $url @param string $class @param string $style @param string $placeholder @return ColumnInterface
entailment
public function setFilterSelectNotAjax( string $field, array $array, array $selected = [], string $url = '', string $class = '', string $style = '', string $placeholder = '' ): ColumnInterface { return $this->setFilter($field, $array, self::FILTER_TYPE_SELECT_NOT_AJAX, $selected, $class, $style, $placeholder, $url); }
@param string $field @param array $array @param string $url @param string $class @param string $style @param string $placeholder @return ColumnInterface
entailment
public function setFilterString( string $field, string $string = '', string $class = '', string $style = '', string $placeholder = '' ): ColumnInterface { return $this->setFilter($field, $string, self::FILTER_TYPE_STRING, [], $class, $style, $placeholder); }
@param string $field @param string $string @param string $class @param string $style @param string $placeholder @return ColumnInterface
entailment
public function setFilterDate( string $field, string $string = '', bool $active = true, string $format = null, string $class = '', string $style = '', string $placeholder = '' ): ColumnInterface { $this->setDateActive($active); if ($format) { $this->setDateFormat($format); } return $this->setFilter($field, $string, self::FILTER_TYPE_DATE, [], $class, $style, $placeholder); }
@param string $field @param string $string @param bool $active @param string|null $format @param string $class @param string $style @param string $placeholder @return ColumnInterface
entailment
public function setFilterDateRange( string $field, string $string = '', bool $active = true, string $format = null, string $class = '', string $style = '', string $placeholder = '' ): ColumnInterface { $this->setDateActive($active); if ($format) { $this->setDateFormat($format); } return $this->setFilter($field, $string, self::FILTER_TYPE_DATE_RANGE, [], $class, $style, $placeholder); }
@param string $field @param string $string @param bool $active @param string|null $format @param string $class @param string $style @param string $placeholder @return ColumnInterface
entailment
public function setActions(Callable $action, string $value = null): ColumnInterface { $this->setKeyAction(); $this->actions = $action; if ($value !== null) { $this->setValue($value); } return $this; }
@param callable $action @param string|null $value @return ColumnInterface
entailment
public function setClassForString(Callable $handler): ColumnInterface { $this->key = self::ACTION_STRING_TR; $this->setHandler($handler); return $this; }
@param callable $handler @return ColumnInterface
entailment
public function gettext_select_plural_form($count) { if (!isset($this->_gettext_select_plural_form) || is_null($this->_gettext_select_plural_form)) { list($nplurals, $expression) = $this->nplurals_and_expression_from_header($this->get_header('Plural-Forms')); $this->_nplurals = $nplurals; $this->_gettext_select_plural_form = $this->make_plural_form_function($nplurals, $expression); } return call_user_func($this->_gettext_select_plural_form, $count); }
The gettext implementation of select_plural_form. It lives in this class, because there are more than one descendand, which will use it and they can't share it effectively. @param int $count Items count @return mixed
entailment
public function nplurals_and_expression_from_header($header) { if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s+plural\s*=\s*(.+)$/', $header, $matches)) { $nplurals = (int) $matches[1]; $expression = trim($matches[2]); return array($nplurals, $expression); } else { return array(2, 'n != 1'); } }
@param $header @return array
entailment
public function make_plural_form_function($nplurals, $expression) { try { $handler = new PluralForms(rtrim($expression, ';')); return array($handler, 'get'); } catch (\Exception $e) { // Fall back to default plural-form function. return $this->make_plural_form_function(2, 'n != 1'); } }
Makes a function, which will return the right translation index, according to the plural forms header. @param int $nplurals @param string $expression @return callable The right translation index
entailment
public function parenthesize_plural_exression($expression) { $expression .= ';'; $res = ''; $depth = 0; for ($i = 0; $i < strlen($expression); ++$i) { $char = $expression[$i]; switch ($char) { case '?': $res .= ' ? ('; $depth++; break; case ':': $res .= ') : ('; break; case ';': $res .= str_repeat(')', $depth) . ';'; $depth = 0; break; default: $res .= $char; } } return rtrim($res, ';'); }
Adds parentheses to the inner parts of ternary operators in plural expressions, because PHP evaluates ternary operators from left to right. @param string $expression the expression without parentheses @return string the expression with parentheses added
entailment
public function make_headers($translation) { $headers = array(); // sometimes \ns are used instead of real new lines $translation = str_replace('\n', "\n", $translation); $lines = explode("\n", $translation); foreach ($lines as $line) { $parts = explode(':', $line, 2); if (!isset($parts[1])) { continue; } $headers[trim($parts[0])] = trim($parts[1]); } return $headers; }
@param string $translation @return array
entailment
public function aroundExecute( CategoryView $subject, \Closure $proceed ) { if (!$subject->getRequest()->isAjax()) { return $proceed(); } try { // Remove query parameters added for AJAX requests $this->cleanRequestUri(); $this->removeAjaxQueryParams(); $page = $proceed(); if (!$page) { throw new \Exception('No page result.'); } if ($this->response->isRedirect()) { throw new \Exception('Unable to process page result, redirect detected.'); } $className = '\Magento\Framework\View\Result\Page'; if (!($page instanceof $className)) { throw new \Exception( sprintf( 'Unable to process page result. Instance of %s expected, instance of %s got.', $className, get_class($page) ) ); } $layout = $page->getLayout(); /** @var $layout \Magento\Framework\View\LayoutInterface */ $block = $layout->getBlock('category.products.list'); if (!$block) { throw new \Exception('Unable to load block content.'); } $pager = $layout->getBlock('product_list_toolbar_pager'); if (!$pager) { throw new \Exception('Unable to load pager block.'); } // Generate page content to initialize toolbar $htmlContent = $layout->renderElement('content'); $response = [ 'success' => true, 'current_page_url' => $this->getCurrentPageUrl($pager), // e.g. "womens.html?p=3" 'previous_page_url' => $this->getPreviousPageUrl($pager), // e.g. "womens.html?p=2" 'next_page_url' => $this->getNextPageUrl($pager), // e.g. "womens.html?p=4" 'html' => [ 'content' => $htmlContent, 'sidebar_main' => $layout->renderElement('sidebar.main') ] ]; } catch (\Exception $e) { $this->logger->critical($e); $response = [ 'success' => false, 'error_message' => 'Sorry, something went wrong. Please try again later.' ]; } return $this->jsonResponse($response); }
Category view action @param CategoryView $subject @param \Closure $proceed @return void|\Magento\Framework\View\Result\Page|\Magento\Framework\Controller\Result\Json
entailment
public static function forType($type, KeyValueStore $store, $code = 0, Exception $cause = null) { return new static(sprintf( 'Values of type %s are not supported by %s.', $type, get_class($store) ), $code, $cause); }
Creates a new exception for the given value type. @param string $type The name of the unsupported type. @param KeyValueStore $store The store that does not support the type. @param int $code The exception code. @param Exception|null $cause The exception that caused this exception. @return static The new exception.
entailment
public static function forValue($value, KeyValueStore $store, $code = 0, Exception $cause = null) { return new static(sprintf( 'Values of type %s are not supported by %s.', gettype($value), get_class($store) ), $code, $cause); }
Creates a new exception for the given value. @param string $value The unsupported value. @param KeyValueStore $store The store that does not support the type. @param int $code The exception code. @param Exception|null $cause The exception that caused this exception. @return static The new exception.
entailment
public function getEnabledProviders() { $result = []; foreach (Port1HybridAuth::PROVIDERS as $provider) { if ((Boolean)$this->config->getByNamespace('Port1HybridAuth', strtolower($provider) . '_enabled')) { $label = $this->snippetManager->getNamespace('frontend/account/login')->get('SignInWith' . $provider); $result[$provider] = $label; } }
Returns all enabled providers @return array
entailment
public function validate(Address $address) { $this->validationContext = $this->validator->startContext(); $this->validateField('firstname', $address->getFirstname(), [new NotBlank()]); $this->validateField('lastname', $address->getLastname(), [new NotBlank()]); if ($this->validationContext->getViolations()->count()) { throw new ValidationException($this->validationContext->getViolations()); } }
@param Address $address @throws ValidationException
entailment
public function setType(string $type = self::TYPE_HIDDEN): InputInterface { $this->type = $type; return $this; }
@param string $type @return InputInterface
entailment
public function setInputHidden( string $name = '', string $value = '', string $id = '', string $class = '', array $options = [] ): InputInterface { $this->setType(self::TYPE_HIDDEN) ->setName($name) ->setValue($value) ->setId($id) ->setClass($class) ->setOptions($options); return $this; }
@param string $name @param string $value @param string $id @param string $class @param array $options @return InputInterface
entailment
public function setQuery(\Illuminate\Database\Eloquent\Builder &$query): PaginationInterface { $this->_query = $query; return $this; }
@param \Illuminate\Database\Eloquent\Builder $query @return PaginationInterface
entailment
public function get(int $page, int $limit = 10): \Illuminate\Pagination\LengthAwarePaginator { if (!$this->_columns && !$this->_query) { return null; } $countTotal = $this->_query->count(); $this->_query->skip(($limit * $page) - $limit); $this->_query->limit($limit); $data = collect(); foreach ($this->_query->get() as $key => $instance) { if ($instance instanceof \Illuminate\Database\Eloquent\Model) { $_listRow = []; foreach ($this->_columns->getColumns() as $column) { $_listRow[$column->getKey()] = $column->getValues($instance); } $buttons = $this->_columns->filterActions($instance); if (count($buttons)) { $_listRow = array_merge($_listRow, [Column::ACTION_NAME => implode('', $buttons)]); } $data->offsetSet($key, $_listRow); } } $this->_data = new \Illuminate\Pagination\LengthAwarePaginator($data, $countTotal, $limit, $page, [ 'path' => \Illuminate\Pagination\Paginator::resolveCurrentPath(), 'pageName' => 'page', ]); return $this->_data; }
Returns a collection in view of pagination @param int $page @param int $limit @return LengthAwarePaginator
entailment
public function getSimple(int $page, int $limit = 10, bool $isClount = false): \Illuminate\Contracts\Pagination\Paginator { if (!$this->_columns && !$this->_query) { return null; } if ($isClount) { $countTotal = $this->_query->count(); } $this->_query->skip(($page - 1) * $page)->take($page + 1); $this->_data = $this->_query->simplePaginate($limit); if ($isClount) { $this->_data->totalCount = $countTotal; } foreach ($this->_data->items() as $key => $instance) { if ($instance instanceof \Illuminate\Database\Eloquent\Model) { $_listRow = []; foreach ($this->_columns->getColumns() as $column) { $_listRow[$column->getKey()] = $column->getValues($instance); if ($column->getKey() === 'preview') { } } $buttons = $this->_columns->filterActions($instance); if (count($buttons)) { $_listRow = array_merge($_listRow, [Column::ACTION_NAME => implode('', $buttons)]); } $this->_data->offsetSet($key, $_listRow); } } return $this->_data; }
Returns a collection in view of pagination @param int $page @param int $limit @return \Illuminate\Contracts\Pagination\Paginator
entailment
public function render(string $view = null, array $data = [], string $formAction = ''): string { if (!$this->_data) { return ''; } return $this->_data->setPath($formAction)->appends($data)->render($view)->toHtml(); }
@param string|null $view @param array $data @param string $formAction @return string
entailment
public function getItemForPagination( string $status = '', string $text = '', string $url = '', string $rel = '', string $page = '' ): array { return [ 'status' => $status, 'text' => $text, 'url' => $url, 'rel' => $rel, 'page' => $page, ]; }
@param string $status @param string $text @param string $url @param string $rel @param string $page @return array
entailment
public function set($key, $value) { $this->store->set($key, $value); $this->cache->save($key, $value, $this->ttl); }
{@inheritdoc}
entailment
public function get($key, $default = null) { if ($this->cache->contains($key)) { return $this->cache->fetch($key); } try { $value = $this->store->getOrFail($key); } catch (NoSuchKeyException $e) { return $default; } $this->cache->save($key, $value, $this->ttl); return $value; }
{@inheritdoc}
entailment
public function getOrFail($key) { if ($this->cache->contains($key)) { return $this->cache->fetch($key); } $value = $this->store->getOrFail($key); $this->cache->save($key, $value, $this->ttl); return $value; }
{@inheritdoc}
entailment
public function getMultiple(array $keys, $default = null) { $values = array(); // Read cached values from the cache foreach ($keys as $i => $key) { if ($this->cache->contains($key)) { $values[$key] = $this->cache->fetch($key); unset($keys[$i]); } } // Don't write cache, as we can't differentiate between existing and // non-existing keys return array_replace($values, $this->store->getMultiple($keys, $default)); }
{@inheritdoc}
entailment
public function getMultipleOrFail(array $keys) { $values = array(); // Read cached values from the cache foreach ($keys as $i => $key) { if ($this->cache->contains($key)) { $values[$key] = $this->cache->fetch($key); unset($keys[$i]); } } $values = array_replace($values, $this->store->getMultipleOrFail($keys)); // Write newly fetched values to the cache foreach ($keys as $key) { $this->cache->save($key, $values[$key], $this->ttl); } return $values; }
{@inheritdoc}
entailment
public function remove($key) { $this->store->remove($key); $this->cache->delete($key); }
{@inheritdoc}
entailment
public function exists($key) { if ($this->cache->contains($key)) { return true; } return $this->store->exists($key); }
{@inheritdoc}
entailment
public function clear() { $this->store->clear(); if ($this->cache instanceof ClearableCache) { $this->cache->deleteAll(); } else { $this->cache->flushAll(); } }
{@inheritdoc}
entailment
protected function getRepository() { if ($this->repository === null) { $this->repository = $this->container->get('models')->getRepository(Customer::class); } return $this->repository; }
Helper function to get access on the static declared repository @return \Shopware\Models\Customer\Repository @throws \Exception
entailment
public static function value($object, $attribute, $defaultValue = null) { if (is_scalar($attribute)) { foreach (explode(self::$pathDivider, $attribute) as $name) { if (isset($object->$name)) { $object = $object->$name; } elseif (isset($object[$name])) { $object = $object[$name]; } else { return $defaultValue; } } return $object; } elseif (is_callable($attribute)) { if ($attribute instanceof Closure) { $attribute = Closure::bind($attribute, $object); } return call_user_func($attribute, $object); } else { return null; } }
Evaluates the value of the specified attribute for the given object or array. The attribute name can be given in a path syntax. For example, if the attribute is "author.firstName", this method will return the value of "$object->author->firstName" or "$array['author']['firstName']". A default value (passed as the last parameter) will be returned if the attribute does not exist or is broken in the middle (e.g. $object->author is null). Anonymous function could also be used for attribute calculation as follows: <code> $taskClosedSecondsAgo=self::value($closedTask,function($model) { return time()-$model->closed_at; }); </code> Your anonymous function should receive one argument, which is the object, the current value is calculated from. @param mixed $object This can be either an object or an array. @param mixed $attribute the attribute name (use dot to concatenate multiple attributes) or anonymous function (PHP 5.3+). Remember that functions created by "create_function" are not supported by this method. Also note that numeric value is meaningless when first parameter is object typed. @param mixed $defaultValue the default value to return when the attribute does not exist. @return mixed the attribute value.
entailment
public static function join($array, $divider = ',', $prefix = null, $postfix = null) { if (is_array($divider)) { list($divider, $prefix, $postfix) = $divider; } array_walk($array, function (&$value) use ($divider, $prefix, $postfix) { if (is_array($value)) { $value = self::join(self::createFlat($value), $divider, $prefix, $postfix); } else { if (is_object($value)) { if (isset($value->id)) { $value = $value->id; } elseif ($value instanceof \Carbon\Carbon) { $value = $value->toDateTimeString(); } else { $value = null; } } $value = $prefix . $value . $postfix; } }); return join($divider, $array); }
Return string containing a string representation of all the items, with the $divider string between each element. <code> $str=A::join([1,2,3],',','["','"]'); // $str='["1"],["2"],["3"]' $str=A::join(['a'=>[1,2,3]],','); // array flatten $str='1,2,3' $str=A::join([$user1,$user2,$user3],','); // for objects joined id attribute $str='id1,id2,id3' </code> @param array|Arrayable $array @param string|array $divider string value of divider OR array [$divider,$prefix,$postfix] @param string $prefix add to start of value @param string $postfix add to end of value @return array @uses array_walk()
entailment
public function register() { $this->commands([ Commands\DeployCommand::class, Commands\ListCommand::class, Commands\RollbackCommand::class, Commands\SyncCommand::class, ]); }
Register the service provider. @return void
entailment
private function addIdentityFieldsToUser() { /** @var CrudService $service */ $service = $this->container->get('shopware_attribute.crud_service'); foreach (self::PROVIDERS as $provider) { $service->update('s_user_attributes', strtolower($provider) . '_identity', 'string', [ 'label' => 'Identity ' . $provider, //user has the opportunity to translate the attribute field for each shop 'translatable' => false, //attribute will be displayed in the backend module 'displayInBackend' => true, //in case of multi_selection or single_selection type, article entities can be selected, 'entity' => Customer::class, //numeric position for the backend view, sorted ascending 'position' => 100, //user can modify the attribute in the free text field module 'custom' => false, ]); } $models = $this->container->get('models'); $metaDataCache = $models->getConfiguration()->getMetadataCacheImpl(); $metaDataCache->deleteAll(); $models->generateAttributeModels(['s_user_attributes']); }
Adds the identity attribute to the customer model. @return void @throws \Exception
entailment
private function activateAmazonProvider() { if (ComposerLocator::isInstalled('hybridauth/hybridauth')) { $hybridauthRootPath = ComposerLocator::getPath('hybridauth/hybridauth'); $hybridauthAmazonPath = rtrim($hybridauthRootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'additional-providers' . DIRECTORY_SEPARATOR . 'hybridauth-amazon'; $hybridauthHybridPath = rtrim($hybridauthRootPath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'hybridauth' . DIRECTORY_SEPARATOR . 'Hybrid'; if ( file_exists($hybridauthAmazonPath) && is_dir($hybridauthAmazonPath) && file_exists($hybridauthHybridPath) && is_dir($hybridauthHybridPath) ) { $source = $hybridauthAmazonPath; $dest = $hybridauthHybridPath; /** @var \RecursiveDirectoryIterator $dirIterator */ $dirIterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($dirIterator as $item) { $subItem = $dest . DIRECTORY_SEPARATOR . $dirIterator->getSubPathName(); if ($item->isDir()) { if (!file_exists($subItem)) { if (!mkdir($subItem) && !is_dir($subItem)) { throw new \RuntimeException(sprintf('Directory "%s" was not created', $subItem)); } } } else { copy($item, $subItem); } } } } }
Activate Amazon provider (copy sources from additional-providers into Hybrid) @return void @throws \Exception
entailment
public function getMultiple(array $keys, $default = null) { KeyUtil::validateMultiple($keys); // Normalize indices of the array $keys = array_values($keys); $values = array(); try { $serializedValues = $this->clientGetMultiple($keys); } catch (Exception $e) { throw ReadException::forException($e); } foreach ($serializedValues as $i => $serializedValue) { $values[$keys[$i]] = $this->clientNotFoundValue() === $serializedValue ? $default : Serializer::unserialize($serializedValue); } return $values; }
{@inheritdoc}
entailment
public function getMultipleOrFail(array $keys) { KeyUtil::validateMultiple($keys); // Normalize indices of the array $keys = array_values($keys); $values = array(); $notFoundKeys = array(); try { $serializedValues = $this->clientGetMultiple($keys); } catch (Exception $e) { throw ReadException::forException($e); } foreach ($serializedValues as $i => $serializedValue) { if ($this->clientNotFoundValue() === $serializedValue) { $notFoundKeys[] = $keys[$i]; } elseif (0 === count($notFoundKeys)) { $values[$keys[$i]] = Serializer::unserialize($serializedValue); } } if (0 !== count($notFoundKeys)) { throw NoSuchKeyException::forKeys($notFoundKeys); } return $values; }
{@inheritdoc}
entailment
public function get($key, $default = null) { KeyUtil::validate($key); try { $serialized = $this->clientGet($key); } catch (Exception $e) { throw ReadException::forException($e); } if ($this->clientNotFoundValue() === $serialized) { return $default; } return Serializer::unserialize($serialized); }
{@inheritdoc}
entailment
public function getOrFail($key) { KeyUtil::validate($key); try { $serialized = $this->clientGet($key); } catch (Exception $e) { throw ReadException::forException($e); } if ($this->clientNotFoundValue() === $serialized) { throw NoSuchKeyException::forKey($key); } return Serializer::unserialize($serialized); }
{@inheritdoc}
entailment
public function set($key, $value) { KeyUtil::validate($key); $serialized = Serializer::serialize($value); try { $this->clientSet($key, $serialized); } catch (Exception $e) { throw WriteException::forException($e); } }
{@inheritdoc}
entailment
public function remove($key) { KeyUtil::validate($key); try { return (bool) $this->clientRemove($key); } catch (Exception $e) { throw WriteException::forException($e); } }
{@inheritdoc}
entailment
public function exists($key) { KeyUtil::validate($key); try { return $this->clientExists($key); } catch (Exception $e) { throw ReadException::forException($e); } }
{@inheritdoc}
entailment
public function start() { // Get server list. $connection = new Connection($this->optServer); $servers = $connection->servers(); $rollback = null; // When in rollback mode, get the commit. if ($this->mode == self::MODE_ROLLBACK) { $rollback = array('commit' => $this->optRollback); } // Init the Git object with the repo and // rollback option. $git = new Git($this->optRepo, $rollback); // There may be one or more servers, but in each // case it's build as an array. foreach ($servers as $name => $credentials) { try { $options = isset($credentials['options']) ? $credentials['options'] : array(); // Connect to the server using the selected // scheme and options. $bridge = new Bridge(http_build_url('', $credentials), $options); } catch (Exception $e) { print "Oh snap: {$e->getMessage()}"; continue; } $deploy = new Deploy($git, $bridge, $credentials); print "\r\n+ --------------- § --------------- +"; print "\n» Server: $name"; // Sync mode. Write revision and close the // connection, so no other files are uploaded. if ($this->mode == self::MODE_SYNC) { $deploy->setSyncCommit($this->optSyncCommit); $deploy->writeRevision(); print "\n √ Synced local revision file to remote"; print "\n+ --------------- √ --------------- +\r\n"; continue; } // Rollback to the specified commit. if ($this->mode == self::MODE_ROLLBACK) { print "\n« Rolling back "; $git->rollback(); } $dirtyRepo = $this->push($deploy); $dirtySubmodules = false; // Check if there are any submodules. if ($git->getSubModules()) { foreach ($git->getSubModules() as $submodule) { // Change repo. $git->setRepo($submodule['path']); // Set submodule name. $deploy->setIsSubmodule($submodule['name']); print "\n» Submodule: " . $submodule['name']; $dirtySubmodules = $this->push($deploy); } } // Files are uploaded or deleted, for the main // repo or submodules. if (($dirtyRepo or $dirtySubmodules)) { if ($this->mode == self::MODE_DEPLOY or $this->mode == self::MODE_ROLLBACK) { // Write latest revision to server. $deploy->writeRevision(); } } else { print "\n» Nothing to do."; } print "\n+ --------------- √ --------------- +\r\n"; // On rollback mode, revert to master. if ($this->mode == self::MODE_ROLLBACK) { $git->revertToMaster(); } } }
Starts the Maneuver
entailment
public function push($deploy) { // Compare local revision to the remote one, to // build files to upload and delete. $message = $deploy->compare(); print $message; print "\n+ --------------- + --------------- +"; $dirty = false; $filesToUpload = $deploy->getFilesToUpload(); $filesToDelete = $deploy->getFilesToDelete(); if ($filesToUpload) { foreach ($filesToUpload as $file) { // On list mode, just print the file. if ($this->mode == self::MODE_LIST) { print "\n√ \033[0;37m{$file}\033[0m \033[0;32mwill be uploaded\033[0m"; continue; } $output = $deploy->upload($file); // An upload procedure may have more than one // output message (uploaded file, created dir, etc). foreach ($output as $message) { print "\n" . $message; } } } if ($filesToDelete) { foreach ($filesToDelete as $file) { // On list mode, just print the file. if ($this->mode == self::MODE_LIST) { print "\n× \033[0;37m{$file}\033[0m \033[0;31mwill be removed\033[0m"; continue; } print "\n" . $deploy->delete($file); } } // Files were uploaded or deleted, so mark // it as dirty. if ($filesToUpload or $filesToDelete) { $dirty = true; } return $dirty; }
Handles the upload and delete processes @param \Fadion\Maneuver\Deploy $deploy @return bool
entailment
protected function cleanRequestUri() { $requestUri = $this->request->getRequestUri(); $requestUriQuery = parse_url($requestUri, PHP_URL_QUERY); parse_str($requestUriQuery, $requestParams); if (is_array($requestParams) && count($requestParams) > 0) { foreach ($this->ajaxQueryParams as $queryParam) { if (array_key_exists($queryParam, $requestParams)) { unset($requestParams[$queryParam]); } } } $this->request->setRequestUri( str_replace($requestUriQuery, http_build_query($requestParams), $requestUri) ); }
Remove query parameters added to the request URI for AJAX requests @return void
entailment
protected function removeAjaxQueryParams() { /** @var \Zend\Stdlib\Parameters */ $query = $this->request->getQuery(); if (count($query) > 0) { foreach ($this->ajaxQueryParams as $queryParam) { $query->set($queryParam, null); } } }
Remove query parameters added for AJAX requests @return void
entailment
protected function jsonResponse($data) { /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultJsonFactory->create(); $resultJson->setHeader('Content-type', 'application/json', true); $resultJson->setData($data); return $resultJson; }
Build a JSON response @param array $data Response data @return \Magento\Framework\Controller\Result\Json
entailment
protected function getCurrentPageUrl($pager) { if ($pager->isFirstPage()) { $pageUrl = $pager->getPageUrl(null); } else { $pageUrl = $pager->getPageUrl($pager->getCurrentPage()); } return $this->removeTags->filter($pageUrl); }
Retrieve current page URL @param \Magento\Theme\Block\Html\Pager $pager @return string
entailment
public function set($key, $value) { KeyUtil::validate($key); $serialized = Serializer::serialize($value); try { $this->client->bucket($this->bucketName)->newBinary($key, $serialized)->store(); } catch (Exception $e) { throw WriteException::forException($e); } }
{@inheritdoc}
entailment
public function get($key, $default = null) { KeyUtil::validate($key); try { $object = $this->client->bucket($this->bucketName)->getBinary($key); $exists = $object->exists(); } catch (Exception $e) { throw ReadException::forException($e); } if (!$exists) { return $default; } return Serializer::unserialize($object->getData()); }
{@inheritdoc}
entailment
public function getOrFail($key) { KeyUtil::validate($key); try { $object = $this->client->bucket($this->bucketName)->getBinary($key); $exists = $object->exists(); } catch (Exception $e) { throw ReadException::forException($e); } if (!$exists) { throw NoSuchKeyException::forKey($key); } return Serializer::unserialize($object->getData()); }
{@inheritdoc}
entailment
public function getMultiple(array $keys, $default = null) { KeyUtil::validateMultiple($keys); $values = array(); try { $bucket = $this->client->bucket($this->bucketName); foreach ($keys as $key) { $object = $bucket->getBinary($key); $values[$key] = $object->exists() ? $object->getData() : false; } } catch (Exception $e) { throw ReadException::forException($e); } foreach ($values as $key => $value) { $values[$key] = false === $value ? $default : Serializer::unserialize($value); } return $values; }
{@inheritdoc}
entailment
public function getMultipleOrFail(array $keys) { KeyUtil::validateMultiple($keys); $values = array(); $notFoundKeys = array(); try { $bucket = $this->client->bucket($this->bucketName); foreach ($keys as $key) { $values[$key] = $bucket->getBinary($key); if (!$values[$key]->exists()) { $notFoundKeys[] = $key; } } } catch (Exception $e) { throw ReadException::forException($e); } if (0 !== count($notFoundKeys)) { throw NoSuchKeyException::forKeys($notFoundKeys); } foreach ($values as $key => $object) { $values[$key] = Serializer::unserialize($object->getData()); } return $values; }
{@inheritdoc}
entailment
public function remove($key) { KeyUtil::validate($key); try { $object = $this->client->bucket($this->bucketName)->get($key); if (!$object->exists()) { return false; } $object->delete(); } catch (Exception $e) { throw WriteException::forException($e); } return true; }
{@inheritdoc}
entailment
public function exists($key) { KeyUtil::validate($key); try { return $this->client->bucket($this->bucketName)->get($key)->exists(); } catch (Exception $e) { throw ReadException::forException($e); } }
{@inheritdoc}
entailment
public function clear() { try { $bucket = $this->client->bucket($this->bucketName); foreach ($bucket->getKeys() as $key) { $bucket->get($key)->delete(); } } catch (Exception $e) { throw WriteException::forException($e); } }
{@inheritdoc}
entailment
public function keys() { try { return $this->client->bucket($this->bucketName)->getKeys(); } catch (Exception $e) { throw ReadException::forException($e); } }
{@inheritdoc}
entailment
public function set($key, $value) { KeyUtil::validate($key); if (is_float($value) && $value > self::MAX_FLOAT) { throw new UnsupportedValueException('The JSON file store cannot handle floats larger than 1.0E+14.'); } $data = $this->load(); $data[$key] = $this->serializeValue($value); $this->save($data); }
{@inheritdoc}
entailment
public function get($key, $default = null) { KeyUtil::validate($key); $data = $this->load(); if (!array_key_exists($key, $data)) { return $default; } return $this->unserializeValue($data[$key]); }
{@inheritdoc}
entailment
public function getOrFail($key) { KeyUtil::validate($key); $data = $this->load(); if (!array_key_exists($key, $data)) { throw NoSuchKeyException::forKey($key); } return $this->unserializeValue($data[$key]); }
{@inheritdoc}
entailment
public function getMultiple(array $keys, $default = null) { $values = array(); $data = $this->load(); foreach ($keys as $key) { KeyUtil::validate($key); if (array_key_exists($key, $data)) { $value = $this->unserializeValue($data[$key]); } else { $value = $default; } $values[$key] = $value; } return $values; }
{@inheritdoc}
entailment
public function getMultipleOrFail(array $keys) { $values = array(); $data = $this->load(); foreach ($keys as $key) { KeyUtil::validate($key); if (!array_key_exists($key, $data)) { throw NoSuchKeyException::forKey($key); } $values[$key] = $this->unserializeValue($data[$key]); } return $values; }
{@inheritdoc}
entailment
public function remove($key) { KeyUtil::validate($key); $data = $this->load(); if (!array_key_exists($key, $data)) { return false; } unset($data[$key]); $this->save($data); return true; }
{@inheritdoc}
entailment
public function exists($key) { KeyUtil::validate($key); $data = $this->load(); return array_key_exists($key, $data); }
{@inheritdoc}
entailment
public function sort($flags = SORT_REGULAR) { $data = $this->load(); ksort($data, $flags); $this->save($data); }
{@inheritdoc}
entailment
public function checked(bool $bool, string $checked = '&check;', string $unchecked = '-'): string { return $bool ? $checked : $unchecked; }
@param bool $bool @param string $checked @param string $unchecked @return string
entailment
public function image(string $link, string $title = null, string $view = null): string { $view = $view ?: 'column.linkImage'; return GridView::view($view, [ 'link' => $link, 'title' => $title, ])->render(); }
@param string $link @param string|null $title @param string|null $view @return string @throws \Throwable
entailment
public function listToString( $data, string $title = null, string $titleAddition = null, string $class = null, string $delimiter = null, string $delimiterAddition = null, string $view = null ): string { $view = $view ?: 'column.listToString'; return GridView::view($view, [ 'data' => $data, 'title' => $title, 'titleAddition' => $titleAddition, 'class' => $class, 'delimiter' => $delimiter, 'delimiterAddition' => $delimiterAddition, ])->render(); }
@param $data @param string|null $title @param string|null $titleAddition @param string|null $class @param string|null $delimiter @param string|null $delimiterAddition @param string|null $view @return string @throws \Throwable
entailment
public function filterButton( string $name, string $id, string $class = null, string $icon = null, string $title = null, string $originTitle = null, string $view = null ): string { $icon = $icon ? $icon : 'fa fa-filter'; $class = $class ? $class : 'btn btn-xs btn-default'; $title = $title ? $title : ''; $originTitle = $originTitle ? $originTitle : GridView::trans('grid.showSimilar'); $view = $view ?: 'column.filterButton'; return GridView::view($view, [ 'id' => $id, 'name' => $name, 'class' => $class, 'icon' => $icon, 'title' => $title, 'originTitle' => $originTitle, ])->render(); }
@param string $name @param string|null $id @param string|null $class @param string|null $icon @param string|null $title @param string|null $originTitle @param string|null $view @return string @throws \Throwable
entailment
public function editable(array $options = [], string $view = null): string { $view = $view ?: 'column.editableClick'; $initJsEvent = isset($options['initJsEvent']) ? $options['initJsEvent'] : 'ready change'; $initJsClass = isset($options['initJsClass']) ? $options['initJsClass'] : 'js_editableClick'; $escape = isset($options['escape']) ? $options['escape'] : true; $class = isset($options['class']) ? $options['class'] : 'inline-editable editable editable-click editable-empty'; $pk = isset($options['pk']) ? $options['pk'] : 1; $name = isset($options['name']) ? $options['name'] : 'name'; $value = isset($options['value']) ? $options['value'] : null; $type = isset($options['type']) ? $options['type'] : 'text'; $text = isset($options['text']) ? $options['text'] : null; $url = isset($options['url']) ? $options['url'] : ''; $source = isset($options['source']) ? $options['source'] : null; $sourceCache = isset($options['sourceCache']) ? $options['sourceCache'] : null; $emptyText = isset($options['emptyText']) ? $options['emptyText'] : 'Empty'; $originalTitle = isset($options['originalTitle']) ? $options['originalTitle'] : null; $title = isset($options['title']) ? $options['title'] : null; $rows = isset($options['rows']) ? $options['rows'] : 10; $callback = isset($options['callback']) ? $options['callback'] : null; return GridView::view($view, [ 'class' => $class, 'name' => $name, 'value' => $value, 'text' => $text, 'emptyText' => $emptyText, 'title' => $title, 'originalTitle' => $originalTitle, 'type' => $type, 'url' => $url, 'pk' => $pk, 'escape' => $escape, 'initJsEvent' => $initJsEvent, 'initJsClass' => $initJsClass, 'source' => $source, 'sourceCache' => $sourceCache, 'rows' => $rows, 'callback' => $callback, ])->render(); }
Editable ceil button * =========================================== * string - $initJsEvent - Init js event * string - $initJsClass - Init js class * bool - $escape - * string - $class - * string - $text - * string|array|int - $name - * string|array|int - $value - * string - $url - * string - $type - Type: text|textarea|select|checklist * int - $pk - * array - $source - Source data for list. * string - $sourceCache - If true and source is string url - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. * string - $emptyText - * string - $originalTitle - Original title * string - $title - * int - $rows - * callable - $callback - function * =========================================== @param array $options @param string|null $view @return string
entailment
public static function validateMultiple($keys) { foreach ($keys as $key) { if (!is_string($key) && !is_int($key)) { throw InvalidKeyException::forKey($key); } } }
Validates that multiple keys are valid. @param array $keys The tested keys. @throws InvalidKeyException If a key is invalid.
entailment
public function loginAction() { $provider = $this->Request()->getParam('provider'); if ($provider) { /** @var \Port1HybridAuth\Service\SingleSignOnService $singleSignOnService */ $singleSignOnService = $this->container->get('port1_hybrid_auth.single_sign_on_service'); $isUserLoggedIn = $singleSignOnService->loginAndRegisterVia($provider); if ($isUserLoggedIn) { return $this->redirect( [ 'controller' => $this->Request()->getParam('sTarget', 'account'), 'action' => $this->Request()->getParam('sTargetAction', 'index') ] ); } $this->forward('index', 'register', 'frontend', [ 'sTarget' => $this->Request()->getParam('sTarget') ]); } else { // @todo: redirect to referere or error? } }
action login @throws \Exception
entailment
public function registerCustomerByUser($user) { /** @var ShopContextInterface $context */ $context = $this->context->getShopContext(); $shop = $context->getShop(); $customer = new Customer(); $customer->setAttribute([strtolower($user->getType()) . 'Identity' => $user->getId()]); $customer->setSalutation($user->getSalutation()); $customer->setEmail($user->getEmail()); $customer->setFirstname($user->getFirstName()); $customer->setLastname($user->getLastName()); // we generate the password here, because we have no password // due the SSO mechanism and we will not neet it in future // But SW needs it :-) $password = uniqid(); $customer->setPassword($password); $billing = new Address(); $billing->setCompany($user->getCompany()); $billing->setSalutation($user->getSalutation()); $billing->setFirstname($user->getFirstName()); $billing->setLastname($user->getLastName()); $billing->setCity($user->getCity()); $billing->setStreet($user->getAddress()); $billing->setZipcode($user->getZip()); // try to find the best matching country for the user $country = $this->countryService->getBestMatchingCountryForUser($user); // try to find the matching country by the current locale of the shop if ($country === null) { $defaultCountry = Shopware()->Config()->getByNamespace('Port1HybridAuth', 'general_default_country'); if ($defaultCountry) { $country = $this->countryService->getCountryById($defaultCountry); } } // take germany if no country could be found if ($country === null) { $country = $this->countryService->getCountryByCountryIso('de'); } $billing->setCountry($country); try { $this->register($shop, $customer, $billing); } catch (Exception $ex) { return null; } return $customer; }
@param User $user @return Customer
entailment
public function connectUserWithExistingCustomer($user, $customer) { $result = false; if ($user->getEmail() === $customer->getEmail()) { \call_user_func( [$customer->getAttribute(), 'set' . ucfirst($user->getType()) . 'Identity'], $user->getId() ); $result = $this->udapteCustomerAttributes($customer); } return $result; }
Connects a user with an existing customer @param User $user @param Customer $customer @return Customer|false Customer if connecting was successful, false if not (e.g. email adresses are not equal)
entailment
protected function udapteCustomerAttributes($customer) { try { $this->validator->validate($customer); $this->modelManager->persist($customer->getAttribute()); $this->modelManager->flush($customer->getAttribute()); $this->modelManager->refresh($customer->getAttribute()); return $customer; } catch (Exception $ex) { return false; } }
@param Customer $customer @return Customer|false
entailment
protected function command($command, $repoPath = null) { if (!$repoPath) { $repoPath = $this->repo; } $command = 'git --git-dir="'.$repoPath.'/.git" --work-tree="'.$repoPath.'" '.$command; exec(escapeshellcmd($command), $output, $returnStatus); if ($returnStatus != 0) { throw new Exception("The following command was attempted but failed:\r\n$command"); } return $output; }
Runs a Git command. @param string $command @param null|string $repoPath @throws Exception if command fails @return array
entailment
protected function subModules() { $repo = $this->repo; $output = $this->command('submodule status'); if ($output) { foreach ($output as $line) { $line = explode(' ', trim($line)); $this->submodules[] = array( 'revision' => $line[0], 'name' => $line[1], 'path' => $repo.'/'.$line[1] ); $this->ignoredFiles[] = $line[1]; $this->checkSubSubmodules($repo, $line[1]); } } }
Checks submodules
entailment
protected function checkSubSubmodules($repo, $name) { $output = $this->command('submodule foreach git submodule status'); if ($output) { foreach ($output as $line) { $line = explode(' ', trim($line)); if (trim($line[0]) == 'Entering') continue; $this->submodules[] = array( 'revision' => $line[0], 'name' => $name.'/'.$line[1], 'path' => $repo.'/'.$name.'/'.$line[1] ); $this->ignoredFiles[] = $name.'/'.$line[1]; } } }
Checks submodules of submodules @param string $repo @param string $name
entailment
final public static function getEverythingFromArgs(\Enlight_Event_EventArgs $args, $element = null) { /** * @var \Enlight_Controller_Action $controller */ $controller = $args->get('subject'); /** * @var \Enlight_Controller_Request_Request $request */ $request = $controller->Request(); /** * @var \Enlight_View_Default $view */ $view = $controller->View(); $result = [ 'controller' => $controller, 'request' => $request, 'view' => $view ]; if ($element !== null) { if (array_key_exists($element, $result)) { $result = $result[$element]; } else { $result = null; } } return $result; }
Returns an array in the form of var association: list($controller, $request, $view) = self::getEverythingFromArgs($args); @param \Enlight_Event_EventArgs $args @param null $element @return array|mixed|null
entailment