Commit 612b62b3 authored by Telenkov Ruslan's avatar Telenkov Ruslan

this is rest api task

parent e3741c51
......@@ -40,6 +40,7 @@
"drupal/rabbit_hole": "^2.26",
"drupal/recaptcha": "^3.0",
"drupal/redirect": "^1.7",
"drupal/restui": "^1.20",
"drupal/search_api": "^1.23",
"drupal/search_api_autocomplete": "^1.6",
"drupal/shariff": "^1.5",
......
......@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "f3d718dfa53852c7031069d608f69011",
"content-hash": "1b24d35c84763c2fdcf7e4fca5e5d99e",
"packages": [
{
"name": "asm89/stack-cors",
......@@ -4222,6 +4222,62 @@
"source": "https://git.drupalcode.org/project/redirect"
}
},
{
"name": "drupal/restui",
"version": "1.20.0",
"source": {
"type": "git",
"url": "https://git.drupalcode.org/project/restui.git",
"reference": "8.x-1.20"
},
"dist": {
"type": "zip",
"url": "https://ftp.drupal.org/files/projects/restui-8.x-1.20.zip",
"reference": "8.x-1.20",
"shasum": "df1d3c486ee0e7b4e9a24e6523a69c9efe73caff"
},
"require": {
"drupal/core": "^8.7.7 || ^9"
},
"type": "drupal-module",
"extra": {
"drupal": {
"version": "8.x-1.20",
"datestamp": "1616839543",
"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": "-enzo-",
"homepage": "https://www.drupal.org/user/294937"
},
{
"name": "clemens.tolboom",
"homepage": "https://www.drupal.org/user/125814"
},
{
"name": "juampynr",
"homepage": "https://www.drupal.org/user/682736"
},
{
"name": "klausi",
"homepage": "https://www.drupal.org/user/262198"
}
],
"description": "Provides a user interface to manage REST resources.",
"homepage": "https://www.drupal.org/project/restui",
"support": {
"source": "https://git.drupalcode.org/project/restui"
}
},
{
"name": "drupal/search_api",
"version": "1.23.0",
......
......@@ -214,8 +214,8 @@ class MyService
public function createPeopleNode($data, $node_id){
$node = Node::create(array(
'type' => 'people' ,
'title' => /*'people' . $counter[0][0]*/$data->name,
'field_swapi_id' => $node_id,
'title' => $data->name,
//'field_swapi_id' => $node_id,
'field_name' =>$data->name,
'field_height' =>$data->height,
'field_mass' =>$data->mass,
......
<?php
namespace Drupal\testblock\Plugin\rest\resource;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\node\Entity\Node;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\user\UserInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Drupal\Core\Url;
/**
* Provides a resource to get user by email.
*
* @RestResource(
* id = "get_user_by_email_resource",
* label = @Translation("Get user by email resource"),
* uri_paths = {
* "canonical" = "/api/v1/get-user-by-email",
* "create" = "/api/v1/get-user-by-email",
* }
* )
*/
class GetUserByEmailResource extends ResourceBase {
/**
* A current user instance.
*
* @var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* Default limit entities per request.
*/
protected $limit = 10;
/**
* Constructs a new ListArticlesResource object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param array $serializer_formats
* The available serialization formats.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
* @param \Drupal\Core\Session\AccountProxyInterface $current_user
* A current user instance.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
array $serializer_formats,
LoggerInterface $logger,
AccountProxyInterface $current_user) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->getParameter('serializer.formats'),
$container->get('logger.factory')->get('dummy'),
$container->get('current_user')
);
}
/**
* Responds to GET requests.
*/
public function get() {
if (!$this->currentUser->hasPermission('access content')) {
throw new AccessDeniedHttpException();
}
$cache = CacheableMetadata::createFromRenderArray([
'#cache' => [
'max-age' => 600,
'contexts' => ['url.query_args'],
],
]);
$response = [
'count' => 0,
'next_page' => FALSE,
'prev_page' => FALSE,
];
// page = 0;
// смоттрю параметры лимита и страницы которые передал пользователь и если они не переданы то выставляю дефолт
$request = \Drupal::request();
$request_query = $request->query;
$request_query_array = $request_query->all();
$limit = $request_query->get('limit') ?: $this->limit;
$page = $request_query->get('page') ?: 0;
// Find out how many articles do we have.
// Узнаю, сколько всего у меня людей на сайте и устанавливаю предыдущую и следующую страницу
$query = \Drupal::entityQuery('node')->condition('type', 'people');
$articles_count = $query->count()->execute();
$position = $limit * ($page + 1);
if ($articles_count > $position) {
$next_page_query = $request_query_array;
$next_page_query['page'] = $page + 1;
$response['next_page'] = Url::createFromRequest($request)
->setOption('query', $next_page_query)
->toString(TRUE)
->getGeneratedUrl();
}
$response['count'] = $articles_count;
if ($page > 0) {
$prev_page_query = $request_query_array;
$prev_page_query['page'] = $page - 1;
$response['prev_page'] = Url::createFromRequest($request)
->setOption('query', $prev_page_query)
->toString(TRUE)
->getGeneratedUrl();
}
// Find articles.
$query = \Drupal::entityQuery('node')
->condition('type', 'people')
->sort('created', 'DESC')
->pager($limit);
$result = $query->execute();
$articles = \Drupal::entityTypeManager()
->getStorage('node')
->loadMultiple($result);
/** @var \Drupal\node\Entity\Node $article */
foreach ($articles as $article) {
$rez_film = $this->getRelatedFilm($article,$cache);
if ($rez_film == NULL){
$rez_film = [];
}
$rez_species = $this->getRelatedSpecies($article);
if ($rez_species == NULL){
$rez_species = [];
}
$rez_vehicles = $this->getRelatedVehicles($article);
if ($rez_vehicles == NULL){
$rez_vehicles = [];
}
$rez_starships = $this->getRelatedStarships($article);
if ($rez_starships == NULL){
$rez_starships = [];
}
$rez_homeworld = $this->getRelatedHomeworld($article);
if ($rez_homeworld == NULL){
$rez_homeworld = [];
}
$response['results'][] = [
'name' => $article->get('field_name')->value,
'height' =>$article->get('field_height')->value ,
'mass' => $article->get('field_mass')->value,
'hair_color' => $article->get('field_hair_color')->value,
'skin_color' => $article->get('field_skin_color')->value,
'eye_color' => $article->get('field_eye_color')->value,
'birth_year' =>$article->get('field_birth_year')->value ,
'gender' => $article->get('field_gender')->value,
'homeworld' =>$rez_homeworld,
'films' => $rez_film,
'species' =>$rez_species,
'vehicles' =>$rez_vehicles,
'starships' =>$rez_starships,
'created' => $article->getCreatedTime(),
'edited' => $article->getChangedTime(),
'url' => $article->get('field_url')->value,
];
$cache->addCacheableDependency($article);
}
return (new ResourceResponse($response, 200))->addCacheableDependency($cache);
}
public function getRelatedFilm($article,&$cache){
$person_film = $article->field_films->referencedEntities();
foreach ($person_film as $film){
$cache->addCacheableDependency($film);
$res_film[] = [
$film->nid->value => $film->getTitle()
];
}
return $res_film;
}
public function getRelatedSpecies($article){
$person_spacie = $article->field_species->referencedEntities();
foreach ($person_spacie as $specie){
$res_specie[] = [
$specie->nid->value => $specie->getTitle()
];
}
return $res_specie;
}
public function getRelatedVehicles($article){
$person_vehicles = $article->field_vehicles->referencedEntities();
foreach ($person_vehicles as $vehicle){
$res_vehicles[] = [
$vehicle->nid->value => $vehicle->getTitle()
];
}
return $res_vehicles;
}
public function getRelatedStarships($article){
$person_starships = $article->field_starships->referencedEntities();
foreach ($person_starships as $starships){
$res_starships[] = [
$starships->nid->value => $starships->getTitle()
];
}
return $res_starships;
}
public function getRelatedHomeworld($article){
$person_homeworld = $article->field_homeworld->referencedEntities();
foreach ($person_homeworld as $p_h){
$res_homeworld[] = [
$p_h->nid->value => $p_h->getTitle()
];
}
return $res_homeworld;
}
public function post($data) {
if (!$this->currentUser->hasPermission('create article content')) {
throw new AccessDeniedHttpException();
}
try {
foreach ($data as $row){
$query = \Drupal::entityQuery('node')->condition('type', 'people');
$articles_count = $query->count()->execute();
++$articles_count;
$node = Node::create(array(
'type' => 'people' ,
'title' => $row['name'],
'field_swapi_id' => $articles_count,
'field_name' => $row['name'],
'field_height' => $row['height'],
'field_mass' =>$row['mass'],
'field_hair_color' =>$row['hair_color'],
'field_skin_color' =>$row['skin_color'],
'field_eye_color' =>$row['eye_color'],
'field_birth_year' =>$row['birth_year'],
'field_gender' =>$row['gender'],
'langcode' => 'ru',
'status' => 1,
));
foreach ($row['films'] as $film){
foreach ($film as $key => $value){
$array_films_keys[] = $key;
}
}
foreach ($row['species'] as $specie){
foreach ($specie as $key => $value){
$array_specie_keys[] = $key;
}
}
foreach ($row['vehicles'] as $vehicle){
foreach ($vehicle as $key => $value){
$array_vehicle_keys[] = $key;
}
}
foreach ($row['starships'] as $starship){
foreach ($starship as $key => $value){
$array_starship_keys[] = $key;
}
}
foreach ($row['homeworld'] as $homeworld){
foreach ($homeworld as $key => $value){
$array_homeworld_keys[] = $key;
}
}
$node->save();
$node->set('field_films',$array_films_keys);
$node->set('field_species',$array_specie_keys);
$node->set('field_vehicles',$array_vehicle_keys);
$node->set('field_starships',$array_starship_keys);
$node->set('field_homeworld',$array_homeworld_keys);
// $node->set('field_films',$array_films_keys);
$node->save();
}
return new ResourceResponse($node);
} catch (\Exception $e) {
return new ResourceResponse('Something went wrong during entity creation. Check your data.', 400);
}
}
}
name: Test
description: Creates a page showing "Bootcamp".
name: TestRestApi
description: Rest Api module
package: Custom
type: module
core_version_requirement: ^8.8 || ^9
dependencies:
- rest
<?php
namespace Drupal\thanks\Controller;
class TestPage {
public function content(){
/**
* {@inheritdoc}
*/
return [
'#theme' => 'dummy_example_first',
];
}
}
name: TestB
name: Test Hook Theme
description: Creates a page showing "Bootcamp".
package: Custom
type: module
......
<?php
/**
* Implements hook_theme().
*/
function thanks_theme($existing, $type, $theme, $path) {
return [
'dummy_example_first' => [
'variables' => [],
],
];
}
/**
* Implements template_preprocess_HOOK().
* Обработчик переменных для первого примера.
*/
function template_preprocess_dummy_example_first(&$variables) {
$date_formatter = \Drupal::service('date.formatter');
$variables['date'] = $date_formatter->format(time());
}
thanks.test-page:
path: '/test-page'
defaults:
_controller: '\Drupal\thanks\Controller\TestPage::content'
_title: 'Test'
requirements:
_permission: 'access content'
......@@ -9,6 +9,6 @@ parameters:
debug: true
auto_reload: true
cache: false
services:
cache.backend.null:
class: Drupal\Core\Cache\NullBackendFactory
#services:
# cache.backend.null:
# class: Drupal\Core\Cache\NullBackendFactory
......@@ -123,8 +123,8 @@ switch ($current_env) {
$settings['trusted_host_patterns'] = [];
// Disable caching during development.
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
$settings['cache']['bins']['page'] = 'cache.backend.null';
// $settings['cache']['bins']['render'] = 'cache.backend.null';
// $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
// $settings['cache']['bins']['page'] = 'cache.backend.null';
break;
}
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