Commit 1cc430a5 authored by Gorodkov Denis's avatar Gorodkov Denis

commit

parent fd76bad4
......@@ -2,8 +2,13 @@
namespace Drupal\mymodule\Plugin\rest\resource;
use Drupal\config_override_integration_test\CacheabilityMetadataConfigOverride;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use \Drupal\node\Entity\Node;
use \Drupal\Core\Cache\CacheableMetadata;
/**
* Provides a resource to get people
......@@ -12,54 +17,201 @@ use Drupal\rest\ResourceResponse;
* id = "get_people",
* label = @Translation("Get people"),
* uri_paths = {
* "canonical" = "/api/people"
* "canonical" = "/api/people",
* "create" = "/api/people/test"
* }
* )
*/
class GetPeople extends ResourceBase {
public function get() {
$query = \Drupal::request()->query->get('page');
if (empty($query)) {
$query = 1;
}
$cache = CacheableMetadata::createFromRenderArray([
'#cache' => [
'max-age' => 600,
'context' => ['url.query_args'],
],
]);
$query = \Drupal::request()->query;
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'type' => 'people'
]);
$nodes = array_values($nodes);
$count_nodes = count($nodes);
$number_last_page = (int)ceil($count_nodes/10);
$i = 0;
$response['count'] = $count_nodes;
$host = \Drupal::request()->getHost();
$host = 'http://' . $host . '/api/people?page=';
$response['count'] = count($nodes);
$response['next'] = '';
$response['previous'] = '';
$response['query'] = $query;
if ($query <= $number_last_page) {
if ($count_nodes > 10 and (empty($query) or $query == 1)) {
$response['next'] = $host . '2';
$response['previous'] = null;
} elseif ($query != $number_last_page) {
$response['next'] = $host . ($query + 1);
$response['previous'] = $host . ($query - 1);
} else {
$response['next'] = null;
$response['previous'] = $host . ($number_last_page - 1);
}
} else {
return new ResourceResponse('404 error');
}
if (!empty($query)) {
$i = ($query * 10) - 10;
}
foreach ($nodes as $node) {
if ($query == $number_last_page) {
$last_index = count($nodes);
} else {
$last_index = $query * 10;
}
$response['results'] = [];
for ($i; $i < $last_index; $i++) {
$node = $nodes[$i];
unset($result);
if (count($response['results']) < 11) {
$result['name'] = $node->label();
$result['height'] = $this->getFieldValue($node->field_height->getValue());
$result['mass'] = $this->getFieldValue($node->field_mass->getValue());
$result['hair_color'] = $this->getFieldValue($node->field_hair_color->getValue());
$result['skin_color'] = $this->getFieldValue($node->field_skin_color->getValue());
$result['eye_color'] = $this->getFieldValue($node->field_eye_color->getValue());
$result['birth_year'] = $this->getFieldValue($node->field_birth_year->getValue());
$result['gender'] = $this->getFieldValue($node->field_gender->getValue());
$result['height'] = $this->getFieldValue('field_height', $node);
$result['mass'] = $this->getFieldValue('field_mass', $node);
$result['hair_color'] = $this->getFieldValue('field_hair_color', $node);
$result['skin_color'] = $this->getFieldValue('field_skin_color', $node);
$result['eye_color'] = $this->getFieldValue('field_eye_color', $node);
$result['birth_year'] = $this->getFieldValue('field_birth_year', $node);
$result['gender'] = $this->getFieldValue('field_gender', $node);
$node_homeworld = $node->field_homeworld->referencedEntities();
$node_homeworld = $node_homeworld[0];
$result['homeworld']['id'] = $node_homeworld->id();
$result['homeworld']['label'] = $node_homeworld->label();
$items = $node->field_films->referencedEntities();
foreach ($items as $item) {
$obj = [
'id' => $item->id(),
'label' => $item->label(),
];
$result['films'][] = $obj;
}
$items = $node->field_species->referencedEntities();
if (!empty($items)) {
foreach ($items as $item) {
$obj = [
'id' => $item->id(),
'label' => $item->label(),
];
$result['species'][] = $obj;
}
} else {
$result['species'][] = null;
}
$items = $node->field_vehicles->referencedEntities();
if (!empty($items)) {
foreach ($items as $item) {
$obj = [
'id' => $item->id(),
'label' => $item->label(),
];
$result['vehicles'][] = $obj;
}
} else {
$result['vehicles'][] = null;
}
$items = $node->field_starships->referencedEntities();
if (!empty($items)) {
foreach ($items as $item) {
$obj = [
'id' => $item->id(),
'label' => $item->label(),
];
$result['starships'][] = $obj;
}
} else {
$result['starships'][] = null;
}
$created = $node->get('created')->getValue();
$created = date("Y-m-d H:i:s", (int)$created[0]['value']);
$result['created'] = $created;
$node_homeworld = $node->field_homeworld;
$result['homeworld'] = $node_homeworld;
$changed = $node->get('changed')->getValue();
$changed = date("Y-m-d H:i:s", (int)$changed[0]['value']);
$result['changed'] = $changed;
#$name = $node->label();
#$alias = Url::fromRoute('entity.node.canonical', ['node' => $node->id()])->toString();
$alias = $node->toUrl()->setAbsolute()->toString();
$result['url'] = $alias;
$response['results'][] = $result;
$cache->addCacheableDependency($node);
}
}
return new ResourceResponse($response);
return new JsonResponse($response);
}
public function post($data) {
if ($data['swapi_id']) {
if ($this->checkNode($data['swapi_id'])) {
return new ResourceResponse(['Нода с таким swapi_id уже существует!']);
}
if (isset($data['name'])) {
$node = Node::create([
'type' => 'people',
'title' => $data['name']
]);
foreach($data as $key => $value) {
if ($key == 'name') {
continue;
}
$field_name = "field_" . $key;
if ($node->hasField($field_name)) {
$node->set($field_name, $value);
} else {
return new ResourceResponse("$field_name данное поле не найдено");
}
}
$node->save();
return new ResourceResponse("Нода с названием {$data['name']} успешно создана");
} else {
return new ResourceResponse(['Укажите обязательное поле name!']);
}
} else {
return new ResourceResponse(['Укажите обязательное поле swapi_id!']);
}
}
public function getFieldValue($value) {
public function getFieldValue($field_name, $node) {
$value = $node->get($field_name)->getValue();
$value = $value[0]['value'];
return $value;
}
public function permissions()
{
public function checkNode($swapi_id) {
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'type' => 'people',
'field_swapi_id' => $swapi_id,
]);
if (!empty($nodes)) {
return true;
}
return false;
}
}
<?php
namespace Drupal\mymodule\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
* Provides a resource to get people
*
* @RestResource(
* id = "post_people",
* label = @Translation("Post people"),
* uri_paths = {
* "/create" = "/post_test",
* }
* )
*/
class PostPeople extends ResourceBase {
}
<?php
namespace Drupal\mymodule\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
/**
* Provides a resource to get people
*
* @RestResource(
* id = "get_people_test",
* label = @Translation("get_people_test"),
* uri_paths = {
* "/create" = "/post_test",
* }
* )
*/
class Test extends ResourceBase {
}
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