sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function statusbar( $str, $height = null, $last_line_to_opposing_stream = true ) { if( $height < 0 ) { $height = Misc::rows() + $height + 1; } if( !$height ) { if( defined('STATUSBAR_HEIGHT') ) { $height = STATUSBAR_HEIGHT; //@todo: backwards compatibility with some of my older code, remove } else { $height = max(5, Misc::rows() - 5); } } static $lines = false; $i = 0; if( !$lines ) { $lines = array_fill(0, $height - 1, array( 'str' => '' )); } foreach( explode(PHP_EOL, $str) as $line ) { $lines[] = array( 'str' => strtr(trim($line), "\r\n", " ") ); array_shift($lines); } fwrite(self::$stream, "\0337\033[1;1f\033[2K"); foreach( $lines as $line ) { $i++; $text = substr(str_pad($line['str'], Misc::cols()), 0, Misc::cols() - 1); Cursor::rowcol($i, 1); if( $i == $height - 1 && $last_line_to_opposing_stream ) { fwrite(self::$altstream, $text); } else { fwrite(self::$stream, $text); } } fwrite(self::$stream, "\033[" . $height . ";1f"); fwrite(self::$stream, str_repeat('─', Misc::cols())); fwrite(self::$stream, "\0338"); }
Render a statusbar stack @staticvar bool $lines A stack of previously added lines @param string $str The status to add @param null|int $height The height of the status menu to render @param bool $last_line_to_opposing_stream Send the last line of the status to the oposite stream (STDERR/STDOUT)
entailment
public static function progressbar( $title, $numerator, $denominator, $line, $time_id = null, $color = 'cyan' ) { static $timer = array(); if( $time_id ) { if( !isset($timer[$time_id]) || $timer[$time_id]['last_numerator'] > $numerator ) { $timer[$time_id] = array( 'start' => microtime(true) ); } $timer[$time_id]['last_numerator'] = $numerator; } $text = $title . ' - ' . self::num_display($numerator) . '/' . self::num_display($denominator); $time_text = ''; if( $time_id ) { $diff = microtime(true) - $timer[$time_id]['start']; $time_left = self::formtime(($numerator ? $diff / $numerator : 0) * ($denominator - $numerator)); $elapsed = self::formtime($diff); if( $diff > 2 ) { $time_text = $time_left . " ($elapsed)"; } } $width = max(min(Misc::cols() - strlen($text) - (strlen($time_text) ? : -1) - 6, $denominator), 4); $main_xs = floor(($numerator / $denominator) * $width); $str = $text . ' [' . Style::$color(str_repeat('#', $main_xs)) . str_repeat('.', $width - $main_xs) . "] " . $time_text; Output::line($str, $line); }
Draw a Progress Bar @staticvar array $timer @param string $title @param int $numerator @param int $denominator @param int $line Which row of the terminal to render @param int|null $time_id @param string $color
entailment
public static function histogram( $title, $numerator, $denominator, $line, $hist_id, $color = 'normal', $full_color = 'red' ) { $levels = array( ' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█' ); static $hist = false; if( !$hist || !$hist[$hist_id] ) { $hist[$hist_id] = array_fill(0, Misc::cols(), $levels[0]); } $text = $title . ' - ' . self::num_display($numerator) . '/' . self::num_display($denominator) . ' '; #$lev = round(($numerator / $denominator) * 8); $lev = intval(($numerator / $denominator) * 9); $lev = min($lev, 8); $hist[$hist_id][] = $lev == 8 ? Style::$full_color($levels[$lev]) : Style::$color($levels[$lev]); array_shift($hist[$hist_id]); $sub_array = array_slice($hist[$hist_id], 0 - (Misc::cols() - strlen($text)) + 4); $str = $text . '[' . implode($sub_array, '') . ']'; Output::line($str, $line); }
Draw a Histogram @param string $title @param int $numerator @param int $denominator @param int $line @param int $hist_id @param string $color @param string $full_color
entailment
public function viewElements(FieldItemListInterface $items, $langcode) { $elements = []; foreach ($items as $delta => $item) { $elements['data'] = [ '#theme' => 'site_commerce_settings_default_formatter', '#new' => $item->new, '#appearance' => $item->appearance, '#stock' => $item->stock, '#sale' => $item->sale, ]; } return $elements; }
{@inheritdoc}
entailment
public function update(Listener $listener, Fluent $extension, array $input) { if (! Extension::started($extension->get('name'))) { return $listener->suspend(404); } $validation = $this->validator->with($input, ["orchestra.validate: extension.{$extension->get('name')}"]); if ($validation->fails()) { return $listener->updateConfigurationFailedValidation($validation->getMessageBag(), $extension->uid); } $input['handles'] = str_replace(['{domain}', '{{domain}}'], '{{domain}}', $input['handles']); unset($input['_token']); $memory = Foundation::memory(); $config = (array) $memory->get("extension.active.{$extension->get('name')}.config", []); $input = new Fluent(\array_merge($config, $input)); Event::dispatch("orchestra.saving: extension.{$extension->get('name')}", [&$input]); $memory->put("extensions.active.{$extension->get('name')}.config", $input->getAttributes()); $memory->put("extension_{$extension->get('name')}", $input->getAttributes()); Event::dispatch("orchestra.saved: extension.{$extension->get('name')}", [$input]); return $listener->configurationUpdated($extension); }
Update an extension configuration. @param \Orchestra\Contracts\Extension\Listener\Configure $listener @param \Illuminate\Support\Fluent $extension @param array $input @return mixed
entailment
public function view(UserViewerListener $listener, array $input = []) { $search = [ 'keyword' => $input['q'] ?? '', 'roles' => $input['roles'] ?? [], ]; // Get Users (with roles) and limit it to only 30 results for // pagination. Don't you just love it when pagination simply works. $eloquent = Foundation::make('orchestra.user')->search($search['keyword'])->hasRolesId($search['roles']); $roles = Foundation::make('orchestra.role')->pluck('name', 'id'); // Build users table HTML using a schema liked code structure. $table = $this->presenter->table($eloquent); Event::dispatch('orchestra.list: users', [$eloquent, $table]); // Once all event listening to `orchestra.list: users` is executed, // we can add we can now add the final column, edit and delete // action for users. $this->presenter->actions($table); $data = [ 'eloquent' => $eloquent, 'roles' => $roles, 'table' => $table, 'search' => $search, ]; return $listener->showUsers($data); }
View list users page. @param \Orchestra\Contracts\Foundation\Listener\Account\UserViewer $listener @param array $input @return mixed
entailment
public function edit(UserUpdaterListener $listener, $id) { $eloquent = Foundation::make('orchestra.user')->findOrFail($id); $form = $this->presenter->form($eloquent, 'update'); $this->fireEvent('form', [$eloquent, $form]); return $listener->showUserChanger(\compact('eloquent', 'form')); }
View edit user page. @param \Orchestra\Contracts\Foundation\Listener\Account\UserUpdater $listener @param string|int $id @return mixed
entailment
public function store(UserCreatorListener $listener, array $input) { $validation = $this->validator->on('create')->with($input); if ($validation->fails()) { return $listener->createUserFailedValidation($validation->getMessageBag()); } $user = Foundation::make('orchestra.user'); $user->status = Eloquent::UNVERIFIED; $user->password = $input['password']; try { $this->saving($user, $input, 'create'); } catch (Exception $e) { return $listener->createUserFailed(['error' => $e->getMessage()]); } return $listener->userCreated(); }
Store a user. @param \Orchestra\Contracts\Foundation\Listener\Account\UserCreator $listener @param array $input @return mixed
entailment
public function update(UserUpdaterListener $listener, $id, array $input) { // Check if provided id is the same as hidden id, just a pre-caution. if ((string) $id !== $input['id']) { return $listener->abortWhenUserMismatched(); } $validation = $this->validator->on('update')->with($input); if ($validation->fails()) { return $listener->updateUserFailedValidation($validation->getMessageBag(), $id); } $user = Foundation::make('orchestra.user')->findOrFail($id); ! empty($input['password']) && $user->password = $input['password']; try { $this->saving($user, $input, 'update'); } catch (Exception $e) { return $listener->updateUserFailed(['error' => $e->getMessage()]); } return $listener->userUpdated(); }
Update a user. @param \Orchestra\Contracts\Foundation\Listener\Account\UserUpdater $listener @param string|int $id @param array $input @return mixed
entailment
public function destroy(UserRemoverListener $listener, $id) { $user = Foundation::make('orchestra.user')->findOrFail($id); // Avoid self-deleting accident. if ((string) $user->id === (string) Auth::user()->id) { return $listener->selfDeletionFailed(); } try { $this->fireEvent('deleting', [$user]); $user->transaction(function () use ($user) { $user->delete(); }); $this->fireEvent('deleted', [$user]); } catch (Exception $e) { return $listener->userDeletionFailed(['error' => $e->getMessage()]); } return $listener->userDeleted(); }
Destroy a user. @param \Orchestra\Contracts\Foundation\Listener\Account\UserRemover $listener @param string|int $id @return mixed
entailment
protected function saving(Eloquent $user, $input = [], $type = 'create') { $beforeEvent = ($type === 'create' ? 'creating' : 'updating'); $afterEvent = ($type === 'create' ? 'created' : 'updated'); $user->fullname = $input['fullname']; $user->email = $input['email']; $this->fireEvent($beforeEvent, [$user]); $this->fireEvent('saving', [$user]); $user->transaction(function () use ($user, $input) { $user->save(); $user->roles()->sync($input['roles']); }); $this->fireEvent($afterEvent, [$user]); $this->fireEvent('saved', [$user]); return true; }
Save the user. @param \Orchestra\Model\User $user @param array $input @param string $type @return bool
entailment
public function saveNodeValue(NodePath $nodePath, string $property, $value) { try { $this->data = $this->storeValue($nodePath, $this->data, $property, $value); } catch (InconsistentValueException $e) { if ($property == 'nodeType') { $node = $this->getNode($nodePath); $this->handleUpgrade($node, $nodePath, $value); } else { throw $e; } } }
Save a single property value for a given node. @param NodePath $nodePath Node Path. @param string $property Property name (e.g. 'nodeType') @param mixed $value Scalar value. @throws InconsistentValueException
entailment
private function storeValue(NodePath $nodePath, array $data, string $property, $value) : array { $nodePath = $nodePath->popFirst($nodeName); $nodeName = $this->encodeNodeName($nodeName); if (!isset($data[$nodeName])) { $data[$nodeName] = []; } if ($nodePath->isEmpty()) { // we arrived at the target, check if the value is not set already if (!empty($data[$nodeName][$property]) && ($data[$nodeName][$property] != $value)) { throw new InconsistentValueException("Attempting to overwrite '$property' value '" . $data[$nodeName][$property] . "' with '$value'."); } $data[$nodeName][$property] = $value; } else { $data[$nodeName] = $this->storeValue($nodePath, $data[$nodeName], $property, $value); } return $data; }
Store a particular value of a particular property for a given node. @param NodePath $nodePath Node Path @param array $data Structure data. @param string $property Name of the property (e.g. 'nodeType') @param mixed $value Scalar value of the property. @return array Structure data @throws InconsistentValueException In case the values is already set and not same.
entailment
private function handleUpgrade(array $node, NodePath $nodePath, string $newType) { if ((($node['nodeType'] == 'array') || ($newType == 'array')) && $this->autoUpgradeToArray) { $this->checkArrayUpgrade($node, $nodePath, $newType); // copy all properties to the array if (!empty($node[self::ARRAY_NAME])) { foreach ($node[self::ARRAY_NAME] as $key => $value) { $newNode[self::ARRAY_NAME][$key] = $value; } } foreach ($node as $key => $value) { if (is_array($value) && ($key != self::ARRAY_NAME)) { $newNode[self::ARRAY_NAME][$key] = $value; } } if ($newType != 'array') { $newNode[self::ARRAY_NAME]['nodeType'] = $newType; } else { $newNode[self::ARRAY_NAME]['nodeType'] = $node['nodeType']; } $newNode['nodeType'] = 'array'; if (!empty($node['headerNames'])) { $newNode[self::ARRAY_NAME]['headerNames'] = self::DATA_COLUMN; $newNode['headerNames'] = $node['headerNames']; } $this->data = $this->storeNode($nodePath, $this->data, $newNode); } elseif (($node['nodeType'] != 'null') && ($newType == 'null')) { // do nothing, old type is fine } elseif (($node['nodeType'] == 'null') && ($newType != 'null')) { $newNode = $this->getNode($nodePath); $newNode['nodeType'] = $newType; $this->data = $this->storeNode($nodePath, $this->data, $newNode); } else { throw new JsonParserException( 'Unhandled nodeType change from "' . $node['nodeType'] . '" to "' . $newType . '" in "' . $nodePath->__toString() . '"' ); } }
Upgrade a node to array @param array $node @param NodePath $nodePath @param string $newType @throws JsonParserException
entailment
public function saveNode(NodePath $nodePath, array $node) { $this->data = $this->storeNode($nodePath, $this->data, $node); }
Store a complete node data in the structure. @param NodePath $nodePath Node path. @param array $node Node data.
entailment
private function storeNode(NodePath $nodePath, array $data, array $node) : array { $nodePath = $nodePath->popFirst($nodeName); $nodeName = $this->encodeNodeName($nodeName); if ($nodePath->isEmpty()) { $data[$nodeName] = $node; } else { if (isset($data[$nodeName])) { $data[$nodeName] = $this->storeNode($nodePath, $data[$nodeName], $node); } else { throw new JsonParserException("Node path " . $nodePath->__toString() . " does not exist."); } } return $data; }
Store a complete node data in the structure. @param NodePath $nodePath Node path. @param array $data Structure data. @param array $node Node data. @return array Structure data. @throws JsonParserException In case the node path is not valid.
entailment
public function getData() { foreach ($this->data as $value) { $this->validateDefinitions($value); } return ['data' => $this->data, 'parent_aliases' => $this->parentAliases]; }
Return complete structure. @return array
entailment
public function getNode(NodePath $nodePath, array $data = null) { if (empty($data)) { $data = $this->data; } $nodePath = $nodePath->popFirst($nodeName); $nodeName = $this->encodeNodeName($nodeName); if (!isset($data[$nodeName])) { return null; } if ($nodePath->isEmpty()) { return $data[$nodeName]; } else { return $this->getNode($nodePath, $data[$nodeName]); } }
Get structure of a particular node. @param NodePath $nodePath Node path. @param array $data Optional structure data (for recursive call). @return array|null Null in case the node path does not exist.
entailment
public function getNodeProperty(NodePath $nodePath, string $property) { $data = $this->getNode($nodePath); if (isset($data[$property])) { return $data[$property]; } else { return null; } }
Return a particular property of the node. @param NodePath $nodePath Node path @param string $property Property name (e.g. 'nodeType') @return mixed Property value or null if the node or property does not exist.
entailment
private function getNodeChildrenProperties(NodePath $nodePath, string $property) : array { $nodeData = $this->getNode($nodePath); $result = []; if (!empty($nodeData)) { if ($nodeData['nodeType'] == 'object') { foreach ($nodeData as $itemName => $value) { if (is_array($value)) { $itemName = $this->decodeNodeName($itemName); // it is a child node if (isset($value[$property])) { $result[$itemName] = $value[$property]; } else { $result[$itemName] = null; } } } } elseif ($nodeData['nodeType'] == 'scalar') { foreach ($nodeData as $itemName => $value) { if ($itemName == $property) { $result[$nodePath->getLast()] = $value; } } } } return $result; }
Return a particular property of a the children of the node. @param NodePath $nodePath Node path @param string $property Property name (e.g. 'nodeType'). @return array
entailment
public function getColumnTypes(NodePath $nodePath) { $values = $this->getNodeChildrenProperties($nodePath, 'nodeType'); $result = []; foreach ($values as $key => $value) { if ($key === self::ARRAY_NAME) { $result[self::DATA_COLUMN] = $value; } else { $result[$key] = $value; } } return $result; }
Get columns from a node and return their data types. @param NodePath $nodePath @return array Index is column name, value is data type.
entailment
public function generateHeaderNames() { foreach ($this->data as $baseType => &$baseArray) { foreach ($baseArray as $nodeName => &$nodeData) { if (is_array($nodeData)) { $nodeName = $this->decodeNodeName($nodeName); $this->generateHeaderName( $nodeData, new NodePath([$baseType, $nodeName]), self::ARRAY_NAME, // # root is always array $baseType ); } } } }
Generate header names for the whole structure.
entailment
public function getParentTargetName(string $name) { if (empty($this->parentAliases[$name])) { return $name; } return $this->parentAliases[$name]; }
Get new name of a parent column @param $name @return mixed
entailment
private function getSafeName(string $name) : string { $name = preg_replace('/[^A-Za-z0-9-]/', '_', $name); if (strlen($name) > 64) { if (str_word_count($name) > 1 && preg_match_all('/\b(\w)/', $name, $m)) { // Create an "acronym" from first letters $short = implode('', $m[1]); } else { $short = md5($name); } $short .= "_"; $remaining = 64 - strlen($short); $nextSpace = strpos($name, " ", (strlen($name)-$remaining)) ? : strpos($name, "_", (strlen($name)-$remaining)); $newName = $nextSpace === false ? $short : $short . substr($name, $nextSpace); } else { $newName = $name; } $newName = preg_replace('/[^A-Za-z0-9-]+/', '_', $newName); $newName = trim($newName, "_"); return $newName; }
If necessary, change the name to a safe to store in database. @param string $name @return string
entailment
private function getUniqueName(string $baseType, string $headerName) : string { if (isset($this->headerIndex[$baseType][$headerName])) { $newName = $headerName; $i = 0; while (isset($this->headerIndex[$baseType][$newName])) { $newName = $headerName . '_u' . $i; $i++; } $headerName = $newName; } $this->headerIndex[$baseType][$headerName] = 1; return $headerName; }
If necessary change the name to a unique one. @param string $baseType @param string $headerName @return string
entailment
private function generateHeaderName(array &$data, NodePath $nodePath, string $parentName, string $baseType) { if (empty($data['headerNames'])) { // write only once, because generateHeaderName may be called repeatedly if ($parentName != self::ARRAY_NAME) { // do not generate headers for arrays $headerName = $this->getSafeName($parentName); $headerName = $this->getUniqueName($baseType, $headerName); $data['headerNames'] = $headerName; } else { $data['headerNames'] = self::DATA_COLUMN; } } if ($data['nodeType'] == 'array') { // array node creates a new type and does not nest deeper $baseType = $baseType . '.' . $parentName; $parentName = ''; } foreach ($data as $key => &$value) { if (is_array($value)) { $key = $this->decodeNodeName($key); if (!$parentName || (!empty($data[$key]['type']) && $data[$key]['type'] == 'parent')) { // skip nesting if there is nowhere to nest (array or parent-type child) $childName = $key; } else { $childName = $parentName . '.' . $key; } $this->generateHeaderName($value, $nodePath->addChild($key), $childName, $baseType); } } }
Generate header name for a node and sub-nodes. @param array $data Node data @param NodePath $nodePath @param string $parentName @param string $baseType
entailment
public function load(array $definitions) { $this->data = $definitions['data'] ?? []; $this->parentAliases = $definitions['parent_aliases'] ?? []; foreach ($this->data as $value) { $this->validateDefinitions($value); } }
Load structure data. @param array $definitions
entailment
public function configure($model, $name) { return $this->form->of("orchestra.extension: {$name}", function (FormGrid $form) use ($model, $name) { $form->setup($this, "orchestra::extensions/{$name}/configure", $model); $handles = data_get($model, 'handles', $this->extension->option($name, 'handles')); $configurable = data_get($model, 'configurable', true); if (! is_null($handles) && $configurable !== false) { $form->fieldset(function (Fieldset $fieldset) use ($handles) { // We should only cater for custom URL handles for a route. $fieldset->control('input:text', 'handles') ->label(trans('orchestra/foundation::label.extensions.handles')) ->value(str_replace(['{{domain}}', '{domain}'], '{domain}', $handles)); }); } }); }
Form View Generator for Orchestra\Extension. @param \Illuminate\Support\Fluent $model @param string $name @return \Orchestra\Contracts\Html\Form\Builder
entailment
public function getState() { return (isset($this->raw['state']) && ! empty($this->raw['state'])) ? (string) $this->raw['state'] : null; }
Возвращает статус ответа от B2B. @return null|string
entailment
public function count() { return isset($this->raw['size']) ? (int) $this->raw['size'] : (isset($this->raw['data']) && is_array($this->raw['data']) ? count($this->raw['data']) : null); }
Возвращает количество вхождений в ответе от B2B. @return int|null
entailment
public static function getCatalogByTerm($term_current, $limit = 4) { $build = []; $pids = []; $site_commerces = []; $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); $db = \Drupal::database(); // Дочерние термины для которого получаем перечень товаров. $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($term_current->getVocabularyId(), $term_current->id(), NULL, TRUE); if (count($terms)) { foreach ($terms as $term) { $pids = []; if ($term->field_view->value) { $query = $db->select('site_commerce_field_data', 'n'); if (!$user->hasRole('site commerce administer online store')) { $query->condition('n.status', 1); $query->condition('n.status_catalog', 1); } $query->fields('n', array('pid')); $query->innerJoin('site_commerce__field_category', 't', 't.entity_id=n.pid'); $query->condition('t.field_category_target_id', $term->id()); $query->range(0, $limit); $query->orderBy('weight'); $result = $query->execute(); foreach ($result as $row) { $pids[] = $row->pid; } if ($pids) { $count_term_products = \Drupal::service('site_commerce.database')->countProducts(1, $term->id()); $site_commerces[$term->id()]['view_all'] = FALSE; $site_commerces[$term->id()]['count_term_products'] = $count_term_products; if ($count_term_products > $limit) { $site_commerces[$term->id()]['view_all'] = TRUE; } $site_commerces[$term->id()]['name'] = $term->getName(); $site_commerces[$term->id()]['summary'] = ""; $site_commerces[$term->id()]['summary'] = $term->get('field_category_summary')->value; $site_commerces[$term->id()]['tid'] = $term->id(); $site_commerces[$term->id()]['site_commerce'] = \Drupal::entityTypeManager()->getStorage('site_commerce')->loadMultiple($pids); } } } } // Товары в текущей категории. $pids = []; $query = $db->select('site_commerce_field_data', 'n'); if (!$user->hasRole('site commerce administer online store')) { $query->condition('n.status', 1); $query->condition('n.status_catalog', 1); } $query->fields('n', array('pid')); $query->innerJoin('site_commerce__field_category', 't', 't.entity_id=n.pid'); $query->condition('t.field_category_target_id', $term_current->id()); $query->orderBy('weight'); $pager = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')->limit(80); $result = $pager->execute(); foreach ($result as $row) { $pids[] = $row->pid; } if ($pids) { $count_term_products = \Drupal::service('site_commerce.database')->countProducts(1, $term_current->id()); $site_commerces[$term_current->id()]['view_all'] = FALSE; $site_commerces[$term_current->id()]['count_term_products'] = $count_term_products; // Заголовок для дополнительных товаров или услуг. $site_commerces[$term_current->id()]['name'] = ""; if (count($terms)) { $site_commerces[$term_current->id()]['name'] = t('Additional products (services) in the category «@category»', ['@category' => $term_current->getName()]); } $site_commerces[$term_current->id()]['summary'] = ""; $site_commerces[$term_current->id()]['view_all'] = FALSE; $site_commerces[$term_current->id()]['tid'] = ""; $site_commerces[$term_current->id()]['site_commerce'] = \Drupal::entityTypeManager()->getStorage('site_commerce')->loadMultiple($pids); } if (count($site_commerces)) { $build['products'] = array( '#theme' => 'site_commerce_catalog_products', '#site_commerces' => $site_commerces, '#attached' => array( 'library' => array( 'site_commerce/card', ), ), '#cache' => [ 'tags' => ['taxonomy_term:' . $term_current->id()], 'contexts' => ['languages'], 'max-age' => Cache::PERMANENT, ], ); // Добавляет пейджер на страницу. if (!count($terms)) { $build['pager'] = array( '#type' => 'pager', '#quantity' => 2, ); } } return $build; }
Страница каталога с товарами по категории.
entailment
public static function getCatalog($vid = "site_commerce") { $query = \Drupal::database()->select('taxonomy_term_field_data', 'n'); $query->fields('n', array('tid')); $query->condition('n.vid', $vid); $query->orderBy('n.weight', 'ASC'); $query->innerJoin('taxonomy_term__parent', 'h', 'h.entity_id=n.tid'); $query->condition('h.parent_target_id', 0); $query->condition('h.bundle', 'site_commerce'); $query->innerJoin('taxonomy_term__field_view', 'v', 'v.entity_id=n.tid'); $query->condition('v.bundle', 'site_commerce'); $query->condition('v.field_view_value', 1); $tids = $query->execute()->fetchCol(); $terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids); return array( '#theme' => 'site_commerce_catalog', '#terms' => $terms, '#vid' => $vid, '#attached' => array( 'library' => array( 'site_commerce/card', ), ), ); }
Страница отображения категорий каталога по названию словаря.
entailment
public static function getCatalogChildrenList($tid) { $db = \Drupal::database(); $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid); $terms_result = []; // Дочерние термины для которого получаем перечень товаров. $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($term->getVocabularyId(), $term->id(), NULL, TRUE); if (count($terms)) { foreach ($terms as $term) { $pids = []; if ($term->field_view->value) { $query = $db->select('site_commerce_field_data', 'n'); $query->condition('n.status', 1); $query->condition('n.status_catalog', 1); $query->fields('n', array('pid')); $query->innerJoin('site_commerce__field_category', 't', 't.entity_id=n.pid'); $query->condition('t.field_category_target_id', $term->id()); $result = $query->countQuery()->execute()->fetchField(); if ($result) { $terms_result[] = $term; } } } } return [ '#theme' => 'site_commerce_catalog_children_list', '#terms' => $terms_result, '#attached' => [ 'library' => [ 'site_commerce/card', ], ], ]; }
Список дочерних категорий по номеру категории-родителя.
entailment
public function handle(Foundation $foundation, Memory $memory) { $this->setupApplication(); $this->refreshApplication($foundation, $memory); $this->optimizeApplication(); }
Execute the console command. @param \Orchestra\Contracts\Foundation\Foundation $foundation @param \Orchestra\Contracts\Memory\Provider $memory @return void
entailment
protected function refreshApplication(Foundation $foundation, Memory $memory): void { if (! $foundation->installed()) { $this->error('Abort as application is not installed!'); return; } $this->call('extension:detect', ['--quiet' => true]); try { Collection::make($memory->get('extensions.active', [])) ->keys()->each(function ($extension) { $options = ['name' => $extension, '--force' => true]; $this->call('extension:refresh', $options); $this->call('extension:update', $options); }); $this->laravel->make('orchestra.extension.provider')->writeFreshManifest(); } catch (PDOException $e) { // Skip if application is unable to make connection to the database. } }
Refresh application for Orchestra Platform. @param \Orchestra\Contracts\Foundation\Foundation $foundation @param \Orchestra\Contracts\Memory\Provider $memory @return void
entailment
protected function optimizeApplication(): void { $this->info('Optimizing application for Orchestra Platform'); $this->call('config:clear'); $this->call('route:clear'); if ($this->laravel->environment('production') && ! $this->option('no-cache')) { $this->call('config:cache'); $this->call('route:cache'); } }
Optimize application for Orchestra Platform. @return void
entailment
public function viewElements(FieldItemListInterface $items, $langcode) { $elements = []; foreach ($items as $delta => $item) { $elements['data'] = [ '#theme' => 'site_commerce_cart_default_formatter', '#visible' => $item->visible, '#event' => $item->event, '#label_add' => $item->label_add, '#label_click' => $item->label_click, '#description' => $item->description, ]; } return $elements; }
{@inheritdoc}
entailment
public function set($key, $values, $replace = true) { parent::set($key, $values, $replace); $this->updateRequest(); }
Sets a header by name. @param string $key @param string|array $values @param bool $replace
entailment
protected function updateRequest() { $headers = []; foreach ($this->all() as $key => $values) { foreach ($values as $value) { $headers[] = $key.': '.$value; } } $this->request->setOption(CURLOPT_HTTPHEADER, $headers); }
Updates the headers in the associated request.
entailment
public function submitForm(array &$form, FormStateInterface $form_state) { $entity = $this->getEntity(); $content = array(); foreach (\Drupal::entityTypeManager()->getStorage('site_commerce_type')->loadMultiple() as $type) { $content[] = $type->id(); } $duplicate = $entity->createDuplicateType("product_" . count($content)); $duplicate->save(); drupal_set_message($this->t('Product type %label has been duplicated.', array('%label' => $duplicate->label()))); $form_state->setRedirectUrl($this->getCancelUrl()); }
{@inheritdoc}
entailment
protected function authorize(?string $action = null): bool { return $this->foundation->memory()->get('site.registrable', false); }
Check authorization. @param string $action @return bool
entailment
public static function getCharacteristicsByTerm($term, $position) { $build = []; $pids = []; $site_commerces = []; $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); $database = \Drupal::database(); }
Страница характеристик по категории.
entailment
public function submitForm(array &$form, FormStateInterface $form_state) { $database = Database::getConnection(); $term = $form_state->getValues()['term']; $scheme = 'public'; $inputFileName = $scheme . '://export/templates/getPrice.xls'; $reader = IOFactory::createReader("Xls"); $spreadsheet = $reader->load($inputFileName); // Формируем данные в шаблон. $spreadsheet->setActiveSheetIndex(0); $worksheet = $spreadsheet->getActiveSheet(); // Название прайс-листа. $worksheet->setCellValueByColumnAndRow(1, 4, $term->getName()); // Перечень товаров по категории. $query = $database->select('site_commerce_field_data', 'n'); $query->condition('n.status', 1); $query->condition('n.status_catalog', 1); $query->fields('n', array('pid')); $query->innerJoin('site_commerce__field_category', 't', 't.entity_id=n.pid'); $query->condition('t.field_category_target_id', $term->id()); $result = $query->execute(); $pids = []; foreach ($result as $row) { $pids[] = $row->pid; } if ($pids) { // Массовая загрузка перечня товаров. $site_commerces = \Drupal::entityTypeManager()->getStorage('site_commerce')->loadMultiple($pids); $id = 1; $row = 8; foreach ($site_commerces as $position) { $title = $position->getTitle(); // Формируем стоимость товара. // TODO: Пока реализовано отображение для ценовой группы по умолчанию равной 1. $group = 1; $data = getCostValueForUserPriceGroup($position, $group, FALSE, FALSE); if ($data['from']) { $cost = $this->t('from') . ' ' . $data['from']; } else { $cost = $data['value']; } if (!$cost) { $cost = $this->t('Check the price'); } // Единица кол-ва. $unit = $position->get('field_quantity')->unit; // Загружаем данные в Excel. $worksheet->getCell('A' . $row)->setValue($id); $worksheet->getCell('B' . $row)->setValue($title); $worksheet->getCell('AQ' . $row)->setValue($cost); $worksheet->getCell('AX' . $row)->setValue($unit); $id++; $row++; } // Скрываем пустые строки. $count_hide_row = $row; for ($i = $count_hide_row; $i <= 1000; $i++) { $worksheet->getRowDimension($i)->setOutlineLevel(1); $worksheet->getRowDimension($i)->setVisible(false); $count_hide_row++; } $worksheet->getRowDimension($count_hide_row)->setCollapsed(true); } // Формируем имя файла. $filename = $term->getName() . '-' . date('d-m-Y-H-i-s', REQUEST_TIME) . '.xls'; $uri = $scheme . '://export/' . $filename; $writer = IOFactory::createWriter($spreadsheet, "Xls"); $writer->save($uri); if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) { $response = new BinaryFileResponse($uri); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename); $form_state->setResponse($response); } }
{@inheritdoc}
entailment
protected function changePermission(string $path, $mode = 0755, bool $recursively = false): void { $filesystem = $this->getContainer()['files']; $filesystem->chmod($path, $mode); if ($recursively === false) { return; } $lists = $filesystem->allFiles($path); $ignoredPath = function ($dir) { return (\substr($dir, -3) === '/..' || \substr($dir, -2) === '/.'); }; // this is to check if return value is just a single file, // avoiding infinite loop when we reach a file. if ($lists !== [$path]) { foreach ($lists as $dir) { // Not a file or folder, ignore it. if (! $ignoredPath($dir)) { $this->changePermission($dir, $mode, true); } } } }
Change CHMOD permission. @param string $path @param int $mode @param bool $recursively @return void
entailment
protected function prepareDirectory(string $path, $mode = 0755): void { $filesystem = $this->getContainer()['files']; if (! $filesystem->isDirectory($path)) { $filesystem->makeDirectory($path, $mode, true); } }
Prepare destination directory. @param string $path @param int $mode @return void
entailment
protected function basePath(string $path): string { // This set of preg_match would filter ftp' user is not accessing // exact path as path('public'), in most shared hosting ftp' user // would only gain access to it's /home/username directory. if (\preg_match('/^\/(home)\/([a-zA-Z0-9]+)\/(.*)$/', $path, $matches)) { $path = '/'.\ltrim($matches[3], '/'); } return $path; }
Get base path for FTP. @param string $path @return string
entailment
protected function destination(string $name, bool $recursively = false): Fluent { $filesystem = $this->getContainer()['files']; $publicPath = $this->basePath($this->getContainer()['path.public']); // Start chmod from public/packages directory, if the extension folder // is yet to be created, it would be created and own by the web server // (Apache or Nginx). If otherwise, we would then emulate chmod -Rf $publicPath = \rtrim($publicPath, '/').'/'; $workingPath = $basePath = "{$publicPath}packages/"; // If the extension directory exist, we should start chmod from the // folder instead. if ($filesystem->isDirectory($folder = "{$basePath}{$name}/")) { $recursively = true; $workingPath = $folder; } // Alternatively if vendor has been created before, we need to // change the permission on the vendor folder instead of // public/packages. if (! $recursively && Str::contains($name, '/')) { [$vendor, ] = \explode('/', $name); if ($filesystem->isDirectory($folder = "{$basePath}{$vendor}/")) { $workingPath = $folder; } } return new Fluent([ 'workingPath' => $workingPath, 'basePath' => $basePath, 'resursively' => $recursively, ]); }
Check upload path. @param string $name @param bool $recursively @return \Illuminate\Support\Fluent
entailment
public function update(Processor $processor, $user) { return $processor->update($this, $user, Input::all()); }
Update the user. PUT (:orchestra)/users/$user @param \Orchestra\Foundation\Processors\User $processor @param int|string $user @return mixed
entailment
protected function getVates(){ return [ self::TAX_NONE, self::TAX_VAT0, self::TAX_VAT10, self::TAX_VAT110, self::TAX_VAT118, self::TAX_VAT18, ]; }
Получить все возможные налоговые ставки
entailment
protected function getVatAmount($amount, $vat){ switch($vat){ case self::TAX_NONE: case self::TAX_VAT0: return round(0, 2); case self::TAX_VAT10: case self::TAX_VAT110: return round($amount * 10 / 110, 2); case self::TAX_VAT18: case self::TAX_VAT118: return round($amount * 18 / 118, 2); default : throw new SdkException('Unknown vat'); } }
Получить сумму налога @param float $amount
entailment
public function processNode(Node $node, Scope $scope): array { $messages = []; $nodeIdentifier = $node->name; if (null === $nodeIdentifier) { return $messages; } $name = $nodeIdentifier->name; if (0 === \strpos($name, 'AnonymousClass')) { return $messages; } $fqcn = $node->namespacedName->toString(); if ($node instanceof Interface_) { if (! \preg_match('/Interface$/', $name)) { $messages[] = \sprintf('Interface %s should end with "Interface" suffix.', $fqcn); } } elseif ($node instanceof Trait_) { if (! \preg_match('/Trait$/', $name)) { $messages[] = \sprintf('Trait %s should end with "Trait" suffix.', $fqcn); } } else { $classRef = $this->broker->getClass($fqcn)->getNativeReflection(); if ($classRef->isAbstract()) { if (false !== \strpos($name, '_')) { $match = \preg_match('/_Abstract[^_]+$/', $name); } else { $match = \preg_match('/^Abstract/', $name); } if (! $match) { $messages[] = \sprintf('Abstract class %s should start with "Abstract" prefix.', $fqcn); } } if ($classRef->isSubclassOf(\Exception::class)) { if (! \preg_match('/Exception$/', $name)) { $messages[] = \sprintf('Exception class %s should end with "Exception" suffix.', $fqcn); } } } return $messages; }
@param \PhpParser\Node\Stmt\ClassLike $node @param \PHPStan\Analyser\Scope $scope @return string[] errors
entailment
protected function registerAssembleCommand() { $this->app->singleton('orchestra.commands.assemble', function (Application $app) { $foundation = $app->make('orchestra.app'); return new AssembleCommand($foundation, $foundation->memory()); }); }
Register the command. @return void
entailment
public function reports($auth_token, $report_uid, $detailed = true, $with_content = true) { return new B2BResponse($this->client->apiRequest( 'get', sprintf('dev/user/reports/%s', urlencode((string) $report_uid)), [ '_detailed' => (bool) $detailed ? 'true' : 'false', '_content' => (bool) $with_content ? 'true' : 'false', ], [ 'Authorization' => (string) $auth_token, ], $this->client->isTest() ? new Response( 200, $this->getTestingResponseHeaders(), file_get_contents(__DIR__ . '/reports.json') ) : null )); }
Запрос отчетов в режиме имитации. @param string $auth_token Токен безопасности @param string $report_uid UID отчета @param bool $detailed Детализация @param bool $with_content Включить контент в ответ @throws B2BApiException @return B2BResponse
entailment
public function getStackValueWithDot($path, $default = null) { if (($current = $this->getAccessorStack()) && 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 handle($request, Closure $next) { $this->beforeSendingThroughPipeline(); $response = $next($request); $this->afterSendingThroughPipeline(); return $response; }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public static function rowcol( $row = 1, $col = 1 ) { $row = intval($row); $col = intval($col); if( $row < 0 ) { $row = Misc::rows() + $row + 1; } if( $col < 0 ) { $col = Misc::cols() + $col + 1; } fwrite(self::$stream, "\033[{$row};{$col}f"); }
Move the cursor to a specific row and column @param int $row @param int $col
entailment
public static function wrap( $wrap = true ) { if( $wrap ) { fwrite(self::$stream, "\033[?7h"); } else { fwrite(self::$stream, "\033[?7l"); } }
Enable/Disable Auto-Wrap @param bool $wrap
entailment
public function buildForm(array $form, FormStateInterface $form_state, $gid = 0) { // Загружаем группу по идентификатору. $group = $this->database->characteristicsReadGroup($gid); // Скрытые поля. $form['group'] = array( '#type' => 'value', '#value' => $group, ); // Вспомогательный текст при редактировании группы. $form['text'] = array( '#type' => 'markup', '#markup' => $this->t('You are editing group № @gid.', ['@gid' => isset($group->gid) ? $group->gid : 0]), '#access' => isset($group->gid) ? TRUE : FALSE, ); $form['tid'] = array( '#type' => 'entity_autocomplete', '#title' => $this->t('Category'), '#target_type' => 'taxonomy_term', '#autocreate' => array( 'bundle' => 'site_commerce', ), '#access' => isset($group->gid) ? FALSE : TRUE, ); $form['title'] = array( '#type' => 'textfield', '#title' => $this->t('Title'), '#maxlength' => 255, '#required' => TRUE, '#default_value' => isset($group->gid) ? $group->title : "", ); $form['description'] = array( '#type' => 'textfield', '#title' => $this->t('Description'), '#maxlength' => 255, '#required' => FALSE, '#default_value' => isset($group->gid) ? $group->description : "", ); $form['status'] = array( '#title' => $this->t('Display'), '#type' => 'checkbox', '#default_value' => 1, '#access' => isset($group->gid) ? FALSE : TRUE, ); $form['parametr'] = array( '#title' => $this->t('Use the characteristics of the group as a parameter when ordering product'), '#type' => 'checkbox', '#default_value' => 0, '#access' => isset($group->gid) ? FALSE : TRUE, ); // 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) { $group = $form_state->getValue('group'); $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($group->gid) && $title) { $uuid = \Drupal::service('uuid'); $data = array( 'uuid' => $uuid->generate(), 'langcode' => $langcode, 'title' => $title, 'description' => $description, ); $return_created = $this->database->characteristicsCreateGroup($data); if ($return_created && $form_state->getValue('tid')) { $data = array( 'tid' => $form_state->getValue('tid'), 'gid' => $return_created, 'status' => $form_state->getValue('status'), 'parametr' => $form_state->getValue('parametr'), 'weight' => 0, ); $this->database->characteristicsCreateGroupIndex($data); } } else { // Выполняем если обновляется элемент. $entry = array( 'gid' => $group->gid, 'title' => $title, 'description' => $description, ); $return_updated = $this->database->characteristicsUpdateGroup($entry); } if ($return_created) { drupal_set_message($this->t('Group «@title» created.', array('@title' => $form_state->getValue('title')))); } if ($return_updated) { drupal_set_message($this->t('Group «@title» updated.', array('@title' => $form_state->getValue('title')))); $form_state->setRedirect('site_commerce.characteristics_editor'); } }
{@inheritdoc}
entailment
protected function convertToArray($value) { // Если получен массив - то просто кидаем его в raw if (\is_array($value)) { return $value; } if (\is_string($value)) { // Если влетела строка - то считаем что это json, и пытаемся его разобрать $json = json_decode($value, true); if (\is_array($json) && \json_last_error() === JSON_ERROR_NONE) { return $json; } } elseif (\is_object($value) && \method_exists($value, 'toArray')) { // Если прилетел объект, и у него есть метод 'convertToArray' - то его и используем return $value->toArray(); } elseif ($value instanceof Response) { // Немного рекурсии не помешает ;) return $this->convertToArray($value->getBody()->getContents()); } }
Преобразует прилетевший в метод объект - в массив. В противном случае вернёт null. @param array|string|Response|object|null $value @return array|null
entailment
public function submitForm(array &$form, FormStateInterface $form_state) { $entity = $this->getEntity(); $duplicate = $entity->createDuplicate(); $duplicate->setTitle($this->t('Duplicate') . ": " . $duplicate->label()); $duplicate->save(); $form_state->setRedirect('entity.site_commerce.collection'); }
{@inheritdoc} Delete the entity and log the event. log() replaces the watchdog.
entailment
public function buildForm(array $form, FormStateInterface $form_state, $pid = 0, $clone_pid = 0) { $form['#theme'] = 'site_commerce_product_version_form'; // Получаем объект товара. // Позиция к которой будет привязан товар. $site_commerce = \Drupal::entityTypeManager()->getStorage('site_commerce'); $position = $site_commerce->load($pid); $form['position'] = array( '#type' => 'hidden', '#value' => $position, ); // Позиция для копирования. $title = NULL; $min = 0; $unit = NULL; $description_catalog = NULL; if ($clone_pid) { $position_clone = $site_commerce->load($clone_pid); $title = $position_clone->getTitle(); $min = $position_clone->get('field_quantity')->min; $unit = $position_clone->get('field_quantity')->unit; $description_catalog = $position_clone->get('field_category_summary')->value; // Формируем стоимость позиции. $group = 1; $cost = getCostValueForUserPriceGroup($position_clone, $group, FALSE, FALSE); $form['position_clone'] = array( '#type' => 'hidden', '#value' => $position_clone, ); $form['title_position_clone'] = array( '#type' => 'hidden', '#value' => $title, ); } $form['title'] = array( '#type' => 'textfield', '#title' => $this->t('Title'), '#default_value' => $title, '#empty_value' => '', '#maxlength' => 255, ); $form['min'] = array( '#type' => 'number', '#title' => $this->t('Minimum order quantity'), '#default_value' => $min, '#empty_value' => '1', '#maxlength' => 255, ); $form['unit'] = array( '#type' => 'select', '#title' => $this->t('Unit of quantity'), '#options' => getUnitMeasurement(), '#default_value' => $unit, '#empty_value' => '', ); $form['cost'] = array( '#type' => 'number', '#title' => $this->t('Price'), '#default_value' => $cost['value'] ? $cost['value'] : '0.00', '#step' => '0.01', '#min' => '0', ); $form['currency'] = array( '#type' => 'select', '#title' => $this->t('Currency'), '#options' => getCurrency(), '#default_value' => $cost['currency'], ); $form['status_catalog'] = array( '#type' => 'checkbox', '#title' => $this->t('Publishing status in catalog'), '#default_value' => TRUE, ); $form['replace'] = array( '#type' => 'checkbox', '#title' => $this->t('Copy with replace'), '#default_value' => TRUE, '#description' => $this->t('The original product from which you are copying will be removed from the settings. The card of the original item will remain.'), ); $form['description_catalog'] = array( '#type' => 'textarea', '#title' => $this->t('Description in catalog'), '#default_value' => $description_catalog, '#rows' => 1, ); $form['copy_description_catalog'] = array( '#type' => 'checkbox', '#title' => $this->t('Copy the text to the short description of the item card'), '#default_value' => TRUE, ); $form['description'] = array( '#type' => 'textarea', '#title' => $this->t('Description'), '#description' => $this->t('Description of the parameter settings of the product. A brief transcript.'), '#default_value' => NULL, '#rows' => 1, ); $form['photo'] = [ '#name' => 'photo', '#type' => 'managed_file', '#multiple' => FALSE, '#title' => $this->t("Add photo"), '#upload_validators' => [ 'file_validate_extensions' => ['jpg jpeg png'], 'file_validate_size' => [25600000], 'file_validate_image_resolution' => ['1920x1080'], ], '#upload_location' => 'public://upload-files/', ]; // Добавляем нашу кнопку для сохранения. $form['actions']['#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) { $database = Database::getConnection(); // Позиция для клонирования. $position_clone = $form_state->getValue('position_clone'); // Позиция товара для привязки. $position = $form_state->getValue('position'); // Введенные параметры. $title = trim($form_state->getValue('title')); $title_position_clone = $position_clone->getTitle(); if ($title == $title_position_clone) { $title = $title . ' (' . $this->t('Clone') . ')'; } $description_catalog = trim($form_state->getValue('description_catalog')); $description = trim($form_state->getValue('description')); $cost = $form_state->getValue('cost'); if (!$cost) { $cost = '0.00'; } // Клонируем текущий товар. $clone = $position_clone->createDuplicate(); $clone->setTitle($title); $clone->set('status_catalog', $form_state->getValue('status_catalog')); $clone->set('field_cost', [ 'group' => 1, 'prefix' => '', 'from' => '0.00', 'value' => $cost, 'currency' => $form_state->getValue('currency'), ]); $clone->set('field_quantity', [ 'min' => $form_state->getValue('min'), 'unit' => $form_state->getValue('unit'), 'visible' => 1, ]); $clone->set('field_category_summary', [ 'value' => $description_catalog, ]); if ($form_state->getValue('copy_description_catalog') && $description_catalog) { $clone->set('field_summary', [ 'value' => $description_catalog, 'format' => 'basic_html', ]); } // Очищаем параметры и привязку к категории. $clone->set('field_parametrs', []); $clone->set('field_category', []); $clone->save(); // Привязка клонированного товара к новой категории. $clone->set('field_category', [ 'target_id' => $position->field_category->target_id, ]); // Сохраняем изображения товара. $destination = 'public://images/products'; file_prepare_directory($destination, FILE_CREATE_DIRECTORY); $image_fid = $form_state->getValue('photo'); if (isset($image_fid[0])) { // Очишаем текущие фото. $clone->set('field_image', []); $clone->save(); $file_form = file_load($image_fid[0]); if ($file_form) { if ($file = file_move($file_form, $destination, FILE_EXISTS_RENAME)) { $clone->field_image = [ 'uid' => $clone->getOwnerId(), 'target_id' => $file->id(), 'alt' => Html::escape($title), ]; } } } else { // Изменяем описание файлов изображений. $database->update('site_commerce__field_image') ->fields([ 'field_image_alt' => Html::escape($title), ]) ->condition('entity_id', $clone->id()) ->execute(); } $clone->save(); // Привязка клонированного товара в качестве параметра выбранного товара. if ($form_state->getValue('replace')) { $database->update('site_commerce__field_parametrs') ->fields([ 'field_parametrs_target_id' => $clone->id(), 'field_parametrs_name' => $title, 'field_parametrs_description' => $description, 'field_parametrs_select' => TRUE, ]) ->condition('entity_id', $position->id()) ->condition('field_parametrs_target_id', $position_clone->id()) ->execute(); } else { // Создаем новую привязку созданного товара. $position->field_parametrs[] = [ 'target_id' => $clone->id(), 'name' => $title, 'description' => $description, 'select' => TRUE, ]; $position->save(); } // Перенаправление. $url = Url::fromRoute('entity.site_commerce.canonical', [ 'site_commerce' => $position->id(), ]); $form_state->setRedirectUrl($url); }
{@inheritdoc}
entailment
protected function registerPublisher(): void { $this->app->singleton('orchestra.publisher', function (Application $app) { $memory = $app->make('orchestra.platform.memory'); return (new PublisherManager($app))->attach($memory); }); }
Register the service provider for publisher. @return void
entailment
protected function registerRoleEloquent(): void { $this->app->bind('orchestra.role', function () { $model = $this->getConfig('models.role', Role::class); return new $model(); }); }
Register the service provider for user. @return void
entailment
protected function registerUserEloquent(): void { $this->app->bind('orchestra.user', function () { $model = $this->getConfig('models.user', User::class); return new $model(); }); }
Register the service provider for user. @return void
entailment
public function autocomplete(Request $request) { // Получаем строку запроса ($_GET['q']). $string = $request->query->get('q'); $matches = []; $matches_id = []; if ($string) { $string_array = explode(" ", $string); $request = ''; $arguments = array(); $i = 1; $count_array_string = count($string_array); foreach ($string_array as $key) { $arguments[':key' . $i] = $key; if ($count_array_string > $i) { $request .= 'INSTR(i.title, :key' . $i . ') > 0 AND '; } else { $request .= 'INSTR(i.title, :key' . $i . ') > 0'; } $i++; } $query = \Drupal::database()->select('site_commerce_field_data', 'i'); $query->fields('i', array('pid', 'type', 'title')); $query->where($request, $arguments); $query->orderBy('i.title', 'ASC'); $query->range(0, 15); $result = $query->execute(); foreach ($result as $row) { if (!array_key_exists($row->pid, $matches_id)) { $matches_id[$row->pid] = $row->pid; $value = Html::escape($row->title); $matches[] = ['value' => $row->pid, 'label' => 'pid:' . $row->pid . ':' . $row->type . ' — ' . $value]; } } } return new JsonResponse($matches); }
{@inheritdoc}
entailment
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $element = []; $element['group'] = array( '#type' => 'select', '#title' => $this->t('Price group'), '#options' => array('0' => $this->t('None'), '1' => $this->t('Default')), '#default_value' => isset($items[$delta]->group) ? $items[$delta]->group : 0, '#empty_value' => 0, '#theme_wrappers' => [], ); $element['prefix'] = array( '#type' => 'textfield', '#title' => $this->t('Price prefix'), '#default_value' => isset($items[$delta]->prefix) ? $items[$delta]->prefix : null, '#empty_value' => '', '#maxlength' => 255, ); $element['from'] = array( '#type' => 'number', '#title' => $this->t('Price from'), '#default_value' => isset($items[$delta]->from) ? $items[$delta]->from : 0, '#empty_value' => '', '#step' => '0.01', '#min' => '0', '#theme_wrappers' => [], ); $element['value'] = array( '#type' => 'number', '#title' => $this->t('Price'), '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : 0, '#empty_value' => '', '#step' => '0.01', '#min' => '0', '#theme_wrappers' => [], ); $element['currency'] = array( '#type' => 'select', '#title' => $this->t('Currency'), '#options' => getCurrency(), '#default_value' => isset($items[$delta]->currency) ? $items[$delta]->currency : null, '#theme_wrappers' => [], ); $element['suffix'] = array( '#type' => 'textfield', '#title' => $this->t('Price suffix'), '#default_value' => isset($items[$delta]->suffix) ? $items[$delta]->suffix : null, '#empty_value' => '', '#maxlength' => 255, ); $element['#theme'] = 'site_commerce_cost_default_widget'; return $element; }
{@inheritdoc}
entailment
public function getActiveFrom() { return ! empty($value = $this->getContentValue('active_from', null)) ? $this->convertToCarbon($value) : null; }
Возвращает дату/время, с которого активен. @return Carbon|null
entailment
public function getActiveTo() { return ! empty($value = $this->getContentValue('active_to', null)) ? $this->convertToCarbon($value) : null; }
Возвращает дату/время, по которые активен. @return Carbon|null
entailment
public function edit(Listener $listener) { $user = Auth::user(); $form = $this->presenter->profile($user, 'orchestra::account'); $this->fireEvent('form', [$user, $form]); return $listener->showProfileChanger(['eloquent' => $user, 'form' => $form]); }
Get account/profile information. @param \Orchestra\Contracts\Foundation\Listener\Account\ProfileUpdater $listener @return mixed
entailment
public function update(Listener $listener, array $input) { $user = Auth::user(); if (! $this->validateCurrentUser($user, $input)) { return $listener->abortWhenUserMismatched(); } $validation = $this->validator->on('update')->with($input); if ($validation->fails()) { return $listener->updateProfileFailedValidation($validation->getMessageBag()); } try { $this->saving($user, $input); } catch (Exception $e) { return $listener->updateProfileFailed(['error' => $e->getMessage()]); } return $listener->profileUpdated(); }
Update profile information. @param \Orchestra\Contracts\Foundation\Listener\Account\ProfileUpdater $listener @param array $input @return mixed
entailment
protected function saving($user, array $input) { $user->setAttribute('email', $input['email']); $user->setAttribute('fullname', $input['fullname']); $this->fireEvent('updating', [$user]); $this->fireEvent('saving', [$user]); $user->saveOrFail(); $this->fireEvent('updated', [$user]); $this->fireEvent('saved', [$user]); }
Save user profile. @param \Orchestra\Foundation\Auth\User $user @param array $input @return void
entailment
public function countProducts($status = 1, $tid = 0) { $query = $this->connection->select('site_commerce_field_data', 'n'); if ($status < 2) { $query->condition('n.status', $status); } $query->addExpression('COUNT(pid)', 'pid_count'); $tids = []; if ($term = \Drupal\taxonomy\Entity\Term::load($tid)) { if ($term->field_view->value) { $tids[] = $term->id(); } $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($term->getVocabularyId(), $term->id(), NULL, TRUE); foreach ($terms as $term) { // Проверяем разрешено или нет отображать текущую категорию в каталоге. // Как правило запрещено отображать страницы фильтры по каталогу. if ($term->field_view->value) { $tids[] = $term->id(); } } if (count($tids)) { $query->innerJoin('site_commerce__field_category', 't', 't.entity_id=n.pid'); $query->condition('t.field_category_target_id', $tids, 'IN'); } } return $query->execute()->fetchField(); }
Возвращает количество товаров в зависимости от статуса и категории. @param int $status @param int $tid @return void
entailment
public function loadProducts($tid, $status = 1) { $loadProducts = &drupal_static(__FUNCTION__); if (!isset($loadProducts)) { $query = $this->connection->select('site_commerce_field_data', 'n'); $query->fields('n', array('pid', 'title')); if ($status < 2) { $query->condition('n.status', $status); } $query->innerJoin('site_commerce__field_category', 't', 't.entity_id=n.pid'); $query->condition('t.field_category_target_id', $tid); $loadProducts = $query->execute()->fetchAllKeyed(); } return $loadProducts; }
Возвращает объекты товаров в зависимости от статуса и категории. @param int $status @param int $tid @return void
entailment
public function priceEditorUpdate($data) { $site_commerce = \Drupal::entityTypeManager()->getStorage('site_commerce')->load($data['pid']); $site_commerce->field_cost->from = $data['from']; $site_commerce->field_cost->value = $data['value']; $site_commerce->field_quantity->unit = $data['unit']; $site_commerce->save(); }
Обновляет значение параметров в редакторе цен.
entailment
public function positionSetWeight($entry) { $update = $this->connection->update('site_commerce_field_data') ->fields(array('weight' => $entry['weight'])) ->condition('pid', $entry['pid']); return $update->execute(); }
Обновляет вес позиции привязанных к категории.
entailment
public function loadFile($type, $id) { $query = $this->connection->select('file_usage', 'n'); $query->fields('n', array('fid')); $query->condition('n.module', 'site_commerce'); $query->condition('n.type', $type); $query->condition('n.id', $id); $fid = $query->execute()->fetchField(); $file = null; if ($fid) { $file = File::load($fid); } return $file; }
Загружает информацию о файле.
entailment
public function characteristicsCreateGroup($entry) { $insert = $this->connection->insert('site_commerce_characteristics_group')->fields($entry); return $insert->execute(); }
Создает группу характеристик товара.
entailment
public function characteristicsUpdateGroup($entry) { $update = $this->connection->update('site_commerce_characteristics_group') ->fields($entry) ->condition('gid', $entry['gid']); return $update->execute(); }
Обновляет группу характеристик товара.
entailment
public function characteristicsDeleteGroup($gid) { // Удаляем из таблиц, в которых используется группа. $query = $this->connection->delete('site_commerce_characteristics_group'); $query->condition('gid', $gid); $query->execute(); $query = $this->connection->delete('site_commerce_characteristics_group_index'); $query->condition('gid', $gid); $query->execute(); // Все характеристики входящие в группу. Удаляем в цикле. $characteristics_items = $this->characteristicsReadItems($gid); foreach ($characteristics_items as $cid => $title) { $this->characteristicsDeleteItem($cid); } }
Удаляет характеристику товара.
entailment
public function characteristicsCreateGroupIndex($entry) { $insert = $this->connection->insert('site_commerce_characteristics_group_index')->fields($entry); return $insert->execute(); }
Создает привязку группы характеристик товара к категории товаров.
entailment
public function characteristicsReadGroupIndex($gid) { $query = $this->connection->select('site_commerce_characteristics_group_index', 'n'); $query->fields('n'); $query->condition('gid', $gid); return $query->execute()->fetchObject(); }
Загружает привязку группы характеристик к категории товаров.
entailment
public function characteristicsUpdateGroupIndex($entry) { $update = $this->connection->update('site_commerce_characteristics_group_index') ->fields($entry) ->condition('tid', $entry['tid']) ->condition('gid', $entry['gid']); return $update->execute(); }
Обновляет привязку группы характеристики товара к категории.
entailment
public function characteristicsCreateItem($entry) { $insert = $this->connection->insert('site_commerce_characteristics_item')->fields($entry); return $insert->execute(); }
Создает характеристику товара.
entailment
public function characteristicsUpdateItem($entry) { $update = $this->connection->update('site_commerce_characteristics_item') ->fields($entry) ->condition('cid', $entry['cid']); return $update->execute(); }
Обновляет характеристику товара.
entailment
public function characteristicsDeleteItem($cid) { // Удаляем из таблиц, в которых используется параметр. $query = $this->connection->delete('site_commerce_characteristics_item'); $query->condition('cid', $cid); $query->execute(); $query = $this->connection->delete('site_commerce_characteristics_item_index'); $query->condition('cid', $cid); $query->execute(); $query = $this->connection->delete('site_commerce_characteristics_data'); $query->condition('cid', $cid); $query->execute(); // Удаляем файлы связанные с параметром. $file_usage = \Drupal::service('file.usage'); if ($file_current_usage = $this->loadFile('characteristic', $cid)) { $file_usage->delete($file_current_usage, 'site_commerce', 'characteristic', $cid); $file_current_usage->status = 0; $file_current_usage->save(); } }
Удаляет характеристику товара.
entailment
public function characteristicsCreateItemIndex($entry) { $insert = $this->connection->insert('site_commerce_characteristics_item_index')->fields($entry); return $insert->execute(); }
Создает привязку характеристики товара к группе характеристик.
entailment
public function characteristicsReadItemIndex($cid) { $query = $this->connection->select('site_commerce_characteristics_item_index', 'n'); $query->fields('n'); $query->condition('cid', $cid); return $query->execute()->fetchObject(); }
Загружает привязку характеристики товара к группе характеристик. Возвращает массив.
entailment
public function characteristicsUpdateItemIndex($entry) { $update = $this->connection->update('site_commerce_characteristics_item_index') ->fields($entry) ->condition('cid', $entry['cid']) ->condition('gid', $entry['gid']); return $update->execute(); }
Обновляет привязку характеристики товара к группе характеристик.
entailment
public function characteristicsReadGroups() { $query = $this->connection->select('site_commerce_characteristics_group', 'n'); $query->fields('n', array('gid', 'title')); $loadGroups = $query->execute()->fetchAllKeyed(); return $loadGroups; }
Загружает все группы характеристик. Возвращает массив.
entailment
public function characteristicsReadGroupsByCategory($tid) { $query = $this->connection->select('site_commerce_characteristics_group', 'n'); $query->fields('n', array('gid', 'title')); $query->join('site_commerce_characteristics_group_index', 'i', 'n.gid = i.gid'); $query->condition('i.tid', $tid); $loadItems = $query->execute()->fetchAllKeyed(); return $loadItems; }
Загружает все группы характеристик по категории. Возвращает массив.
entailment
public function characteristicsReadItems($gid) { $query = $this->connection->select('site_commerce_characteristics_item_index', 'n'); $query->fields('n', array('cid')); $query->condition('n.gid', $gid); $query->join('site_commerce_characteristics_item', 'i', 'n.cid = i.cid'); $query->fields('i', array('title')); $loadItems = $query->execute()->fetchAllKeyed(); return $loadItems; }
Загружает все характеристики по выбранной группе характеристик.
entailment
public function characteristicsProductReadItems($pid, $gid) { // Получаем группы параметры. $query = $this->connection->select('site_commerce_characteristics_data', 'n'); $query->fields('n', array('cid')); $query->condition('n.pid', $pid); $query->condition('n.gid', $gid); $query->join('site_commerce_characteristics_item', 'i', 'n.cid = i.cid'); $query->fields('i', array('title')); $loadItems = $query->execute()->fetchAllKeyed(); return $loadItems; }
Загружает все активные характеристики по выбранной группе характеристик и товару.
entailment
public function characteristicDataCreateItem($entry) { $insert = $this->connection->insert('site_commerce_characteristics_data')->fields($entry); return $insert->execute(); }
Создает привязку характеристики к товару.
entailment
public function characteristicDataReadItem($pid, $cid) { $query = $this->connection->select('site_commerce_characteristics_data', 'n'); $query->fields('n'); $query->condition('n.cid', $cid); $query->condition('n.pid', $pid); return $query->execute()->fetchObject(); }
Загружает привязку характеристики к товару.
entailment
public function characteristicDataUpdateItem($entry) { $update = $this->connection->update('site_commerce_characteristics_data') ->fields($entry) ->condition('cid', $entry['cid']) ->condition('pid', $entry['pid']); return $update->execute(); }
Обновляет привязку характеристики к товару.
entailment
public function characteristicDataReadProductItems($pid, $parametr = 0) { // Получаем группы параметры. $query = $this->connection->select('site_commerce_characteristics_data', 'n'); $query->fields('n', ['gid']); $query->condition('n.pid', $pid); $query->join('site_commerce_characteristics_group_index', 'i', 'i.gid = n.gid'); $query->condition('i.parametr', $parametr); $result = $query->execute(); $elements = []; foreach ($result as $row) { // Загружаем группу. $gid = $row->gid; $group = $this->characteristicsReadGroup($gid); $elements[$gid] = [ 'group' => $group, ]; // Получаем перечень зарегистрированных к товару характеристик из группы. $query = $this->connection->select('site_commerce_characteristics_data', 'n'); $query->fields('n'); $query->condition('n.pid', $pid); $query->condition('n.gid', $gid); $result_data = $query->execute(); foreach ($result_data as $row_data) { $characteristic = $this->characteristicsReadItem($row_data->cid); $elements[$gid] += [ 'characteristic' => $characteristic, 'fid' => $row_data->fid, 'cost' => $row_data->cost, 'unit' => $row_data->unit, 'value' => $row_data->value, 'status' => $row_data->status, 'use_in_title' => $row_data->use_in_title, ]; } } return $elements; }
Загружает объекты характеристик.
entailment
protected function addRequiredForSecretField(ValidatorResolver $resolver, $field, $hidden) { $resolver->sometimes($field, 'required', function ($input) use ($hidden) { return $input->$hidden == 'yes'; }); }
Add required for secret or password field. @param \Illuminate\Contracts\Validation\Validator $resolver @param string $field @param string $hidden @return void
entailment
public function show(Listener $listener) { $panes = $this->widget->make('pane.orchestra'); return $listener->showDashboard(['panes' => $panes]); }
View dashboard. @param \Orchestra\Contracts\Foundation\Listener\Account\ProfileDashboard $listener @return mixed
entailment