Commit 7c804b3c authored by Telenkov Ruslan's avatar Telenkov Ruslan

ALL TAASK

parent 3e60c79b
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
"drupal/backup_migrate": "^5.0", "drupal/backup_migrate": "^5.0",
"drupal/better_exposed_filters": "^5.0", "drupal/better_exposed_filters": "^5.0",
"drupal/bootstrap": "^3.24", "drupal/bootstrap": "^3.24",
"drupal/commerce": "^2.30",
"drupal/config_ignore": "^2.3", "drupal/config_ignore": "^2.3",
"drupal/config_pages": "^2.9", "drupal/config_pages": "^2.9",
"drupal/core": "^9.1", "drupal/core": "^9.1",
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "e9a9771504018aa49812e463441864e1", "content-hash": "c448fd18581abf3ff2baaf7cebe285d8",
"packages": [ "packages": [
{ {
"name": "asm89/stack-cors", "name": "asm89/stack-cors",
...@@ -106,6 +106,110 @@ ...@@ -106,6 +106,110 @@
"description": "Drupal code generator", "description": "Drupal code generator",
"time": "2020-12-05T05:59:11+00:00" "time": "2020-12-05T05:59:11+00:00"
}, },
{
"name": "commerceguys/addressing",
"version": "v1.3.0",
"source": {
"type": "git",
"url": "https://github.com/commerceguys/addressing.git",
"reference": "566febd56ca71e31dd383b014c4e1bec680507bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/commerceguys/addressing/zipball/566febd56ca71e31dd383b014c4e1bec680507bf",
"reference": "566febd56ca71e31dd383b014c4e1bec680507bf",
"shasum": ""
},
"require": {
"doctrine/collections": "~1.0",
"php": ">=7.3"
},
"require-dev": {
"ext-json": "*",
"mikey179/vfsstream": "1.*",
"phpunit/phpunit": "^9.5",
"squizlabs/php_codesniffer": "3.*",
"symfony/validator": "^4.4 || ^5.4"
},
"suggest": {
"symfony/validator": "to validate addresses"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"CommerceGuys\\Addressing\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bojan Zivanovic"
},
{
"name": "Damien Tournoud"
}
],
"description": "Addressing library powered by CLDR and Google's address data.",
"keywords": [
"address",
"internationalization",
"localization",
"postal"
],
"time": "2022-04-08T13:06:51+00:00"
},
{
"name": "commerceguys/intl",
"version": "v1.1.1",
"source": {
"type": "git",
"url": "https://github.com/commerceguys/intl.git",
"reference": "cab3b55dbf8c1753fe54457404082c777a8c154f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/commerceguys/intl/zipball/cab3b55dbf8c1753fe54457404082c777a8c154f",
"reference": "cab3b55dbf8c1753fe54457404082c777a8c154f",
"shasum": ""
},
"require": {
"php": ">=7.1.3"
},
"require-dev": {
"mikey179/vfsstream": "1.*",
"phpunit/phpunit": "^7.5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"CommerceGuys\\Intl\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Bojan Zivanovic"
}
],
"description": "Internationalization library powered by CLDR data.",
"time": "2021-10-30T18:07:14+00:00"
},
{ {
"name": "composer/installers", "name": "composer/installers",
"version": "v1.12.0", "version": "v1.12.0",
...@@ -1745,6 +1849,79 @@ ...@@ -1745,6 +1849,79 @@
"abandoned": "roave/better-reflection", "abandoned": "roave/better-reflection",
"time": "2020-10-27T21:46:55+00:00" "time": "2020-10-27T21:46:55+00:00"
}, },
{
"name": "drupal/address",
"version": "1.10.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/address.git",
"reference": "8.x-1.10"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/address-8.x-1.10.zip",
"reference": "8.x-1.10",
"shasum": "bbe61eb51da9d9b2a7ab247f90426836eb9b6f25"
},
"require": {
"commerceguys/addressing": "^1.2.0",
"drupal/core": "^9.2 || ^10",
"php": "^7.3 || ^8.0"
},
"require-dev": {
"drupal/token": "^1.0"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.10",
"datestamp": "1643715226",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "Centarro",
"homepage": "https://www.drupal.org/user/3661446"
},
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "dww",
"homepage": "https://www.drupal.org/user/46549"
},
{
"name": "googletorp",
"homepage": "https://www.drupal.org/user/386230"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "mglaman",
"homepage": "https://www.drupal.org/user/2416470"
},
{
"name": "rszrama",
"homepage": "https://www.drupal.org/user/49344"
}
],
"description": "Provides functionality for storing, validating and displaying international postal addresses.",
"homepage": "http://drupal.org/project/address",
"support": {
"source": "https://git.drupalcode.org/project/address"
}
},
{ {
"name": "drupal/admin_toolbar", "name": "drupal/admin_toolbar",
"version": "3.1.0", "version": "3.1.0",
...@@ -2091,6 +2268,93 @@ ...@@ -2091,6 +2268,93 @@
"issues": "https://www.drupal.org/project/issues/captcha" "issues": "https://www.drupal.org/project/issues/captcha"
} }
}, },
{
"name": "drupal/commerce",
"version": "2.30.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/commerce.git",
"reference": "8.x-2.30"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/commerce-8.x-2.30.zip",
"reference": "8.x-2.30",
"shasum": "45cf6a7e09b0aa318f3dce063254c1a8ed503e60"
},
"require": {
"commerceguys/intl": "^1.0.0",
"drupal/address": "^1.7",
"drupal/core": "^9.2 || ^10",
"drupal/entity": "^1.0",
"drupal/entity_reference_revisions": "~1.0",
"drupal/inline_entity_form": "^1.0@RC",
"drupal/profile": "^1.2",
"drupal/state_machine": "^1.5",
"drupal/token": "^1.7",
"ext-bcmath": "*",
"php": "^7.3 || ^8.0"
},
"conflict": {
"drupal/commerce_shipping": "<2.1"
},
"require-dev": {
"drupal/commerce_cart": "*",
"drupal/commerce_number_pattern": "*",
"drupal/commerce_order": "*",
"drupal/commerce_payment": "*",
"drupal/commerce_price": "*",
"drupal/commerce_product": "*",
"drupal/commerce_store": "*",
"drupal/entity_print": "^2.2",
"drupal/entity_reference_revisions": "*",
"drupal/mailsystem": "^4.3",
"drupal/profile": "*",
"drupal/state_machine": "*"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-2.30",
"datestamp": "1649341535",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0+"
],
"authors": [
{
"name": "Centarro",
"homepage": "https://www.drupal.org/user/3661446"
},
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "mglaman",
"homepage": "https://www.drupal.org/user/2416470"
},
{
"name": "rszrama",
"homepage": "https://www.drupal.org/user/49344"
}
],
"description": "Drupal Commerce is a flexible eCommerce solution.",
"homepage": "http://drupal.org/project/commerce",
"support": {
"source": "https://git.drupalcode.org/project/commerce"
}
},
{ {
"name": "drupal/config_filter", "name": "drupal/config_filter",
"version": "2.3.0", "version": "2.3.0",
...@@ -2840,6 +3104,75 @@ ...@@ -2840,6 +3104,75 @@
"source": "https://git.drupalcode.org/project/devel_php" "source": "https://git.drupalcode.org/project/devel_php"
} }
}, },
{
"name": "drupal/entity",
"version": "1.3.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/entity.git",
"reference": "8.x-1.3"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/entity-8.x-1.3.zip",
"reference": "8.x-1.3",
"shasum": "9515e28a70448d369adf4199d08a01a5ab75792d"
},
"require": {
"drupal/core": "^8.8.2 || ^9"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.3",
"datestamp": "1646324539",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "Berdir",
"homepage": "https://www.drupal.org/user/214652"
},
{
"name": "TR",
"homepage": "https://www.drupal.org/user/202830"
},
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "dawehner",
"homepage": "https://www.drupal.org/user/99340"
},
{
"name": "dixon_",
"homepage": "https://www.drupal.org/user/239911"
},
{
"name": "fago",
"homepage": "https://www.drupal.org/user/16747"
},
{
"name": "mglaman",
"homepage": "https://www.drupal.org/user/2416470"
}
],
"description": "Provides expanded entity APIs, which will be moved to Drupal core one day.",
"homepage": "https://www.drupal.org/project/entity",
"support": {
"source": "https://git.drupalcode.org/project/entity",
"issues": "https://www.drupal.org/project/issues/entity"
}
},
{ {
"name": "drupal/entity_reference_revisions", "name": "drupal/entity_reference_revisions",
"version": "1.9.0", "version": "1.9.0",
...@@ -3182,6 +3515,98 @@ ...@@ -3182,6 +3515,98 @@
"source": "https://git.drupalcode.org/project/fontawesome_menu_icons" "source": "https://git.drupalcode.org/project/fontawesome_menu_icons"
} }
}, },
{
"name": "drupal/inline_entity_form",
"version": "1.0.0-rc11",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/inline_entity_form.git",
"reference": "8.x-1.0-rc11"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/inline_entity_form-8.x-1.0-rc11.zip",
"reference": "8.x-1.0-rc11",
"shasum": "67a92ec1482be19b2f2091ca9498f585e34072b9"
},
"require": {
"drupal/core": "^8.8 || ^9",
"php": ">=7.1"
},
"require-dev": {
"drupal/entity_reference_revisions": "^1.0"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.0-rc11",
"datestamp": "1648748863",
"security-coverage": {
"status": "not-covered",
"message": "RC releases are not covered by Drupal security advisories."
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "Centarro",
"homepage": "https://www.drupal.org/user/3661446"
},
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "dawehner",
"homepage": "https://www.drupal.org/user/99340"
},
{
"name": "geek-merlin",
"homepage": "https://www.drupal.org/user/229048"
},
{
"name": "joachim",
"homepage": "https://www.drupal.org/user/107701"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "kaythay",
"homepage": "https://www.drupal.org/user/2182186"
},
{
"name": "oknate",
"homepage": "https://www.drupal.org/user/471638"
},
{
"name": "ram4nd",
"homepage": "https://www.drupal.org/user/601534"
},
{
"name": "rszrama",
"homepage": "https://www.drupal.org/user/49344"
},
{
"name": "slashrsm",
"homepage": "https://www.drupal.org/user/744628"
},
{
"name": "webflo",
"homepage": "https://www.drupal.org/user/254778"
}
],
"description": "Provides a widget for inline management (creation, modification, removal) of referenced entities.",
"homepage": "https://www.drupal.org/project/inline_entity_form",
"support": {
"source": "https://git.drupalcode.org/project/inline_entity_form"
}
},
{ {
"name": "drupal/jquery_ui", "name": "drupal/jquery_ui",
"version": "1.4.0", "version": "1.4.0",
...@@ -3936,6 +4361,74 @@ ...@@ -3936,6 +4361,74 @@
"documentation": "https://www.drupal.org/docs/8/modules/pathauto" "documentation": "https://www.drupal.org/docs/8/modules/pathauto"
} }
}, },
{
"name": "drupal/profile",
"version": "1.4.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/profile.git",
"reference": "8.x-1.4"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/profile-8.x-1.4.zip",
"reference": "8.x-1.4",
"shasum": "253fd577c3b791c93747bb910ad2ae8e67d71eed"
},
"require": {
"drupal/core": "^8.9 || ^9 || ^10",
"drupal/entity": "^1.0-rc2"
},
"require-dev": {
"drupal/token": "^1.7"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.4",
"datestamp": "1652430373",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "daggerhart",
"homepage": "https://www.drupal.org/user/167806"
},
{
"name": "fago",
"homepage": "https://www.drupal.org/user/16747"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "mglaman",
"homepage": "https://www.drupal.org/user/2416470"
},
{
"name": "pcambra",
"homepage": "https://www.drupal.org/user/122101"
}
],
"description": "Provides configurable user profiles.",
"homepage": "http://drupal.org/project/profile",
"support": {
"source": "https://git.drupalcode.org/project/profile"
}
},
{ {
"name": "drupal/queue_ui", "name": "drupal/queue_ui",
"version": "3.0.0", "version": "3.0.0",
...@@ -4651,6 +5144,103 @@ ...@@ -4651,6 +5144,103 @@
"issues": "https://www.drupal.org/project/issues/smtp" "issues": "https://www.drupal.org/project/issues/smtp"
} }
}, },
{
"name": "drupal/state_machine",
"version": "1.6.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/state_machine.git",
"reference": "8.x-1.6"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/state_machine-8.x-1.6.zip",
"reference": "8.x-1.6",
"shasum": "9a29e00e4c47202fd4b27be792d18d2026f733b2"
},
"require": {
"drupal/core": "^9.2 || ^10",
"php": ">=7.0.8"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.6",
"datestamp": "1644836575",
"security-coverage": {
"status": "covered",
"message": "Covered by Drupal's security advisory policy"
}
}
},
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "Brandonian",
"homepage": "https://www.drupal.org/user/77766"
},
{
"name": "Elijah Lynn",
"homepage": "https://www.drupal.org/user/353190"
},
{
"name": "arithmetric",
"homepage": "https://www.drupal.org/user/162305"
},
{
"name": "bojanz",
"homepage": "https://www.drupal.org/user/86106"
},
{
"name": "das-peter",
"homepage": "https://www.drupal.org/user/762870"
},
{
"name": "e2thex",
"homepage": "https://www.drupal.org/user/189123"
},
{
"name": "ericduran",
"homepage": "https://www.drupal.org/user/244460"
},
{
"name": "fmitchell",
"homepage": "https://www.drupal.org/user/213574"
},
{
"name": "indytechcook",
"homepage": "https://www.drupal.org/user/245817"
},
{
"name": "jsacksick",
"homepage": "https://www.drupal.org/user/972218"
},
{
"name": "robeano",
"homepage": "https://www.drupal.org/user/67660"
},
{
"name": "stevector",
"homepage": "https://www.drupal.org/user/179805"
},
{
"name": "timcosgrove",
"homepage": "https://www.drupal.org/user/118452"
},
{
"name": "zroger",
"homepage": "https://www.drupal.org/user/67977"
}
],
"description": "Provides code-driven workflow functionality.",
"homepage": "http://drupal.org/project/state_machine",
"support": {
"source": "https://git.drupalcode.org/project/state_machine"
}
},
{ {
"name": "drupal/token", "name": "drupal/token",
"version": "1.10.0", "version": "1.10.0",
......
...@@ -36,14 +36,11 @@ use Drupal\Core\Datetime\Element\Datetime; ...@@ -36,14 +36,11 @@ use Drupal\Core\Datetime\Element\Datetime;
foreach ($context['sandbox']['items'] as $row_item) { foreach ($context['sandbox']['items'] as $row_item) {
//если счетчик не достиг лимита то закидываем каждый элемент //если счетчик не достиг лимита то закидываем каждый элемент
if ($counter != $limit) { if ($counter != $limit) {
// $this->processItem($row_item,$service);
self::processItem($row_item,$service); self::processItem($row_item,$service);
$counter++; $counter++;
$count++; $count++;
$context['sandbox']['progress']++; $context['sandbox']['progress']++;
// $context['message'] = $this->t('Now processing node' . $counter);
// $context['message'] = t('Now processing Batch API overview', array('Batch API overview' => $counter));
$context['message'] = t('Now processing node :progress of :count', [ $context['message'] = t('Now processing node :progress of :count', [
':progress' => $context['sandbox']['progress'], ':progress' => $context['sandbox']['progress'],
':count' => $context['sandbox']['max'], ':count' => $context['sandbox']['max'],
...@@ -60,6 +57,7 @@ use Drupal\Core\Datetime\Element\Datetime; ...@@ -60,6 +57,7 @@ use Drupal\Core\Datetime\Element\Datetime;
// Increment total processed item values. Will be used in finished // Increment total processed item values. Will be used in finished
// callback. // callback.
$context['results']['processed'] += $count; $context['results']['processed'] += $count;
//изначально финиш равен 1, если я уберу условие то цикл 1 раз пройдет, пока финиш меньше он будет вновь и вновь заходить
// If not finished all tasks, we count percentage of process. 1 = 100%. // If not finished all tasks, we count percentage of process. 1 = 100%.
if ($context['sandbox']['progress'] != $context['sandbox']['max']) { if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max']; $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
......
...@@ -39,40 +39,41 @@ class BatchCommands extends DrushCommands ...@@ -39,40 +39,41 @@ class BatchCommands extends DrushCommands
*/ */
public function goApi($date = null) public function goApi($date = null)
{ {
//дата 0 - не ввели дату
if ($date === null){ if ($date === null){
$this->output()->writeln('Вы не ввели дату'); $this->output()->writeln('Вы не ввели дату');
} }
else { else {
$timestamp = strtotime($date); $timestamp = strtotime($date); //перевод даты в нужный формат
$service = \Drupal::service('myservice.my'); $service = \Drupal::service('myservice.my'); //обраение к сервису
$request = $service->getResult('https://swapi.dev/api/'); $request = $service->getResult('https://swapi.dev/api/'); // получение адресов апи
foreach ($request as $api_url) { foreach ($request as $api_url) { //цикл для каждого url апишки
$url = $api_url; $url = $api_url;
do { do {
$request_items = $service->getResult($url); $request_items = $service->getResult($url); // обращаюсь к сервису, получаю уже на основе точного url элементы
$result_items = $request_items->results; // выкинул служебную информацию $result_items = $request_items->results; // выкинул служебную информацию, более структурировано выглядит
foreach ($result_items as $row_item) { foreach ($result_items as $row_item) { //прохожусь по каждому элементу
$timestamp_swapi = strtotime($row_item->edited); $timestamp_swapi = strtotime($row_item->edited); // получаю дату со свапи
if ($timestamp < $timestamp_swapi) { if ($timestamp < $timestamp_swapi) { //если дата меньше чем дата свапи, делаею дальнейшую обработку элемента
$type = $service->nodeType($row_item->url); // получаю ID ноды для дальнейшей проверки из БД $type = $service->nodeType($row_item->url); // получаю ID ноды для дальнейшей проверки из БД
$id = $service->nodeId($row_item->url); // получаю тип ноды для дальнейшей проверки из БД $id = $service->nodeId($row_item->url); // получаю тип ноды для дальнейшей проверки из БД
$nids = $service->existNode($type, $id); // вызываю функцию проверки ноды в БД, если есть, то вернется ID $nids = $service->existNode($type, $id); // вызываю функцию проверки ноды в БД, если есть, то вернется ID
$this->output()->writeln('Обработана сущность: ' . $type . $id); $this->output()->writeln('Обработана сущность: ' . $type . $id); // более корректный вывод в самой команде
if (empty($nids)) { if (empty($nids)) {
$service->createNode($row_item); // вызываю метод создания ноды из сервиса $service->createNode($row_item); // вызываю метод создания ноды из сервиса
$service->updateNode($row_item); $service->updateNode($row_item); // сразу апдейт, чтобы 2 раза не запускать прогу , если нод реферанца нет - создат и свяжет ТОЛЬКО на нужную референц
} else { } else {
$service->updateNode($row_item); $service->updateNode($row_item);
} }
} }
} }
$url = $request_items->next; $url = $request_items->next; // меняем УРЛ чтобы перейти на следующую страницу в апи
} while ($url); } while ($url); // пока есть урл, т е пока у меня есть следующая страница
} }
} }
} }
......
...@@ -120,7 +120,7 @@ class DrushSettingsForm extends FormBase { ...@@ -120,7 +120,7 @@ class DrushSettingsForm extends FormBase {
/** /**
* Processor for batch operations. * Processor for batch operations.
*/ */
public function processItems($items,array &$context) { /* public function processItems($items,array &$context) {
// Elements per operation. // Elements per operation.
$limit = 5; $limit = 5;
...@@ -191,10 +191,11 @@ class DrushSettingsForm extends FormBase { ...@@ -191,10 +191,11 @@ class DrushSettingsForm extends FormBase {
$service->updateNode($row_item); $service->updateNode($row_item);
} }
} }
*/
/** /**
* Finished callback for batch. * Finished callback for batch.
*/ */
/*
public function finished($success, $results, $operations) { public function finished($success, $results, $operations) {
$message = $this->t('Number of nodes affected by batch: @count', [ $message = $this->t('Number of nodes affected by batch: @count', [
'@count' => $results['processed'], '@count' => $results['processed'],
...@@ -202,5 +203,5 @@ class DrushSettingsForm extends FormBase { ...@@ -202,5 +203,5 @@ class DrushSettingsForm extends FormBase {
$this->messenger() $this->messenger()
->addStatus($message); ->addStatus($message);
} }
*/
} }
...@@ -15,6 +15,7 @@ function formApi_theme($existing, $type, $theme, $path) { ...@@ -15,6 +15,7 @@ function formApi_theme($existing, $type, $theme, $path) {
* Обработчик переменных для первого примера. * Обработчик переменных для первого примера.
*/ */
function template_preprocess_form_theme(&$variables) { function template_preprocess_form_theme(&$variables) {
$myConfigPage = \Drupal\config_pages\Entity\ConfigPages::config('custom_config'); $myConfigPage = \Drupal\config_pages\Entity\ConfigPages::config('custom_config');
$variables['string_modal'] = $myConfigPage->get('field_modal_title')->value; $variables['string_modal'] = $myConfigPage->get('field_modal_title')->value;
$current_user = \Drupal::currentUser(); $current_user = \Drupal::currentUser();
......
...@@ -88,7 +88,7 @@ class FormApiTask extends FormBase { ...@@ -88,7 +88,7 @@ class FormApiTask extends FormBase {
//ВАЛИДАЦИЯ адреса сайта //ВАЛИДАЦИЯ адреса сайта
//она зависит от того, выбрал ли я нужную радиокнопку. Если выбрано "у меня нет сайта" , то валидация не нужна //она зависит от того, выбрал ли я нужную радиокнопку. Если выбрано "у меня нет сайта" , то валидация не нужна
if ($form_state->getValue('radio') === '1') { if ($form_state->getValue('radio') === '1') { //выбрал "У меня есть сайт"
$reg = '/(https?:\/\/)?(www.)?([\da-z\.-]+)\.([a-z\.]{2,6})/ui'; $reg = '/(https?:\/\/)?(www.)?([\da-z\.-]+)\.([a-z\.]{2,6})/ui';
if (preg_match($reg, $form_state->getValue('site_address'), $array_of_site_address)) { if (preg_match($reg, $form_state->getValue('site_address'), $array_of_site_address)) {
// Если пользователь повторно ввел все нормально в это поле, то при сабмите сбросим красную рамку // Если пользователь повторно ввел все нормально в это поле, то при сабмите сбросим красную рамку
...@@ -173,9 +173,6 @@ class FormApiTask extends FormBase { ...@@ -173,9 +173,6 @@ class FormApiTask extends FormBase {
$response->addCommand(new AddCssCommand($style)); $response->addCommand(new AddCssCommand($style));
} }
//после валидации обращаюсь к БД и заполняю поля у таблицы //после валидации обращаюсь к БД и заполняю поля у таблицы
if ($valid_email && $valid_name && ($valid_site_address || $radio)){ if ($valid_email && $valid_name && ($valid_site_address || $radio)){
......
...@@ -25,12 +25,11 @@ class DrupalLocalTask { ...@@ -25,12 +25,11 @@ class DrupalLocalTask {
} }
public function swapi($node){ public function swapi($node){
$perms = array_keys(\Drupal::service('user.permissions')->getPermissions()); // $perms = array_keys(\Drupal::service('user.permissions')->getPermissions());
$type = $node->getType(); $type = $node->getType();
$id = $node->get('field_swapi_id')->value; $id = $node->get('field_swapi_id')->value;
$conc = 'https://swapi.dev/api/'.$type.'/'.$id.'/'; $conc = 'https://swapi.dev/api/'.$type.'/'.$id.'/';
$request = $this->getResult($conc); $request = $this->getResult($conc);
// $request = json_encode($request);
return [ return [
'#markup' => $request, '#markup' => $request,
......
...@@ -112,7 +112,7 @@ class MyService ...@@ -112,7 +112,7 @@ class MyService
// проверяю, если у ноды есть связанная сущность // проверяю, если у ноды есть связанная сущность
$array_of_related_fields = ['species','films', 'starships', 'vehicles' , 'characters' , 'planets' , 'pilots' , 'people', 'residents' ]; $array_of_related_fields = ['species','films', 'starships', 'vehicles' , 'characters' , 'planets' , 'pilots' , 'people', 'residents' ];
//foreach ($row_item as $key => $value){
foreach ($array_of_related_fields as $related_field){ foreach ($array_of_related_fields as $related_field){
if (!empty($row_item->related_field)){ if (!empty($row_item->related_field)){
$array = $row_item->$related_field; $array = $row_item->$related_field;
...@@ -215,7 +215,7 @@ class MyService ...@@ -215,7 +215,7 @@ class MyService
$node = Node::create(array( $node = Node::create(array(
'type' => 'people' , 'type' => 'people' ,
'title' => $data->name, 'title' => $data->name,
//'field_swapi_id' => $node_id, 'field_swapi_id' => $node_id,
'field_name' =>$data->name, 'field_name' =>$data->name,
'field_height' =>$data->height, 'field_height' =>$data->height,
'field_mass' =>$data->mass, 'field_mass' =>$data->mass,
......
...@@ -5,7 +5,9 @@ use Drupal\node\NodeInterface; ...@@ -5,7 +5,9 @@ use Drupal\node\NodeInterface;
/** /**
* Implements hook_node_access(). * Implements hook_node_access().
*/ */
//хук для сокрытия кнопки редактирования для пользователей, которох нет в данной ноде в поле редакторы
function role_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) { function role_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
//получаю тип ноды текущей
$type = $node $type = $node
->bundle(); ->bundle();
...@@ -15,6 +17,7 @@ function role_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Se ...@@ -15,6 +17,7 @@ function role_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Se
$uid_role = $node->get('field_role')->target_id; $uid_role = $node->get('field_role')->target_id;
// id текущего пользователя // id текущего пользователя
$uid_now = $account->id(); $uid_now = $account->id();
//сравниваю айдишники и если равны то разрешаю доступ на редактирование
if ($uid_now == $uid_role) { if ($uid_now == $uid_role) {
return AccessResult::allowed(); return AccessResult::allowed();
} }
...@@ -28,22 +31,24 @@ function role_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Se ...@@ -28,22 +31,24 @@ function role_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Se
/** /**
* Implements hook_form_alter(). * Implements hook_form_alter().
*/ */
function role_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { function role_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
// если у меня форма редактирования ноды - редакторы это поле не видят и не могут менять
if ($form_id == 'node_editor_edit_form') { if ($form_id == 'node_editor_edit_form') {
$current_user = \Drupal::currentUser(); $current_user = \Drupal::currentUser();
if (in_array('redaktory', $current_user->getRoles())){ if (in_array('redaktory', $current_user->getRoles())){
$form['field_role']['#access'] = false; $form['field_role']['#access'] = false; // запрещаю доступ к полю
} }
} }
if ($form_id == 'node_editor_form') { if ($form_id == 'node_editor_form') { // если форма создания ноды - так же запрещаю видеть это поле редакторам
$current_user = \Drupal::currentUser(); $current_user = \Drupal::currentUser();
if (in_array('redaktory', $current_user->getRoles())){ if (in_array('redaktory', $current_user->getRoles())){
$form['field_role']['#access'] = false; $form['field_role']['#access'] = false;
} }
} }
} }
// хук позволяет вставить текущего редактора в поле, ведь у меня поле редактора скрыто
function role_node_insert(Drupal\Core\Entity\EntityInterface $entity) function role_node_insert(Drupal\Core\Entity\EntityInterface $entity)
{ {
$current_user = \Drupal::currentUser(); $current_user = \Drupal::currentUser();
......
...@@ -99,7 +99,7 @@ class GetUserByEmailResource extends ResourceBase { ...@@ -99,7 +99,7 @@ class GetUserByEmailResource extends ResourceBase {
'prev_page' => FALSE, 'prev_page' => FALSE,
]; ];
// page = 0; // page = 0;
// смоттрю параметры лимита и страницы которые передал пользователь и если они не переданы то выставляю дефолт // получаю параметры текущей страницы из запроса пользователя, если нет то выставляю дефолтные значения
$request = \Drupal::request(); $request = \Drupal::request();
$request_query = $request->query; $request_query = $request->query;
$request_query_array = $request_query->all(); $request_query_array = $request_query->all();
...@@ -108,9 +108,13 @@ class GetUserByEmailResource extends ResourceBase { ...@@ -108,9 +108,13 @@ class GetUserByEmailResource extends ResourceBase {
// Find out how many articles do we have. // Find out how many articles do we have.
// Узнаю, сколько всего у меня людей на сайте и устанавливаю предыдущую и следующую страницу // Узнаю, сколько всего у меня людей на сайте и устанавливаю предыдущую и следующую страницу
//колличество людей на сайте
$query = \Drupal::entityQuery('node')->condition('type', 'people'); $query = \Drupal::entityQuery('node')->condition('type', 'people');
$articles_count = $query->count()->execute(); $articles_count = $query->count()->execute();
// текущая позиция - лимит с шагом в 10
$position = $limit * ($page + 1); $position = $limit * ($page + 1);
//если колличество людей больше текущей позиции - задаю следующую страницу, получаю ее урл
if ($articles_count > $position) { if ($articles_count > $position) {
$next_page_query = $request_query_array; $next_page_query = $request_query_array;
$next_page_query['page'] = $page + 1; $next_page_query['page'] = $page + 1;
...@@ -121,7 +125,7 @@ class GetUserByEmailResource extends ResourceBase { ...@@ -121,7 +125,7 @@ class GetUserByEmailResource extends ResourceBase {
} }
$response['count'] = $articles_count; $response['count'] = $articles_count;
// если мы перешли на следующую страницу - нужно сделать предыдущую по аналогии
if ($page > 0) { if ($page > 0) {
$prev_page_query = $request_query_array; $prev_page_query = $request_query_array;
$prev_page_query['page'] = $page - 1; $prev_page_query['page'] = $page - 1;
...@@ -248,11 +252,12 @@ foreach ($person_homeworld as $p_h){ ...@@ -248,11 +252,12 @@ foreach ($person_homeworld as $p_h){
} }
try { try {
// для каждого персонажа
foreach ($data as $row){ foreach ($data as $row){
//делаю запрос в БД для того чтобы узнать колличество нод которые у меня на сайте
$query = \Drupal::entityQuery('node')->condition('type', 'people'); $query = \Drupal::entityQuery('node')->condition('type', 'people');
$articles_count = $query->count()->execute(); $articles_count = $query->count()->execute();
++$articles_count; ++$articles_count; //нужно для свапи айди
$node = Node::create(array( $node = Node::create(array(
'type' => 'people' , 'type' => 'people' ,
'title' => $row['name'], 'title' => $row['name'],
...@@ -268,10 +273,10 @@ foreach ($person_homeworld as $p_h){ ...@@ -268,10 +273,10 @@ foreach ($person_homeworld as $p_h){
'langcode' => 'ru', 'langcode' => 'ru',
'status' => 1, 'status' => 1,
)); ));
// прохожусь по данным о фильме - айдишник и название
foreach ($row['films'] as $film){ foreach ($row['films'] as $film){
foreach ($film as $key => $value){ foreach ($film as $key => $value){
$array_films_keys[] = $key; $array_films_keys[] = $key; // вытягиваю айдишник
} }
} }
foreach ($row['species'] as $specie){ foreach ($row['species'] as $specie){
......
...@@ -5,16 +5,20 @@ use Drupal\Core\Cache\CacheableMetadata; ...@@ -5,16 +5,20 @@ use Drupal\Core\Cache\CacheableMetadata;
function mytheme_preprocess_node__people__full(&$variables) function mytheme_preprocess_node__people__full(&$variables)
{ {
//задаю кеш контекст для кеширования с разными параметрами
$variables['#cache'] = ([ $variables['#cache'] = ([
'contexts' => ['url.query_args'], 'contexts' => ['url.query_args'],
]); ]);
//проверяю вызываю параметр введеный пользователем
$param = \Drupal::request()->query; $param = \Drupal::request()->query;
$key = $param->get('tab'); $key = $param->get('tab');
$variables['test'] = false; $variables['test'] = false;
//если параметр равен films - вызываю код js который делает клик на таб фильмов
if ($key == 'films'){ if ($key == 'films'){
$variables['#attached']['library'][] = 'mytheme/test'; $variables['#attached']['library'][] = 'mytheme/test';
} }
// задаю переменные, которые являются полями ноды текущей
$variables['name'] = $variables['elements']['#node']->get('field_name')->value; $variables['name'] = $variables['elements']['#node']->get('field_name')->value;
$variables['height'] = $variables['elements']['#node']->get('field_height')->value; $variables['height'] = $variables['elements']['#node']->get('field_height')->value;
$variables['mass'] = $variables['elements']['#node']->get('field_mass')->value; $variables['mass'] = $variables['elements']['#node']->get('field_mass')->value;
...@@ -23,12 +27,13 @@ function mytheme_preprocess_node__people__full(&$variables) ...@@ -23,12 +27,13 @@ function mytheme_preprocess_node__people__full(&$variables)
$variables['eye_color'] = $variables['elements']['#node']->get('field_eye_color')->value; $variables['eye_color'] = $variables['elements']['#node']->get('field_eye_color')->value;
$variables['birth_year'] = $variables['elements']['#node']->get('field_birth_year')->value; $variables['birth_year'] = $variables['elements']['#node']->get('field_birth_year')->value;
$variables['gender'] = $variables['elements']['#node']->get('field_gender')->value; $variables['gender'] = $variables['elements']['#node']->get('field_gender')->value;
//получаю заголовок связанной сущности родной планеты
$homeworld_array = $variables['elements']['#node']->field_homeworld->referencedEntities(); $homeworld_array = $variables['elements']['#node']->field_homeworld->referencedEntities();
foreach ($homeworld_array as $key => $value){ foreach ($homeworld_array as $key => $value){
$value = $value->getTitle(); $value = $value->getTitle();
} }
$variables['homeworld'] = $value; $variables['homeworld'] = $value;
//получаю заголовок связанной сущности фильмов, закидыаю в массив, чтобы правильно вывести в шаблне уже
$films_array = $variables['elements']['#node']->field_films->referencedEntities(); $films_array = $variables['elements']['#node']->field_films->referencedEntities();
foreach ($films_array as $key => $value){ foreach ($films_array as $key => $value){
$value_films[] = $value->getTitle(); $value_films[] = $value->getTitle();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment