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('rout...
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 { ...
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); } } ...
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' => $characterist...
{@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()->g...
{@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' => getAppeara...
{@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 commer...
{@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/...
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->getLi...
@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; ...
{@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['logi...
Определяет тип данных, которые содержатся в ответе от сервиса 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 { dru...
{@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 (!$con...
Импорт каталога товаров.
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->flatte...
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 . $ro...
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('n...
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/...
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' => \Drup...
{@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', 'si...
{@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 (($do...
Извлекает имя домена из токена авторизации (если он в нем присутствует и токен корректный). @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($usern...
Извлекает имя пользователя из токена авторизации (если он в нем присутствует и токен корректный). Внимение! Извлекается имя пользователя без значения домена. @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_repl...
{@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()->sub...
Метод генерации токена авторизации. По умолчанию токен генерируется со временем жизни - 1 сутки. @param string $username Имя пользователя @param string $password Пароль пользователя @param string|null $domain Домен пользователя @param int $age Время жизни токена (unix-time, в секундах) @p...
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 - то // данные будут переданы в теле самого запроса ...
{@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('...
{@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'] = $name...
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->...
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'); ...
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.orches...
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') ->ti...
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.p...
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...
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); $objS...
{@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 ...
{@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->hasPositionInC...
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) ...
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 boo...
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.for...
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, ...
Информация о текущем пользователе. @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', ...
Проверка доступности квоты по 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.rese...
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...
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()) { retur...
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_i...
{@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 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 (! ...
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)) { re...
@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) { // Создаем новый термин. ...
{@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)) { ...
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; } ...
Возвращает значения из КОНТЕНТА отчета, обращаясь к нему с помощью 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_...
Возвращает строку 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->{...
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['...
{@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); ...
{@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->getVa...
{@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'; ...
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)) { r...
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)) { retur...
Transforms a resource into an object. @access public @param mixed $resource @return object @static
entailment