sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function register() { $this->app['routes.javascript'] = $this->app->share(function ($app) { $generator = new Generators\RoutesJavascriptGenerator($app['files'], $app['router']); return new Commands\RoutesJavascriptCommand($generator); }); $this->commands('routes.javascript'); }
Register the service provider. @return void
entailment
public function add($key, $value = null) { if (is_array($key)) { foreach ($key as $innerKey => $innerValue) { Arr::set($this->variables, $innerKey, $innerValue); } } elseif ($key instanceof Closure) { $this->variables[] = $key; } else { Arr::set($this->variables, $key, $value); } return $this; }
Add a variable. @param array|string|\Closure $key @param mixed $value @return $this
entailment
public function render($namespace = 'config') { foreach ($this->variables as $key => $variable) { if ($variable instanceof Closure) { $variable = $variable(); if (is_array($variable)) { $this->add($variable); } } } $variables = array_filter($this->variables, function ($variable) { return !$variable instanceof Closure; }); return new HtmlString( '<script>window.'.$namespace.' = '.json_encode($variables).';</script>' ); }
Render as a HTML string. @param string $namespace @return \Illuminate\Support\HtmlString
entailment
public function buildForm(array $form, FormStateInterface $form_state, $cid = 0) { // Загружаем характеристику по идентификатору. $characteristic = $this->database->characteristicsReadItem($cid); // Скрытые поля. $form['characteristic'] = array( '#type' => 'value', '#value' => $characteristic, ); // Вспомогательный текст при редактировании характеристики. $form['text'] = array( '#type' => 'markup', '#markup' => $this->t('You are editing characteristic № @сid.', ['@сid' => isset($characteristic->cid) ? $characteristic->cid : 0]), '#access' => isset($characteristic->cid) ? TRUE : FALSE, ); $form['gid'] = array( '#type' => 'select', '#title' => $this->t('Group'), '#options' => $this->database->characteristicsReadGroups(), '#access' => isset($characteristic->cid) ? FALSE : TRUE, ); $form['title'] = array( '#type' => 'textfield', '#title' => $this->t('Title'), '#maxlength' => 255, '#required' => TRUE, '#default_value' => isset($characteristic->cid) ? $characteristic->title : "", ); $form['description'] = array( '#type' => 'textfield', '#title' => $this->t('Description'), '#maxlength' => 255, '#required' => FALSE, '#default_value' => isset($characteristic->cid) ? $characteristic->description : "", ); $form['status'] = array( '#title' => $this->t('Display'), '#type' => 'checkbox', '#default_value' => 1, '#access' => isset($characteristic->cid) ? FALSE : TRUE, ); $form['image'] = [ '#name' => 'characteristic_image', '#type' => 'managed_file', '#multiple' => FALSE, '#title' => $this->t("Add image"), '#upload_validators' => [ 'file_validate_extensions' => ['svg jpg jpeg png'], 'file_validate_size' => [25600000], 'file_validate_image_resolution' => ['30x30'], ], '#default_value' => NULL, '#upload_location' => 'public://upload-files/', '#description' => $this->t('Used as an icon before the name of the product characteristics.'), ]; // Now we add our submit button, for submitting the form results. // The 'actions' wrapper used here isn't strictly necessary for tabledrag, // but is included as a Form API recommended practice. $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t('Save'), '#button_type' => 'primary', ); return $form; }
{@inheritdoc}
entailment
public function submitForm(array &$form, FormStateInterface $form_state) { $characteristic = $form_state->getValue('characteristic'); $title = trim($form_state->getValue('title')); $description = trim($form_state->getValue('description')); $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId(); // Выполняем если создаётся новый элемент. $return_created = null; $return_updated = null; if (!isset($characteristic->cid) && $title) { $uuid = \Drupal::service('uuid'); $data = array( 'uuid' => $uuid->generate(), 'langcode' => $langcode, 'title' => $title, 'description' => $description, ); $return_created = $this->database->characteristicsCreateItem($data); $characteristic = $this->database->characteristicsReadItem($return_created); if (isset($characteristic->cid) && $form_state->getValue('gid')) { $data = array( 'cid' => $characteristic->cid, 'gid' => $form_state->getValue('gid'), 'status' => $form_state->getValue('status'), 'weight' => 0, ); $this->database->characteristicsCreateItemIndex($data); } } else { // Выполняем если обновляется элемент. $entry = array( 'cid' => $characteristic->cid, 'title' => $title, 'description' => $description, ); $return_updated = $this->database->characteristicsUpdateItem($entry); } // Сохраняем изображение. if (isset($characteristic->cid)) { $destination = 'public://images/characteristics'; file_prepare_directory($destination, FILE_CREATE_DIRECTORY); $image_fid = $form_state->getValue('image'); if (isset($image_fid[0])) { $file_form = file_load($image_fid[0]); if ($file_form) { if ($file = file_move($file_form, $destination, FILE_EXISTS_RENAME)) { $file->status = FILE_STATUS_PERMANENT; $file->save(); // Выполняем привязку файла к характеристике. $entry = array( 'cid' => $characteristic->cid, 'fid' => $file->id(), ); $this->database->characteristicsUpdateItem($entry); // Изменяем применяемость файла. $file_usage = \Drupal::service('file.usage'); if ($file_current_usage = $this->database->loadFile('characteristic', $characteristic->cid)) { $file_usage->delete($file_current_usage, 'site_commerce', 'characteristic', $characteristic->cid); $file_current_usage->status = 0; $file_current_usage->save(); } $file_usage->add($file, 'site_commerce', 'characteristic', $characteristic->cid); } else { // Фиксируем в журнале событий ошибку. \Drupal::logger('characteristic create image')->error('Файл не был загружен: @id', array( '@id' => $file_form->id(), )); } } } } if ($return_created) { drupal_set_message($this->t('Characteristic «@title» created.', array('@title' => $form_state->getValue('title')))); } if ($return_updated) { drupal_set_message($this->t('Characteristic «@title» updated.', array('@title' => $form_state->getValue('title')))); $form_state->setRedirect('site_commerce.characteristics_editor'); } }
{@inheritdoc}
entailment
public function boot() { $this->registerRouteMiddleware( $this->app->make(Router::class), $this->app->make(Kernel::class) ); $this->bootRoutes(); $this->app->make('events')->dispatch('orchestra.ready'); }
Bootstrap the application events. @return void
entailment
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $element = []; $element['appearance'] = array( '#type' => 'select', '#title' => $this->t('Appearance'), '#options' => getAppearance(), '#default_value' => isset($items[$delta]->appearance) ? $items[$delta]->appearance : '0', '#empty_value' => 0, '#theme_wrappers' => [], ); $element['new'] = array( '#type' => 'select', '#title' => $this->t('New product'), '#options' => array( '0' => $this->t('None'), '1' => $this->t('Да'), ), '#default_value' => isset($items[$delta]->new) ? $items[$delta]->new : '0', '#empty_value' => 0, '#theme_wrappers' => [], ); $element['stock'] = array( '#type' => 'select', '#title' => $this->t('Stock availability'), '#options' => getStockAvailability(), '#empty_value' => 0, '#default_value' => isset($items[$delta]->stock) ? $items[$delta]->stock : '0', '#theme_wrappers' => [], ); $element['sale'] = array( '#type' => 'select', '#title' => $this->t('Type of sale'), '#options' => array( 'sale_type_1' => $this->t('Поштучная продажа'), 'sale_type_2' => $this->t('Продажа в составе другого товара'), ), '#default_value' => isset($items[$delta]->sale) ? $items[$delta]->sale : 'sale_type_1', '#theme_wrappers' => [], ); $element['#theme'] = 'site_commerce_settings_default_widget'; return $element; }
{@inheritdoc}
entailment
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) { switch ($operation) { case 'view': return AccessResult::allowedIfHasPermission($account, 'access content'); case 'edit': return AccessResult::allowedIfHasPermission($account, 'administer site commerce'); case 'update': return AccessResult::allowedIfHasPermission($account, 'administer site commerce'); case 'duplicate': return AccessResult::allowedIfHasPermission($account, 'administer site commerce'); case 'delete': return AccessResult::allowedIfHasPermission($account, 'administer site commerce'); } return AccessResult::forbidden(); }
{@inheritdoc} Link the activities to the permissions. checkAccess is called with the $operation as defined in the routing.yml file.
entailment
public static function string( $str, $row = null, $col = null ) { if( $col !== null || $row !== null ) { Cursor::rowcol($row, $col); } fwrite(self::$stream, $str); }
Output a string @param string $str String to output @param false|int $row The optional row to output to @param false|int $col The optional column to output to
entailment
public static function line( $str, $col = null, $erase = true ) { if( $col !== null ) { Cursor::rowcol($col, 1); } if( $erase ) { Erase::line(); } fwrite(self::$stream, $str); }
Output a line, erasing the line first @param string $str String to output @param null|int $col The column to draw the current line @param boolean $erase Clear the line before drawing the passed string
entailment
public function register() { $this->registerFoundation(); $this->registerMetaContainer(); $this->registerThrottlesLogins(); $this->registerFacadesAliases(); $this->registerCoreContainerAliases(); $this->registerEventListeners(); }
Register the service provider. @return void
entailment
protected function registerThrottlesLogins(): void { $config = $this->app->make('config')->get('orchestra/foundation::throttle', []); $throttles = $config['resolver'] ?? BasicThrottle::class; $this->app->bind(ThrottlesLogins::class, $throttles); BasicThrottle::setConfig($config); }
Register the service provider for foundation. @return void
entailment
public function boot() { $this->bootAuthen(); $path = \realpath(__DIR__.'/../../'); $this->addConfigComponent('orchestra/foundation', 'orchestra/foundation', "{$path}/resources/config"); $this->addLanguageComponent('orchestra/foundation', 'orchestra/foundation', "{$path}/resources/lang"); $this->addViewComponent('orchestra/foundation', 'orchestra/foundation', "{$path}/resources/views"); }
Bootstrap the application events. @return void
entailment
public function processNode(Node $node, Scope $scope): array { $messages = []; $docComment = $node->getDocComment(); if (empty($docComment)) { return $messages; } $hash = \sha1(\sprintf('%s:%s:%s:%s', $scope->getFile(), $docComment->getLine(), $docComment->getFilePos(), $docComment->getText() )); if (isset($this->alreadyParsedDocComments[$hash])) { return $messages; } $this->alreadyParsedDocComments[$hash] = true; $lines = \preg_split('/\R/u', $docComment->getText()); if (false === $lines) { return $messages; } foreach ($lines as $lineNumber => $lineContent) { $matches = []; if (! \preg_match('/^(?:\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)\\\\?(?<className>\w[^:\s]*)(?:::\S+)?\s*$/u', $lineContent, $matches)) { continue; } if (! $this->broker->hasClass($matches['className'])) { $messages[] = \sprintf('Class %s does not exist (line: %s).', $matches['className'], $docComment->getLine() + $lineNumber); } } return $messages; }
@param \PhpParser\Node $node @param \PHPStan\Analyser\Scope $scope @return string[] errors
entailment
public function configure($content) { foreach ((array) $this->convertToArray($content) as $data_block) { switch ($this->getDataType($data_block)) { case static::DATA_TYPE_REPORT: $this->stack[] = new ReportData($data_block); break; case static::DATA_TYPE_USER_INFO: $this->stack[] = new UserInfoData($data_block); break; case static::DATA_TYPE_USER_BALANCE: $this->stack[] = new BalanceData($data_block); break; case static::DATA_TYPE_REPORT_TYPE: $this->stack[] = new ReportTypeData($data_block); break; case static::DATA_TYPE_REPORT_MAKE: $this->stack[] = new ReportStatusData($data_block); break; default: $this->stack[] = new UnknownDataType($data_block); } } }
{@inheritdoc}
entailment
public function each(Closure $closure) { foreach ($this->stack as &$item) { $closure($item); } return $this; }
Перебирает все элементы стека, выполняя для каждого элемента переданную лямбду. @param Closure $closure @return static|self
entailment
protected function getDataType($data_block) { if (\is_array($data_block) && ! empty($data_block)) { switch (true) { case isset($data_block['report_type_uid'], $data_block['query']): return static::DATA_TYPE_REPORT; case isset($data_block['login'], $data_block['state'], $data_block['roles']): return static::DATA_TYPE_USER_INFO; case isset($data_block['balance_type'], $data_block['report_type_uid']): return static::DATA_TYPE_USER_BALANCE; case isset($data_block['state'], $data_block['total_quote'], $data_block['content']): return static::DATA_TYPE_REPORT_TYPE; case isset($data_block['isnew'], $data_block['suggest_get']): return static::DATA_TYPE_REPORT_MAKE; } } return static::DATA_TYPE_UNKNOWN; }
Определяет тип данных, которые содержатся в ответе от сервиса B2B. @param array|mixed $data_block @return string
entailment
public function save(array $form, FormStateInterface $form_state) { $site_commerce = $this->entity; $status = $site_commerce->save(); if ($status) { drupal_set_message($this->t('Saved the %label site_commerce.', array( '%label' => $site_commerce->label(), ))); } else { drupal_set_message($this->t('The %label site_commerce was not saved.', array( '%label' => $site_commerce->label(), ))); } $form_state->setRedirect('entity.site_commerce_type.collection'); }
{@inheritdoc}
entailment
public function exist($id) { $entity = $this->entityQuery->get('site_commerce_type') ->condition('id', $id) ->execute(); return (bool) $entity; }
Helper function to check whether an SiteCommerceType configuration entity exists.
entailment
public function import_catalog($file, $md5_current, $config) { $reader = new Xls(); $spreadsheet = $reader->load($file); $sheet = $spreadsheet->getActiveSheet(); $cells = $sheet->getCellCollection(); $row_max = $cells->getHighestRow(); // Строка с которой начнется импорт из файла. if (!$config->get('import_catalog_row')) { $row = 2; } else { $row = $config->get('import_catalog_row'); } // Максимальное кол-во строк обрабатываемых за один цикл CRON; $row_chank_size = 5000; $row_chank_size_max = $row_chank_size + $row; $queue = \Drupal::queue('site_commerce_catalog_import'); $queue->createQueue(); $data = []; $queue_created = TRUE; for ($row; $row <= $row_max; $row++) { if ($row > $row_chank_size_max) { $queue_created = FALSE; $config->set('import_catalog_row', $row)->save(); \Drupal::logger('import_catalog')->notice('Import categories of goods completed in row: @row.', ['@row' => $row]); break; } // Создаем очередь задания. $data = [ 'name' => $sheet->getCellByColumnAndRow(1, $row)->getCalculatedValue(), 'id' => $sheet->getCellByColumnAndRow(2, $row)->getCalculatedValue(), 'parent' => $sheet->getCellByColumnAndRow(3, $row)->getCalculatedValue(), 'published' => $sheet->getCellByColumnAndRow(4, $row)->getCalculatedValue(), ]; $queue->createItem($data); } // Записываем текущее значение md5. Считаем, что файл полностью обработан. if ($queue_created) { $config->set('file_catalog_md5', $md5_current)->save(); $config->set('import_catalog_row', 0)->save(); \Drupal::logger('import_catalog')->notice('Import catalog processing completed.'); } }
Импорт каталога товаров.
entailment
public function getCreatedAt() { return ! empty($value = $this->getContentValue('created_at', null)) ? $this->convertToCarbon($value) : null; }
Возвращает дату/время, когда был создан. @return Carbon|null
entailment
public function listen($events) { $this->dispatcher->listen($events, function (DelayedEvent $event) { $this->dispatch($event); }); }
Register events. @param array|string $events
entailment
public function begin() { $this->current = $this->current instanceof Transaction ? $this->current->newTransaction() : new Transaction; }
Should be called after transaction started. @return void
entailment
public function commit() { $this->assert(); $current = $this->current; $this->current = $current->getParentKeepingChildren(); if (!$this->current instanceof Transaction) { // There are no transactions, dispatch all reserved payloads foreach ($current->flatten() as $payload) { $payload->fire(); } } }
Should be called after transaction committed. @return void
entailment
protected function dispatch(DelayedEvent $event) { if ($this->current instanceof Transaction) { // Already in transaction, reserve it $this->current->attach($event); } else { // There are no transactions, just dispatch it $event->fire(); } }
Dispaches payload. @param DelayedEvent $event @return void
entailment
protected function getParsedRoutes($filter = null, $prefix = null) { $parsedRoutes = []; foreach ($this->routes as $route) { $routeInfo = $this->getRouteInformation($route); if ($routeInfo) { if ($prefix) { $routeInfo['uri'] = $prefix . $routeInfo['uri'] ; } if ($filter) { if (in_array($filter, $routeInfo['before'])) { unset($routeInfo['before']); $parsedRoutes[] = $routeInfo; } } else { unset($routeInfo['before']); $parsedRoutes[] = $routeInfo; } } } return array_filter($parsedRoutes); }
Get parsed routes @param string $filter @param string $prefix @return array
entailment
protected function getRouteInformation(Route $route) { if ($route->getName()) { return [ 'uri' => $route->uri(), 'name' => $route->getName(), 'before' => $this->getBeforeFilters($route), ]; } return null; }
Get the route information for a given route. @param \Illuminate\Routing\Route $route @return array
entailment
protected function getPatternFilters($route) { $patterns = []; foreach ($route->methods() as $method) { $inner = $this->getMethodPatterns($route->uri(), $method); $patterns = array_merge($patterns, array_keys($inner)); } return $patterns; }
Get all of the pattern filters matching the route. @param \Illuminate\Routing\Route $route @return array
entailment
protected function getMethodPatterns($uri, $method) { return $this->router->findPatternFilters(Request::create($uri, $method)); }
Get the pattern filters for a given URI and method. @param string $uri @param string $method @return array
entailment
public function hasTooManyLoginAttempts() { return $this->cacheLimiter->tooManyAttempts( $this->getUniqueLoginKey(), $this->maxLoginAttempts(), $this->lockoutTime() / 60 ); }
Determine if the user has too many failed login attempts. @return bool
entailment
public function fire() { $path = $this->getPath(); $options = [ 'filter' => $this->option('filter'), 'object' => $this->option('object'), 'prefix' => $this->option('prefix'), ]; if ($this->generator->make($this->option('path'), $this->argument('name'), $options)) { return $this->info("Created {$path}"); } $this->error("Could not create {$path}"); }
Execute the console command. @return mixed
entailment
protected function createDriver($driver) { $name = "orchestra.publisher.{$driver}"; if (! $this->app->bound($name)) { throw new RuntimeException("Unable to resolve [{$driver}] publisher"); } return $this->app->make($name); }
Create a new driver instance. @param string $driver @throws \InvalidArgumentException @return mixed
entailment
public function execute(): bool { $messages = $this->app->make('orchestra.messages'); $queues = $this->queued(); $fails = []; foreach ($queues as $queue) { try { $this->driver()->upload($queue); $messages->add('success', trans('orchestra/foundation::response.extensions.activate', [ 'name' => $queue, ])); } catch (Exception $e) { // this could be anything. $messages->add('error', $e->getMessage()); $fails[] = $queue; } } $this->memory->put('orchestra.publisher.queue', $fails); return true; }
Execute the queue. @return bool
entailment
public function queue($queue): bool { $queue = \array_unique(\array_merge($this->queued(), (array) $queue)); $this->memory->put('orchestra.publisher.queue', $queue); return true; }
Add a process to be queue. @param string|array $queue @return bool
entailment
public function viewElements(FieldItemListInterface $items, $langcode) { $elements = []; $values = []; foreach ($items as $delta => $item) { $values[$delta] = [ 'group' => $item->group, 'prefix' => $item->cost, 'cost_from' => \Drupal::service('kvantstudio.formatter')->price($item->cost_from), 'cost' => \Drupal::service('kvantstudio.formatter')->price($item->cost), 'currency' => $item->currency, 'suffix' => $item->suffix, ]; } $elements['data'] = [ '#theme' => 'site_commerce_cost_default_formatter', '#values' => $values, ]; return $elements; }
{@inheritdoc}
entailment
public function update($path, $contents, Config $config) { $location = $this->applyPathPrefix($path); $mimetype = Util::guessMimeType($path, $contents); if (($size = file_put_contents($location, $contents)) === false) { return false; } return compact('path', 'size', 'contents', 'mimetype'); }
{@inheritdoc}
entailment
public function removePathPrefix($path) { if ($this->getPathPrefix() === null) { return $path; } $length = strlen($this->getPathPrefix()); return substr($path, $length); }
{@inheritdoc}
entailment
protected function wrapPath($path) { $scheme = $this->vfs->scheme().'://'; $path = str_replace($scheme, null, $path); return $scheme.$path; }
@param string $path @return string
entailment
public static function extractDomainFromToken($auth_token) { $token_info = (array) static::parse($auth_token); $username = isset($token_info['username']) ? (string) $token_info['username'] : null; if (mb_strlen($username) >= 3 && mb_strpos($username, '@') !== false) { if (($domain = mb_substr($username, mb_strpos($username, '@') + 1)) && mb_strlen($domain) >= 1) { return $domain; } } }
Извлекает имя домена из токена авторизации (если он в нем присутствует и токен корректный). @param string $auth_token @return string|null
entailment
public static function extractUsernameFromToken($auth_token) { $token_info = (array) static::parse($auth_token); $username = isset($token_info['username']) ? (string) $token_info['username'] : null; if (\is_string($username) && mb_strlen($username) >= 1) { if (mb_strpos($username, '@') !== false) { $just_username = mb_substr($username, 0, mb_strpos($username, '@')); if (mb_strlen($just_username) >= 1) { return $just_username; } } else { return $username; } } }
Извлекает имя пользователя из токена авторизации (если он в нем присутствует и токен корректный). Внимение! Извлекается имя пользователя без значения домена. @param string $auth_token @return string|null
entailment
public static function parse($auth_token) { if (! empty($auth_token) && \is_string($auth_token)) { // Проверяем наличие префикса в токене if (mb_strpos($auth_token, trim(static::TOKEN_PREFIX)) !== false) { // Удаляем префикс $auth_token = trim(str_replace(static::TOKEN_PREFIX, '', $auth_token)); } // Разбираем токен на части $parts = explode(':', base64_decode($auth_token, true)); $username = isset($parts[0]) ? $parts[0] : null; $timestamp = isset($parts[1]) ? $parts[1] : null; $age = isset($parts[2]) ? $parts[2] : null; $salted_hash = isset($parts[3]) ? $parts[3] : null; // И проверяем их if (\is_string($username) && \is_numeric($timestamp) && \is_numeric($age) && \is_string($salted_hash)) { return [ 'username' => $username, 'timestamp' => (int) $timestamp, 'age' => (int) $age, 'salted_hash' => $salted_hash, ]; } } return false; }
{@inheritdoc} Пример структуры возвращаемого массива: <code> [ 'username' => '%username%', 'timestamp' => '%1234567890%', 'age' => '%1234567890%', 'salted_hash' => '%salted_hash%', ] </code>
entailment
public static function generate($username, $password, $domain = null, $age = 172800, $timestamp = null) { static $stack = []; // Время генерации токена отматываем на сутки назад, дабы покрыть возможную разницу в часовых поясах $timestamp = empty($timestamp) ? Carbon::now()->subHours(24)->getTimestamp() : (int) $timestamp; $stack_hash = 'item_' . crc32($username . $domain . $password . $age . $timestamp); if (isset($stack[$stack_hash])) { return $stack[$stack_hash]; } else { $pass_hash = base64_encode(md5($password, true)); $salted_hash = base64_encode(md5(implode(':', [$timestamp, $age, $pass_hash]), true)); $token = static::TOKEN_PREFIX . base64_encode( implode(':', [ empty($domain) ? $username : sprintf('%s@%s', $username, $domain), $timestamp, $age, $salted_hash, ]) ); $stack[$stack_hash] = $token; } return $stack[$stack_hash]; }
Метод генерации токена авторизации. По умолчанию токен генерируется со временем жизни - 1 сутки. @param string $username Имя пользователя @param string $password Пароль пользователя @param string|null $domain Домен пользователя @param int $age Время жизни токена (unix-time, в секундах) @param int|null $timestamp Временная метка (unix-time, начала жизни токена) @return string
entailment
public function boot() { $finder = $this->app->make('orchestra.extension.finder'); foreach ($this->extensions as $name => $path) { if (\is_numeric($name)) { $finder->addPath($path); } else { $finder->registerExtension($name, $path); } } }
Bootstrap the application events. @return void
entailment
public function request($method, $uri, array $data = [], array $headers = []) { $method = \mb_strtoupper(trim((string) $method)); // Если использует GET-запрос, то передаваемые данные клиент вставит в сам запрос. Если же POST или PUT - то // данные будут переданы в теле самого запроса $query = $method === 'GET' ? $data : null; $body = \in_array($method, ['PUT', 'POST', 'DELETE'], true) && $data !== [] ? \json_encode($data) : null; $headers = array_replace_recursive([ 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'User-Agent' => $this->getUserAgentName(), ], $headers); $this->fire('before_request', $method, $uri, $body, $headers); $response = $this->endsWith($uri, 'just/for/internal/test') ? new Response(200, ['X-Fake' => true], '["Just for a test"]') : $this->http_client->request($method, (string) $uri, [ 'query' => $query, 'body' => $body, 'headers' => $headers, ]); $this->fire('after_request', $response); return $response; }
{@inheritdoc}
entailment
protected function endsWith($haystack, $needle) { $length = \mb_strlen($needle); return $length === 0 || (\mb_substr($haystack, -$length) === $needle); }
Возвращает true, если строка заканчивается подстрокой $needle. @param string $haystack @param string $needle @return bool
entailment
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $element = []; $element['visible'] = array( '#type' => 'select', '#title' => $this->t('Display form add to cart'), '#options' => array('0' => $this->t('Disallow'), '1' => $this->t('Allow')), '#default_value' => isset($items[$delta]->visible) ? $items[$delta]->visible : '1', '#theme_wrappers' => [], ); $element['event'] = array( '#type' => 'select', '#title' => $this->t('Event after adding to cart'), '#options' => getEventAddCart(), '#default_value' => isset($items[$delta]->event) ? $items[$delta]->event : 'load_open_cart_form', '#theme_wrappers' => [], ); $element['label_add'] = array( '#type' => 'textfield', '#title' => $this->t('Button name adding to cart'), '#default_value' => isset($items[$delta]->label_add) ? $items[$delta]->label_add : $this->t('Add to cart'), '#maxlength' => 255, '#theme_wrappers' => [], ); $element['label_click'] = array( '#type' => 'textfield', '#title' => $this->t('Button name purchase in one click'), '#default_value' => isset($items[$delta]->label_click) ? $items[$delta]->label_click : $this->t('Purchase in one click'), '#maxlength' => 255, '#theme_wrappers' => [], ); $element['description'] = array( '#type' => 'textarea', '#title' => $this->t('Note on the form of adding to cart'), '#default_value' => isset($items[$delta]->description) ? $items[$delta]->description : null, ); $element['#theme'] = 'site_commerce_cart_default_widget'; return $element; }
{@inheritdoc}
entailment
public function flush(): void { $this->booted = false; $this->config = null; $this->widget = null; $this->services = [ 'acl' => null, 'memory' => null, 'menu' => null, ]; }
Flush the container of all bindings and resolved instances. @return void
entailment
public function widget(string $type) { return ! \is_null($this->widget) ? $this->widget->make("{$type}.orchestra") : null; }
Get widget services by type. @param string $type @return \Orchestra\Widget\Handler|null
entailment
public function namespaced($namespace, $attributes = [], Closure $callback = null): void { if ($attributes instanceof Closure) { $callback = $attributes; $attributes = []; } if (! empty($namespace) && $namespace != '\\') { $attributes['namespace'] = $namespace; } $attributes['middleware'] = \array_unique(\array_merge( $attributes['middleware'] ?? [], ['orchestra'] )); $this->group('orchestra/foundation', 'orchestra', $attributes, $callback); }
Register the given Closure with the "group" function namespace set. @param string|null $namespace @param array|\Closure $attributes @param \Closure|null $callback @return void
entailment
public function route(string $name, string $default = '/'): UrlGenerator { // Boot the application. $this->boot(); return parent::route($name, $default); }
Get extension route. @param string $name @param string $default @return \Orchestra\Contracts\Extension\UrlGenerator
entailment
protected function bootApplication(): void { $this->registerBaseServices(); try { $memory = $this->bootInstalledApplication(); } catch (Exception $e) { $memory = $this->bootNewApplication(); } $this->services['memory'] = $memory; $this->app->instance('orchestra.platform.memory', $memory); $this->registerComponents($memory); $this->app->make('events')->dispatch('orchestra.started', [$memory]); }
Boot application. @return void
entailment
protected function bootInstalledApplication(): MemoryProvider { // Initiate Memory class from App, this to allow advanced user // to use other implementation if there is a need for it. $memory = $this->app->make('orchestra.memory')->make(); $name = $memory->get('site.name'); if (\is_null($name)) { throw new Exception('Installation is not completed'); } $this->config->set('app.name', $name); // In event where we reach this point, we can consider no // exception has occur, we should be able to compile acl and // menu configuration $this->acl()->attach($memory); // In any event where Memory failed to load, we should set // Installation status to false routing for installation is // enabled. $this->app->instance('orchestra.installed', true); $this->createAdminMenu(); return $memory; }
Run booting on installed application. @throws \Exception @return \Orchestra\Contracts\Memory\Provider
entailment
protected function bootNewApplication(): MemoryProvider { // In any case where Exception is catched, we can be assure that // Installation is not done/completed, in this case we should // use runtime/in-memory setup $memory = $this->app->make('orchestra.memory')->make('runtime.orchestra'); $memory->put('site.name', $this->config->get('app.name', 'Orchestra Platform')); $this->menu()->add('install') ->title('Install') ->link($this->handles('orchestra::install')) ->icon('power-off'); $this->app->instance('orchestra.installed', false); return $memory; }
Run booting on new application. @return \Orchestra\Contracts\Memory\Provider
entailment
protected function createAdminMenu(): void { $menu = $this->menu(); $events = $this->app->make('events'); $handlers = [ UserMenuHandler::class, ExtensionMenuHandler::class, SettingMenuHandler::class, ]; $menu->add('home') ->title(\trans('orchestra/foundation::title.home')) ->link($this->handles('orchestra::/')) ->icon('home'); foreach ($handlers as $handler) { $events->listen('orchestra.started: admin', $handler); } }
Create Administration Menu for Orchestra Platform. @return void
entailment
protected function registerBaseServices(): void { $this->services['acl'] = $this->app->make('orchestra.acl')->make('orchestra'); $this->app->instance('orchestra.platform.acl', $this->services['acl']); $this->services['menu'] = $this->widget('menu'); $this->app->instance('orchestra.platform.menu', $this->services['menu']); }
Register base application services. @return void
entailment
protected function registerComponents(MemoryProvider $memory): void { $this->app->make('orchestra.notifier')->setDefaultDriver('orchestra'); $this->app->make('orchestra.mail')->attach($memory); }
Register base application components. @param \Orchestra\Contracts\Memory\Provider $memory @return void
entailment
public static function forge(RequestInterface $request) { $headerSize = $request->getInfo(CURLINFO_HEADER_SIZE); $response = $request->getRawResponse(); $content = (strlen($response) === $headerSize) ? '' : substr($response, $headerSize); $rawHeaders = rtrim(substr($response, 0, $headerSize)); $headers = []; foreach (preg_split('/(\\r?\\n)/', $rawHeaders) as $header) { if ($header) { $headers[] = $header; } else { $headers = []; } } $headerBag = []; $info = $request->getInfo(); $status = explode(' ', $headers[0]); $status = explode('/', $status[0]); unset($headers[0]); foreach ($headers as $header) { $headerPair = explode(': ', $header); if (count($headerPair) > 1) { list($key, $value) = $headerPair; $headerBag[trim($key)] = trim($value); } } $response = new static($content, $info['http_code'], $headerBag); $response->setProtocolVersion($status[1]); $response->setCharset(substr(strstr($response->headers->get('Content-Type'), '='), 1)); return $response; }
Forge a new object based on a request. @param RequestInterface $request @return Response
entailment
public function parseEXCEL() { # Создаем массив для данных EXCEL. $items = []; require_once 'libraries/PHPExcel/Classes/PHPExcel/IOFactory.php'; $path = drupal_realpath($this->file->getFileUri()); $objPHPExcel = \PHPExcel_IOFactory::load($path); $objPHPExcel->setActiveSheetIndex(0); $objSheet = $objPHPExcel->getActiveSheet(); // Обрабатываем каждую строку. foreach ($objSheet->getRowIterator() as $rkey => $row) { $cellIterator = $row->getCellIterator(); foreach ($cellIterator as $ckey => $cell) { $items[$rkey][] = trim($cell->getCalculatedValue()); } } if ($this->skip_first_line) { unset($items[1]); } # После того как распарсили файл в массив, мы разбиваем его на кусочки. $chunks = array_chunk($items, $this->chunk_size); # Теперь каждый кусок устанавливаем на выполнение. foreach ($chunks as $chunk) { $this->setOperation($chunk); } }
{@inheritdoc} В данном методе мы обрабатываем наш EXCEL строка за строкой, а не грузим весь файл в память, так что данный способ значительно менее затратный и более шустрый. Каждую строку мы получаем в виде массива, а массив передаем в операцию на выполнение.
entailment
public static function processItem($data, &$context) { $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId(); $db = \Drupal::database(); foreach ($data as $item) { $title = trim($item[3]); // Загружаем термин таксономии. $term = ''; if ($item[2]) { $terms = taxonomy_term_load_multiple_by_name(trim($item[2]), 'site_commerce'); $term = reset($terms); } if (is_object($term)) { $site_commerce_data = array( 'type' => 'product', 'title' => $title, 'langcode' => $langcode, 'uid' => 1, 'status' => 1, 'field_body' => array( 'value' => $item[4], 'format' => 'basic_html', ), 'field_category' => array( 'target_id' => $term->id(), ), 'field_code' => array(trim($item[1])), 'field_cost' => array( 'group' => 1, 'prefix' => '', 'from' => round($item[5], 2), 'value' => round($item[6], 2), 'currency' => 'руб.', 'suffix' => '', ), ); // Create file object from remote URL. $path = 'http://www.sidingmarket.ru/sites/default/files/pictures/site_commerce/' . $item[8]; $file_contents = file_get_contents($path); if ($file_contents) { $pathinfo = pathinfo($path); $query = $db->select('file_managed', 'n'); $query->addExpression('MAX(fid)', 'max_fid'); $max_fid = $query->execute()->fetchField(); // Формирует имя файла. $path = \Drupal::service('pathauto.alias_cleaner')->cleanstring($title); $path = \Drupal::transliteration()->transliterate($path, $langcode); $filename = $path . '_' . $max_fid . '.' . $pathinfo['extension']; // Удаление пробелов. $filename = str_replace(' ', '-', $filename); // Удаление не безопасных символов. $filename = preg_replace('![^0-9A-Za-z_.-]!', '', $filename); // Удаление символов не алфавита. $filename = preg_replace('/(_)_+|(\.)\.+|(-)-+/', '\\1\\2\\3', $filename); // Преобразование. $filename = Unicode::strtolower($filename); $destination = 'public://images/products/' . $filename; // Проверка длины пути файла не более 255 символов. if (Unicode::strlen($destination) > 255) { $pathinfo = pathinfo($destination); $destination = Unicode::substr($destination, 0, 254 - Unicode::strlen($pathinfo['extension'])) . ".{$pathinfo['extension']}"; } $file = file_save_data($file_contents, $destination, FILE_EXISTS_RENAME); $site_commerce_data += [ 'field_image' => array( 'target_id' => $file->id(), 'alt' => $title, ), ]; } $site_commerce = \Drupal\site_commerce\Entity\SiteCommerce::create($site_commerce_data); $site_commerce->save(); } # Записываем результат в общий массив результатов batch операции. По этим # данным мы будем выводить кол-во импортированных данных. $context['results'][] = $title; $context['message'] = $title; } }
{@inheritdoc} Обработка элемента (строки из файла). В соответствии со столбцами и их порядком мы получаем их данные в переменные. И не забываем про $context.
entailment
public function cartBlock($pid) { $site_commerce = $this->entityTypeManager->getStorage('site_commerce')->load($pid); // Проверяем добавлена ли текущая позиция в корзину. $position_in_cart = FALSE; $databaseSendOrder = \Drupal::service('site_orders.database'); if ($databaseSendOrder->hasPositionInCart($site_commerce->getEntityTypeId(), $site_commerce->id())) { $position_in_cart = TRUE; } // Тип отображения. $type = 'default'; if ($position_in_cart) { // Доступные варианты: default, load_open_cart_form, load_order_form, load_message_form. $type = $site_commerce->get('field_cart')->event; } return [ '#theme' => 'site_commerce_cart_block', '#site_commerce' => $site_commerce, '#type' => $type, ]; }
Callback lazy builder for to cart block. @param [int] $pid @return array
entailment
public function parametrsBlock($id) { $databaseSendOrder = \Drupal::service('site_orders.database'); $site_commerce = \Drupal::entityTypeManager()->getStorage('site_commerce')->load($id); $items = $site_commerce->get('field_parametrs')->getValue(); $values = []; foreach ($items as $delta => $item) { $item = (object) $item; $hasParametrInCart = $databaseSendOrder->hasPositionInCart('site_commerce_parametr', $id, $delta); // Если передан объект товара. if ($item->target_id) { $position = \Drupal::entityTypeManager()->getStorage('site_commerce')->load($item->target_id); if ($position) { // Формируем стоимость позиции. $group = 1; $cost = getCostValueForUserPriceGroup($position, $group, FALSE, FALSE); $values[$delta] = array( 'id' => $id, 'target_id' => $item->target_id, 'position' => $position, 'site_commerce' => $site_commerce, 'name' => $item->name, 'description' => $item->description, 'min' => $position->field_quantity->min, 'unit' => $position->field_quantity->unit, 'cost' => $cost['value'], 'currency' => $cost['currency'], 'select' => $item->select, 'in_cart' => $hasParametrInCart, ); } } else { $values[$delta] = array( 'id' => $id, 'target_id' => $item->target_id, 'position' => NULL, 'site_commerce' => $site_commerce, 'name' => $item->name, 'description' => $item->description, 'min' => $item->min, 'unit' => $item->unit, 'cost' => \Drupal::service('kvantstudio.formatter')->price($item->cost), 'currency' => $item->currency, 'select' => $item->select, 'in_cart' => $hasParametrInCart, ); } } return [ '#theme' => 'site_commerce_parametrs_default_formatter', '#values' => $values, '#attached' => array( 'library' => array( 'site_commerce/product_parametrs', 'site_orders/module', ), ), ]; }
Callback lazy builder for parametrs block. @param [array] $values @return array
entailment
public static function cols( $cache = true ) { static $cols = false; if( !$cols || !$cache ) { $cols = intval(`tput cols`); } return $cols ? : 80; } /** * The row size of the current terminal as returned by tput * * @staticvar bool|int $rows the cached value for the number of columns * @param bool $cache Whether to cache the response * @return int */ public static function rows( $cache = true ) { static $rows = false; if( !$rows || !$cache ) { $rows = intval(`tput lines`); } return $rows ? : 24; }
The col size of the current terminal as returned by tput @staticvar bool|int $cols the cached value for the number of columns @param bool $cache Whether to cache the response @return int
entailment
public function createProfileFailed(array $errors) { messages('error', trans('orchestra/foundation::response.db-failed', $errors)); return $this->redirect($this->getRedirectToRegisterPath())->withInput(); }
Response when create a user failed. @param array $errors @return mixed
entailment
public function toMail($notifiable) { $email = $notifiable->getEmailForPasswordReset(); $expired = \config("auth.passwords.{$this->provider}.expire", 60); $url = \config('orchestra/foundation::routes.reset', 'orchestra::forgot/reset'); $title = \trans('orchestra/foundation::email.forgot.title'); $message = new MailMessage(); $message->title($title) ->level('warning') ->line(\trans('orchestra/foundation::email.forgot.message.intro')) ->action($title, \handles("{$url}/{$this->token}?email=".\urlencode($email))) ->line(\trans('orchestra/foundation::email.forgot.message.expired_in', \compact('expired'))) ->line(\trans('orchestra/foundation::email.forgot.message.outro')); if (! \is_null($view = \config("auth.passwords.{$this->provider}.email"))) { $message->view($view, [ 'email' => $email, 'fullname' => $notifiable->getRecipientName(), ]); } return $message; }
Get the notification message for mail. @param mixed $notifiable @return \Orchestra\Notifications\Messages\MailMessage
entailment
public function info($auth_token) { return new B2BResponse($this->client->apiRequest( 'get', 'user', null, [ 'Authorization' => (string) $auth_token, ], $this->client->isTest() ? new Response( 200, $this->getTestingResponseHeaders(), str_replace( [ '%domain%', '%username%', ], [ AuthToken::extractDomainFromToken($auth_token), AuthToken::extractUsernameFromToken($auth_token), ], file_get_contents(__DIR__ . '/user.json') ) ) : null )); }
Информация о текущем пользователе. @param string $auth_token Токен безопасности @throws B2BApiException @return B2BResponse
entailment
public function balance($auth_token, $report_type_uid, $detailed = false) { return new B2BResponse($this->client->apiRequest( 'get', sprintf('user/balance/%s', urlencode($report_type_uid)), [ '_detailed' => (bool) $detailed ? 'true' : 'false', ], [ 'Authorization' => (string) $auth_token, ], $this->client->isTest() ? new Response( 200, $this->getTestingResponseHeaders(), str_replace( [ '%domain%', '%default_report_type_uid%', ], [ AuthToken::extractDomainFromToken($auth_token), $report_type_uid, ], file_get_contents(__DIR__ . '/balance.json') ) ) : null )); }
Проверка доступности квоты по UID-у типа отчета. @param string $auth_token Токен безопасности @param string $report_type_uid UID типа отчета @param bool $detailed @throws B2BApiException @return B2BResponse
entailment
public function showResetForm($token = null) { if (is_null($token)) { return $this->showLinkRequestForm(); } $email = Request::input('email'); set_meta('title', trans('orchestra/foundation::title.reset-password')); return view('orchestra/foundation::forgot.reset', compact('email', 'token')); }
Once user actually visit the reset my password page, we now should be able to make the operation to create a new password. GET (:orchestra)/forgot/reset/(:hash) @param string $token @return mixed
entailment
public function reset(Processor $processor) { $input = Request::only('email', 'password', 'password_confirmation', 'token'); return $processor->update($this, $input); }
Create a new password for the user. POST (:orchestra)/forgot/reset @param \Orchestra\Foundation\Processors\Account\PasswordBroker $processor @return mixed
entailment
public function passwordResetHasFailed($response) { $message = trans($response); $token = Request::input('token'); return $this->redirectWithMessage(handles("orchestra::forgot/reset/{$token}"), $message, 'error'); }
Response when reset password failed. @param string $response @return mixed
entailment
public function toCleanString() : string { $path = array_filter($this->path, function ($val) { return $val != Structure::ARRAY_NAME; }); return implode('.', $path); }
Convert path to user-display string. @return string
entailment
public function addChild(string $key) : NodePath { $path = $this->path; $path[] = $key; return new NodePath($path); }
Return new path with an added child. @param string $key @return NodePath
entailment
public function popFirst(&$first) : NodePath { $path = $this->path; $first = array_shift($path); return new NodePath($path); }
Remove the first item from path and return new path @param string $first @return NodePath
entailment
public function edit(SettingUpdateListener $listener) { // Orchestra settings are stored using Orchestra\Memory, we need to // fetch it and convert it to Fluent (to mimick Eloquent properties). $memory = $this->memory; $eloquent = new Fluent([ 'site_name' => $memory->get('site.name', ''), 'site_description' => $memory->get('site.description', ''), 'site_registrable' => ($memory->get('site.registrable', false) ? 'yes' : 'no'), 'email_driver' => $memory->get('email.driver', ''), 'email_address' => $memory->get('email.from.address', ''), 'email_host' => $memory->get('email.host', ''), 'email_port' => $memory->get('email.port', ''), 'email_username' => $memory->get('email.username', ''), 'email_password' => $memory->secureGet('email.password', ''), 'email_encryption' => $memory->get('email.encryption', ''), 'email_sendmail' => $memory->get('email.sendmail', ''), 'email_queue' => ($memory->get('email.queue', false) ? 'yes' : 'no'), 'email_key' => $memory->secureGet('email.key', ''), 'email_secret' => $memory->secureGet('email.secret', ''), 'email_domain' => $memory->get('email.domain', ''), 'email_region' => $memory->get('email.region', ''), ]); $form = $this->presenter->form($eloquent); Event::dispatch('orchestra.form: settings', [$eloquent, $form]); return $listener->showSettingChanger(compact('eloquent', 'form')); }
View setting page. @param \Orchestra\Contracts\Foundation\Listener\SettingUpdater $listener @return mixed
entailment
public function update(SettingUpdateListener $listener, array $input) { $input = new Fluent($input); $driver = $this->getValue($input['email_driver'], 'mail.driver'); $validation = $this->validator->on($driver)->with($input->toArray()); if ($validation->fails()) { return $listener->settingFailedValidation($validation->getMessageBag()); } $memory = $this->memory; $memory->put('site.name', $input['site_name']); $memory->put('site.description', $input['site_description']); $memory->put('site.registrable', ($input['site_registrable'] === 'yes')); $memory->put('email.driver', $driver); $memory->put('email.from', [ 'address' => $this->getValue($input['email_address'], 'mail.from.address'), 'name' => $input['site_name'], ]); if ((empty($input['email_password']) && $input['enable_change_password'] === 'no')) { $input['email_password'] = $memory->secureGet('email.password'); } if ((empty($input['email_secret']) && $input['enable_change_secret'] === 'no')) { $input['email_secret'] = $memory->secureGet('email.secret'); } $memory->put('email.host', $this->getValue($input['email_host'], 'mail.host')); $memory->put('email.port', $this->getValue($input['email_port'], 'mail.port')); $memory->put('email.username', $this->getValue($input['email_username'], 'mail.username')); $memory->securePut('email.password', $this->getValue($input['email_password'], 'mail.password')); $memory->put('email.encryption', $this->getValue($input['email_encryption'], 'mail.encryption')); $memory->put('email.sendmail', $this->getValue($input['email_sendmail'], 'mail.sendmail')); $memory->put('email.queue', ($input['email_queue'] === 'yes')); $memory->securePut('email.key', $this->getValue($input['email_key'], "services.{$driver}.key")); $memory->securePut('email.secret', $this->getValue($input['email_secret'], "services.{$driver}.secret")); $memory->put('email.domain', $this->getValue($input['email_domain'], "services.{$driver}.domain")); $memory->put('email.region', $this->getValue($input['email_region'], "services.{$driver}.region")); Event::dispatch('orchestra.saved: settings', [$memory, $input]); return $listener->settingHasUpdated(); }
Update setting. @param \Orchestra\Contracts\Foundation\Listener\SettingUpdater $listener @param array $input @return mixed
entailment
private function getValue($input, $alternative) { if (empty($input)) { $input = Config::get($alternative); } return $input; }
Resolve value or grab from configuration. @param mixed $input @param string $alternative @return mixed
entailment
public static function preDelete(EntityStorageInterface $storage, array $entities) { parent::preDelete($storage, $entities); // Ensure that all products deleted are removed from the search index. if (\Drupal::moduleHandler()->moduleExists('search')) { foreach ($entities as $entity) { search_index_clear('site_commerce_search', $entity->pid->value); } } }
{@inheritdoc}
entailment
public function handle($request, Closure $next, ?string $action = null) { if (! $this->authorize($action)) { return $this->responseOnUnauthorized($request); } return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @param string|null $action @return mixed
entailment
protected function authorize(?string $action = null): bool { if (empty($action)) { return false; } return $this->foundation->acl()->can($action); }
Check authorization. @param string|null $action @return bool
entailment
protected function responseOnUnauthorized($request) { if ($request->ajax()) { return $this->response->make('Unauthorized', 401); } $type = ($this->auth->guest() ? 'guest' : 'user'); $url = $this->config->get("orchestra/foundation::routes.{$type}"); return $this->response->redirectTo($this->foundation->handles($url)); }
Response on authorized request. @param \Illuminate\Http\Request $request @return mixed
entailment
public function reauth(Request $request, AccountValidator $validator) { $validation = $validator->on('reauthenticate')->with($request->only(['password'])); if ($validation->fails()) { return $this->userReauthenticateHasFailedValidation($validation->getMessageBag()); } elseif (! (new ReauthLimiter($request))->attempt($request->input('password'))) { return $this->userHasFailedReauthentication(); } return $this->userHasReauthenticated(); }
Handle the reauthentication request to the application. @param \Illuminate\Http\Request $request @param \Orchestra\Foundation\Validations\Account $validator @return mixed
entailment
public function processNode(Node $node, Scope $scope): array { $className = $node->value; if (isset($className[0]) && '\\' === $className[0]) { $className = \substr($className, 1); } $messages = []; if (! \preg_match('/^\\w.+\\w$/u', $className)) { return $messages; } if (! $this->broker->hasClass($className)) { return $messages; } $classRef = $this->broker->getClass($className)->getNativeReflection(); if ($classRef->isInternal() && $classRef->getName() !== $className) { return $messages; } return [ \sprintf('Class %s should be written with ::class notation, string found.', $className), ]; }
@param \PhpParser\Node\Scalar\String_ $node @param \PHPStan\Analyser\Scope $scope @return string[] errors
entailment
public function processItem($data) { if ($data['id']) { $result = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['field_code' => ['value' => $data['id']]]); $term = reset($result); // Если категория не найдена. if (!$term) { // Создаем новый термин. $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId(); $term = [ 'name' => $data['name'], 'vid' => 'site_commerce', 'langcode' => $langcode, 'parent' => [0], 'field_view' => [ 'value' => $data['published'], ], 'field_code' => [ 'value' => $data['id'], ], ]; // Определяем термин родитель по артикулу. // TODO: Важно в файле импорта соблюдать порядок следования категорий, дочерние должны быть ниже!!! $parent = $data['parent']; if ($parent) { $result = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['field_code' => ['value' => $parent]]); $term_parent = reset($result); if ($term_parent) { $term['parent'] = [$term_parent->id()]; } } $term = Term::create($term); $term->save(); // Фиксируем в журнале событий процесс регистрации. // \Drupal::logger('site_commerce_catalog_import')->notice('Создана категория - ' . $term->getName()); } else { $term = Term::load($term->id()); $term->name->setValue($data['name']); $term->field_view->setValue(['value' => $data['published']]); // Определяем термин родитель по артикулу. $parent = $data['parent']; if ($parent) { $result = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['field_code' => ['value' => $parent]]); $term_parent = reset($result); if ($term_parent) { $term->parent->setValue([$term_parent->id()]); } } $term->save(); // Фиксируем в журнале событий процесс регистрации. // \Drupal::logger('site_commerce_catalog_import')->notice('Обновлена категория - ' . $term->getName()); } } }
{@inheritdoc}
entailment
public function migrationHasSucceed(Fluent $extension) { $message = trans('orchestra/foundation::response.extensions.migrate', $extension->getAttributes()); return $this->redirectWithMessage(handles('orchestra::extensions'), $message); }
Response when extension migration has succeed. @param \Illuminate\Support\Fluent $extension @return mixed
entailment
public function getAttributes() { $attributes = $this->attributes(); $fields = $this->getFields(); $interfaces = $this->interfaces(); $attributes = array_merge($this->attributes, [ 'fields' => $fields ], $attributes); if(sizeof($interfaces)) { $attributes['interfaces'] = $interfaces; } return $attributes; }
Get the attributes from the container. @return array
entailment
public function getSourceByName($source_name) { if ($this->hasSourceName($source_name)) { foreach ($this->sources() as $source) { if ($source->getName() === $source_name) { return $source; } } } }
Возвращает объект данных по источнику, извлекая его по имени. В случае его отсутствия вернется null. @param string $source_name @return ReportSource|null
entailment
public function getSourcesNames() { static $result = []; if (empty($result)) { foreach ($this->sources() as $source) { $result[] = $source->getName(); } } return $result; }
Возвращает массив имен всех источников, что были запрошены в отчете. @return string[]|array
entailment
public function getField($path, $default = null) { if (($current = $this->getContent()) && \is_array($current)) { $p = strtok((string) $path, '.'); while ($p !== false) { if (! isset($current[$p])) { return $default; } $current = $current[$p]; $p = strtok('.'); } } return $current; }
Возвращает значения из КОНТЕНТА отчета, обращаясь к нему с помощью dot-нотации. Для более подробной смотри спецификацию по филдам. @param string $path @param mixed|null $default @return array|mixed|null
entailment
public function on($event_type, Closure $callback) { $event_type = (string) $event_type; // Инициализируем стек if (! isset($this->callbacks[$event_type])) { $this->callbacks[$event_type] = []; } $this->callbacks[$event_type][] = $callback; return $this; }
Добавляет именованное событие в стек. @param string $event_type По умолчанию: 'before_request', 'after_request' @param Closure $callback @return static|self
entailment
public function fire($event_type, ...$arguments) { $event_type = (string) $event_type; if (isset($this->callbacks[$event_type])) { foreach ($this->callbacks[$event_type] as &$callback) { $callback(...$arguments); } } }
Выполняет все события, что были помещены в именованный стек. @param string $event_type По умолчанию: 'before_request', 'after_request' @param array ...$arguments
entailment
public function getUserAgentName() { static $user_agent_name = ''; if (empty($user_agent_name)) { $user_agent_name = 'B2BApi Client/' . $this->api_client->getClientVersion() . ' curl/' . \curl_version()['version'] . ' PHP/' . PHP_VERSION; } return $user_agent_name; }
Возвращает строку User-Agent, используемую по умолчанию. @return string
entailment
protected function redirectUserTo(string $namespace, string $path, ?string $redirect = null): string { return \handles($this->redirectUserPath($namespace, $path, $redirect)); }
Get redirection handles. @param string $namespace @param string $path @param string|null $redirect @return string
entailment
protected function redirectUserPath(string $namespace, string $path, ?string $redirect = null): string { if (! empty($redirect)) { $path = $redirect; } $property = \sprintf('redirect%sPath', Str::ucfirst($namespace)); return \property_exists($this, $property) ? $this->{$property} : $path; }
Get redirection path. @param string $namespace @param string $path @param string|null $redirect @return string
entailment
public function processItem($data) { // Если импорт категорий завершен. $queue = \Drupal::queue('site_commerce_catalog_import'); if (!$queue->numberOfItems()) { $database = Database::getConnection(); // Получаем переменные. $code = trim($data['code']); $catalog_number = trim($data['catalog_number']); $category_name = trim($data['category_name']); $title = Html::escape(trim($data['title'])); $description = trim($data['description']); $quantity = (int) trim($data['quantity']); $cost_group_1 = round(trim($data['cost_group_1']), 2); $status = (int) trim($data['status']); $images = trim($data['images']); if ($code) { $result = \Drupal::entityTypeManager()->getStorage('site_commerce')->loadByProperties(['field_code' => ['value' => $code]]); $site_commerce = reset($result); // Если товар не найден. if (!$site_commerce) { // Создаем новый товар. $langcode = \Drupal::languageManager()->getCurrentLanguage()->getId(); // Загружаем термин таксономии. // Если удалось определить категорию создаем товар. $categories = explode("|", $category_name); $name = array_pop($categories); $terms = taxonomy_term_load_multiple_by_name($name, 'site_commerce'); $term = reset($terms); if (is_object($term)) { $site_commerce_data = array( 'type' => 'product', 'title' => $title, 'langcode' => $langcode, 'uid' => 1, 'status' => $status, 'field_summary' => array( 'value' => $description, 'format' => 'basic_html', ), 'field_category' => array( 'target_id' => $term->id(), ), 'field_code' => array($code), 'field_cost' => array( 'group' => 1, 'prefix' => '', 'from' => '0.00', 'value' => $cost_group_1, 'currency' => 'руб.', 'suffix' => '', ), 'field_quantity' => [ 'stock' => $quantity, ], ); // Создаем папку для хранения изображений товаров. $images_array = explode("|", $images); foreach ($images_array as $image) { $path = 'public://import/images/' . $image; if ($image && file_exists($path)) { $file_contents = file_get_contents($path); if ($file_contents) { $pathinfo = pathinfo($path); $query = $database->select('file_managed', 'n'); $query->addExpression('MAX(fid)', 'max_fid'); $max_fid = $query->execute()->fetchField(); // Формирует имя файла. $path = \Drupal::service('pathauto.alias_cleaner')->cleanstring($title); $path = \Drupal::transliteration()->transliterate($path, $langcode); $filename = $path . '_' . $max_fid . '.' . $pathinfo['extension']; // Удаление пробелов. $filename = str_replace(' ', '-', $filename); // Удаление не безопасных символов. $filename = preg_replace('![^0-9A-Za-z_.-]!', '', $filename); // Удаление символов не алфавита. $filename = preg_replace('/(_)_+|(\.)\.+|(-)-+/', '\\1\\2\\3', $filename); // Преобразование. $filename = Unicode::strtolower($filename); $destination = 'public://images/products/' . $filename; // Проверка длины пути файла не более 255 символов. if (Unicode::strlen($destination) > 255) { $pathinfo = pathinfo($destination); $destination = Unicode::substr($destination, 0, 254 - Unicode::strlen($pathinfo['extension'])) . ".{$pathinfo['extension']}"; } // Перемещаем файл изображения в папку назначения. $file = file_save_data($file_contents, $destination, FILE_EXISTS_RENAME); if ($file) { $site_commerce_data += [ 'field_image' => array( 'target_id' => $file->id(), 'alt' => $title, ), ]; } } } } // Сохраняем товар. $site_commerce = \Drupal\site_commerce\Entity\SiteCommerce::create($site_commerce_data); $site_commerce->save(); } // Фиксируем в журнале событий процесс регистрации. // \Drupal::logger('site_commerce_products_import')->notice('Создан товар - ' . $site_commerce->getTitle()); } else { $site_commerce->title->setValue($title); $site_commerce->status->setValue($status); $site_commerce->field_summary->setValue(['value' => $description]); $site_commerce->field_code->setValue(['value' => $code]); $site_commerce->field_cost->setValue(['group' => 1, 'value' => $cost_group_1]); $site_commerce->save(); // Фиксируем в журнале событий процесс регистрации. // \Drupal::logger('site_commerce_products_import')->notice('Обновлен товар - ' . $site_commerce->getTitle()); } } } }
{@inheritdoc}
entailment
public function buildForm(array $form, FormStateInterface $form_state, $pid = 0, $cid = 0) { $form['#theme'] = 'site_commerce_product_characteristic_add_form'; // Получаем объект товара. $site_commerce = \Drupal::entityTypeManager()->getStorage('site_commerce'); $position = $site_commerce->load($pid); $form['position'] = array( '#type' => 'hidden', '#value' => $position, ); // Получаем объект характеристики товара. $characteristic = $this->database->characteristicsReadItem($cid); $form['characteristic'] = array( '#type' => 'hidden', '#value' => $characteristic, ); // Характеристика с данными о привязке к товару. $characteristic_data = $this->database->characteristicDataReadItem($pid, $cid); $this->wrapper = 'characteristic-wrapper'; $form['gid'] = [ '#type' => 'select', '#title' => $this->t('Group'), '#options' => $this->database->characteristicsReadGroupsByCategory($position->field_category->target_id), '#empty_option' => $this->t('- None -'), '#ajax' => [ 'callback' => [$this, 'ajaxCallChangeGroup'], 'wrapper' => $this->wrapper, 'progress' => [], ], //'#default_value' => isset($form_state->getValue('gid')) ? $form_state->getValue('gid') : NULL, ]; $form['cid'] = [ '#type' => 'select', '#title' => $this->t('Characteristic'), '#options' => [], '#empty_option' => $this->t('- None -'), '#prefix' => '<div id="' . $this->wrapper . '">', '#suffix' => '</div>', '#validated' => TRUE, ]; $form['value'] = array( '#type' => 'textfield', '#title' => $this->t('Parameter value'), '#maxlength' => 255, '#required' => FALSE, '#default_value' => isset($characteristic_data->cid) ? $characteristic_data->value : "", ); // TODO: Требуется разработка справочника ед. измерения характеристик. $form['unit'] = array( '#type' => 'select', '#title' => $this->t('Unit'), '#options' => [], '#empty_option' => $this->t('- None -'), '#default_value' => NULL, ); $form['cost'] = array( '#type' => 'number', '#title' => $this->t('Price'), '#default_value' => '0.00', '#step' => '0.01', '#min' => '0', ); $form['use_in_title'] = array( '#title' => $this->t('Add to product name'), '#type' => 'checkbox', '#default_value' => FALSE, ); $form['image'] = [ '#name' => 'characteristic_image', '#type' => 'managed_file', '#multiple' => FALSE, '#title' => $this->t("Add image"), '#upload_validators' => [ 'file_validate_extensions' => ['svg jpg jpeg png'], 'file_validate_size' => [25600000], 'file_validate_image_resolution' => ['1920x1080'], ], '#default_value' => NULL, '#upload_location' => 'public://upload-files/', '#description' => $this->t('Used as a product image.'), ]; // Now we add our submit button, for submitting the form results. // The 'actions' wrapper used here isn't strictly necessary for tabledrag, // but is included as a Form API recommended practice. $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => $this->t('Save'), '#button_type' => 'primary', ); return $form; }
{@inheritdoc}
entailment
public function ajaxCallChangeGroup(array &$form, FormStateInterface $form_state) { $element = $form_state->getTriggeringElement(); $gid = $element['#value']; $options = $this->database->characteristicsReadItems($gid); $form['cid']['#options'] = $options; return $form['cid']; }
Ajax callback.
entailment
public function submitForm(array &$form, FormStateInterface $form_state) { $position = $form_state->getValue('position'); $characteristic = $form_state->getValue('characteristic'); $gid = (int) $form_state->getValue('gid'); $cid = (int) $form_state->getValue('cid'); $value = trim($form_state->getValue('value')); $unit = (int) $form_state->getValue('unit'); $cost = trim($form_state->getValue('cost')); $use_in_title = (int) $form_state->getValue('use_in_title'); if (empty($characteristic)) { $characteristic = $this->database->characteristicsReadItem($cid); } // Выполняем если создаётся новый элемент. $return_created = null; $return_updated = null; if (!$this->database->characteristicDataReadItem($pid, $characteristic->cid)) { $uuid = \Drupal::service('uuid'); $data = array( 'cid' => $characteristic->cid, 'gid' => $gid, 'pid' => $position->id(), 'status' => 1, 'use_in_title' => $use_in_title, 'fid' => 0, 'value' => $value, 'cost' => $cost, 'unit' => $unit, 'weight' => 1, ); $this->database->characteristicDataCreateItem($data); $characteristic_data = $this->database->characteristicDataReadItem($position->id(), $cid); $return_created = TRUE; } else { // Выполняем если обновляется элемент. $entry = array( 'cid' => $characteristic->cid, 'pid' => $position->id(), 'use_in_title' => $use_in_title, 'value' => $value, 'cost' => $cost, 'unit' => $unit, ); $this->database->characteristicDataUpdateItem($entry); $characteristic_data = $this->database->characteristicDataReadItem($position->id(), $characteristic->cid); $return_updated = TRUE; } // Сохраняем изображение. if (isset($characteristic_data->cid)) { $destination = 'public://images/characteristics/products'; file_prepare_directory($destination, FILE_CREATE_DIRECTORY); $image_fid = $form_state->getValue('image'); if (isset($image_fid[0])) { $file_form = file_load($image_fid[0]); if ($file_form) { if ($file = file_move($file_form, $destination, FILE_EXISTS_RENAME)) { $file->status = FILE_STATUS_PERMANENT; $file->save(); // Выполняем привязку файла к характеристике товара. $entry = array( 'cid' => $characteristic_data->cid, 'pid' => $position->id(), 'fid' => $file->id(), ); $this->database->characteristicDataUpdateItem($entry); // Изменяем применяемость файла. $file_usage = \Drupal::service('file.usage'); if ($file_current_usage = $this->database->loadFile('characteristic_product', $position->id() . '-' . $characteristic_data->cid)) { $file_usage->delete($file_current_usage, 'site_commerce', 'characteristic_product', $position->id() . '-' . $characteristic_data->cid); $file_current_usage->status = 0; $file_current_usage->save(); } $file_usage->add($file, 'site_commerce', 'characteristic_product', $position->id() . '-' . $characteristic_data->cid); } else { // Фиксируем в журнале событий ошибку. \Drupal::logger('characteristic create image')->error('Файл не был загружен: @id', array( '@id' => $file_form->id(), )); } } } } if ($return_created) { drupal_set_message($this->t('Characteristic «@title» created.', array('@title' => $characteristic->title))); } if ($return_updated) { drupal_set_message($this->t('Characteristic «@title» updated.', array('@title' => $characteristic->title))); } }
{@inheritdoc}
entailment
public static function is($data) { if (self::isArray($data)) { return 'array'; } else if (self::isObject($data)) { return 'object'; } else if (self::isJson($data)) { return 'json'; } else if (self::isSerialized($data)) { return 'serialized'; } else if (self::isXml($data)) { return 'xml'; } return 'other'; }
Returns a string for the detected type. @access public @param mixed $data @return string @static
entailment
public static function toArray($resource) { if (self::isArray($resource)) { return $resource; } else if (self::isObject($resource)) { return self::buildArray($resource); } else if (self::isJson($resource)) { return json_decode($resource, true); } else if ($ser = self::isSerialized($resource)) { return self::toArray($ser); } else if ($xml = self::isXml($resource)) { return self::xmlToArray($xml); } return $resource; }
Transforms a resource into an array. @access public @param mixed $resource @return array @static
entailment
public static function toJson($resource) { if (self::isJson($resource)) { return $resource; } if ($xml = self::isXml($resource)) { $resource = self::xmlToArray($xml); } else if ($ser = self::isSerialized($resource)) { $resource = $ser; } return json_encode($resource); }
Transforms a resource into a JSON object. @access public @param mixed $resource @return string (json) @static
entailment
public static function toObject($resource) { if (self::isObject($resource)) { return $resource; } else if (self::isArray($resource)) { return self::buildObject($resource); } else if (self::isJson($resource)) { return json_decode($resource); } else if ($ser = self::isSerialized($resource)) { return self::toObject($ser); } else if ($xml = self::isXml($resource)) { return $xml; } return $resource; }
Transforms a resource into an object. @access public @param mixed $resource @return object @static
entailment