site files

This commit is contained in:
Ste Vaidis 2023-12-31 00:04:21 +02:00
parent 1de1c64261
commit a002064040
101 changed files with 3464 additions and 32 deletions

View File

@ -0,0 +1,8 @@
name: 'AAAAA bundle'
description: 'AAAAA bundle'
package: DOTSOFT
type: module
version: 1.0
core_version_requirement: ^10

View File

@ -0,0 +1,39 @@
bundle_AAAAA.node:
path: '/api/{lang}/AAAAAs/{alias}'
defaults:
_controller: 'Drupal\bundle_AAAAA\Controller\NodeController::getNode'
methods: [GET]
requirements:
_access: 'TRUE'
options:
no_cache: 'TRUE'
bundle_AAAAA.nodes:
path: '/api/{lang}/AAAAAs'
defaults:
_controller: 'Drupal\bundle_AAAAA\Controller\NodesController::getNodes'
methods: [GET]
requirements:
_access: 'TRUE'
options:
no_cache: 'TRUE'
# bundle_AAAAA.categories:
# path: '/api/{lang}/AAAAAs/categories'
# defaults:
# _controller: 'Drupal\bundle_AAAAA\Controller\CategoryController::getCategories'
# methods: [GET]
# requirements:
# _access: 'TRUE'
# options:
# no_cache: 'TRUE'
# bundle_AAAAA.nodes_category:
# path: '/api/{lang}/AAAAAs/categories/{category}'
# defaults:
# _controller: 'Drupal\bundle_AAAAA\Controller\NodesController::getNodes'
# methods: [GET]
# requirements:
# _access: 'TRUE'
# options:
# no_cache: 'TRUE'

View File

@ -0,0 +1,65 @@
<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class CategoryController extends ControllerBase {
private const VOCABULARY = 'AAAAA_category'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
// MAIN
public function getCategories(Request $request, $lang) {
$this->response = [
'code' => $this->statusCode,
'lang' => $lang,
'categories' => $this->buildVocabulary($lang)];
return new JsonResponse($this->response, $this->statusCode);
}
// RESPONSE ARRAY
private function buildVocabulary($lang): array {
$terms = $this->loadTerms($lang);
$terms_response = [];
foreach ($terms as $type) {
$terms_response[] = [
'id' => $type->id(),
'name' => $type->getName()
];
}
return $terms_response;
}
// RESPONSE ARRAY VALUES
private function loadTerms($lang) {
// All terms from the vocabulary
$terms=\Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties([
'vid' => self::VOCABULARY,
]);
// Current language only
$termList=[];
foreach($terms as $term) {
if($term->hasTranslation($lang)){
$tid = $term->id();
$translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $lang);
$termList[$tid] = $translated_term;
}
}
return $termList;
}
}

View File

@ -0,0 +1,163 @@
<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
use Drupal\media\Plugin\media\Source;
use Drupal\media\Entity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TempStore;
class NodeController extends ControllerBase {
private const FIELD_CATEGORY = 'field_AAAAA_category'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_NOT_FOUND = 404;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
// Main
public function getNode(Request $request, $lang, $alias) {
// check if alias exist in path
if (empty($alias)) {
$this->errorAliasMissing();
return new JsonResponse($this->response, $this->statusCode);
}
// check if alias exist in drupal
$path_alias = '/'.$alias;
$path = \Drupal::service('path_alias.manager')->getPathByAlias($path_alias);
if ( $path_alias == $path) {
$this->errorNodeNotExist($alias, $path);
return new JsonResponse($this->response, $this->statusCode);
}
// check if node has translation
$nid = Url::fromUri('internal:' . $path_alias)->getRouteParameters()['node'];
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
if (! $node->hasTranslation($lang)) {
$this->errorTranslationNotExist($lang, $alias);
return new JsonResponse($this->response, $this->statusCode);
}
// build response
$this->buildNodeResponse($lang, $alias);
return new JsonResponse($this->response, $this->statusCode);
}
// Response
private function buildNodeResponse($lang, $alias) {
$path = \Drupal::service('path_alias.manager')->getPathByAlias($alias);
$nid = Url::fromUri('internal:/' . $path)->getRouteParameters()['node'];
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid)->getTranslation($lang);
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
$this->response = [
'code' => $this->statusCode,
'alias' => $alias,
'path' => $path,
'nid' => $nid,
'title' => $node->get('title')->value,
'body' => $node->get('body')->value,
'lang' => $node->get('langcode')->value,
'alias' => $node->get('path')->alias,
'created' => $node->get('created')->value,
'author' => $name,
// 'files' => $this->getFiles($node, 'field_file'),
// 'images' => $this->getImages($node, 'field_image'),
// 'category' => $this->getTerms($node, self::FIELD_CATEGORY)
// // single value taxonomy field
// 'tag' => (
// $node
// ->get('field_tags')
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get('field_tags')->entity,
// $node->currentTranslation
// )->getName():''
];
}
// Multiple vallue fields
// private function getTerms(Node $node, string $field): array {
// $terms = $node->get($field)->referencedEntities();
// $response = [];
// foreach ($terms as $term) {
// $name = $term->getName();
// $tid = $term->id();
// $response[] = array(
// 'name' => $name,
// 'id' => $tid
// );
// }
// return $response;
// }
// private function getFiles(Node $node, string $field): array {
// $uris = [];
// foreach ($node->get($field) as $value) {
// $file = \Drupal::entityTypeManager()
// ->getStorage('file')
// ->load($value->getValue()['target_id']);
//
// $url = \Drupal::service('file_url_generator')
// ->generateAbsoluteString($file->getFileUri());
//
// $uris[] = array("url" => $url);
// }
// return $uris;
// }
// private function getImages(Node $node, string $field): array {
// $uris = [];
// foreach ($node->get($field)->getValue() as $value) {
// $file = \Drupal::entityTypeManager()
// ->getStorage('file')
// ->load($value['target_id']);
// $url = \Drupal::service('file_url_generator')
// ->generateAbsoluteString($file->getFileUri());
// $uris[] = array("url" => $url, "alt" => $value['alt']);
// }
// return $uris;
// }
// Error functions
private function errorNodeNotExist($alias, $path) {
$this->statusCode = self::HTTP_NOT_FOUND;
$this->response = [
'code' => $this->statusCode,
"message" => "Node with alias " . $alias . " does not exist." . $path
];
}
private function errorTranslationNotExist($lang, $alias) {
$this->statusCode = self::HTTP_NOT_FOUND;
$this->response = [
'code' => $this->statusCode,
"message" => "Node with alias " . $alias . " does not have a translation for language code " . $lang
];
}
private function errorAliasMissing() {
$this->statusCode = self::HTTP_BAD_REQUEST;
$this->response = [
'code' => $this->statusCode,
'message' => 'Query parameter "alias" is mandatory and is missing.'
];
}
// \Drupal::logger('hello')->notice(''.$nid);
}

View File

@ -0,0 +1,238 @@
<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
use Drupal\media\Plugin\media\Source;
use Drupal\media\Entity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TempStore;
class NodesController extends ControllerBase {
private const NODE_TYPE = 'AAAAA'; // Editable
// Taxonomy reference field
// Used for : optional URL argument
// Value : single ID of field_article_category value
// Example : /api/en/articles/1234
private const FIELD_CATEGORY = 'field_AAAAA_category'; // Editable
// Taxonomy reference field
// Used for : optional URL query params - accept multiple values
// Value : multiple ID's of field_article_subcategory values
// Example : /api/en/articles/1234?subcategory=55,66,77
private const FIELD_SUBCATEGORY = 'field_AAAAA_subcategory'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_NOT_FOUND = 404;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
// Main
public function getNodes(Request $request, $lang, $category = 'all') {
$nodes = $this->loadNodes($request, $lang, $category);
$nodes_response = $this->buildNodes($nodes, $lang, $category);
$this->response = [
'code' => $this->statusCode,
'count' => count($nodes_response),
'nodes' => $nodes_response
];
return new JsonResponse($this->response, $this->statusCode);
}
// Response List
private function buildNodes(array $nodes, $lang): array {
$nodes_response = [];
foreach ($nodes as $node) {
// don't show node if it hasn't translation
if ( $node->hasTranslation($lang)) {
$node = $node->getTranslation($lang);
$published = $node->get('status')->value;
// get user name
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
if ($published == 1) {
$nodes_response[] = [
'id' => $node->id(),
'title' => $node->getTitle(),
'body' => $node->get('body')->value,
'lang' => $node->get('langcode')->value,
'created' => $node->get('created')->value,
'alias' => $node->get('path')->alias,
'author' => $name,
// 'file' => $this->getFiles($node, 'field_file'),
// 'image' => $this->getImages($node, 'field_image'),
// 'category_id' => (
// $node
// ->get(self::FIELD_CATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_CATEGORY)->entity,
// $node->currentTranslation
// )->id():'',
// 'category_label' => (
// $node
// ->get(self::FIELD_CATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_CATEGORY)->entity,
// $node->currentTranslation
// )->getName():'',
// 'subcategory_id' => (
// $node
// ->get(self::FIELD_SUBCATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_SUBCATEGORY)->entity,
// $node->currentTranslation
// )->id():'',
// 'subcategory_label' => (
// $node
// ->get(self::FIELD_SUBCATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_SUBCATEGORY)->entity,
// $node->currentTranslation
// )->getName():'',
// 'terms' => $this->getTerms($node, 'field_tags')
];
}
}
}
return $nodes_response;
}
// Multivalue fields
private function getTerms(Node $node, string $field): array {
$terms = $node->get($field)->referencedEntities();
$response = [];
foreach ($terms as $term) {
$name = $term->getName();
$tid = $term->id();
$response[] = array(
'name' => $name,
'id' => $tid
);
}
return $response;
}
private function getFiles(Node $node, string $field): array {
$uris = [];
foreach ($node->get($field) as $value) {
$file = \Drupal::entityTypeManager()
->getStorage('file')
->load($value->getValue()['target_id']);
$url = \Drupal::service('file_url_generator')
->generateAbsoluteString($file->getFileUri());
$uris[] = array("url" => $url);
}
return $uris;
}
private function getImages(Node $node, string $field): array {
$uris = [];
foreach ($node->get($field)->getValue() as $value) {
$file = \Drupal::entityTypeManager()
->getStorage('file')
->load($value['target_id']);
$url = \Drupal::service('file_url_generator')
->generateAbsoluteString($file->getFileUri());
$uris[] = array("url" => $url, "alt" => $value['alt']);
}
return $uris;
}
// get response data
private function loadNodes($request, $lang, $category) {
// build query for nodes
$query = \Drupal::entityTypeManager()
->getStorage('node')
->getQuery()
->accessCheck(false);
// category is a URL parameter, matched with a taxonomy field
if ($category != 'all'){
$query->condition(self::FIELD_CATEGORY, $category);
}
// add subcategory URL query filter, matched with a taxonomy field
if ($request->query->get('subcategory')){
$or_group = $query->orConditionGroup();
$terms = explode(',', $request->query->get('subcategory'));
foreach ($terms as $term) {
$or_group->condition(self::FIELD_SUBCATEGORY.'.target_id', $term);
}
$query->condition($or_group);
}
// add pager
$query->range($request->get('start'), $request->get('length'));
// sort results by DESC or ASC
if ($request->get('sort')) {
$sort = $request->get('sort');
if(strcasecmp($sort, 'desc') == 0 || strcasecmp($sort, 'asc') == 0){
$sort = $request->get('sort');
}
else{
$sort = 'DESC';
}
}
else{
$sort = 'DESC';
}
// sort results by field
if ($request->get('sortby')) {
$sortby = $request->get('sortby');
if(strcasecmp($sortby, 'title') == 0 || strcasecmp($sortby, 'created') == 0){
$sortby = $request->get('sortby');
}
else{
$sortby = 'created';
}
}
else{
$sortby = 'created';
}
// execute query to get node ids
$nodeIds = $query
->condition('type', self::NODE_TYPE)
->sort($sortby, $sort, $lang)
->execute();
// get nodes from ids
$nodes=\Drupal::entityTypeManager()
->getStorage('node')
->loadMultiple($nodeIds);
// Response List
$nodeList=[];
foreach ($nodes as $node) {
$tid = $node->id();
$nodeList[$tid] = $node->hasTranslation($lang) ? $node->getTranslation($lang) : $node;
$node->currentTranslation = $lang;
}
return $nodeList;
}
// \Drupal::logger('Bundle AAAAA')->notice(''.$some_var);
}

View File

@ -0,0 +1,6 @@
name: 'Builders test'
description: 'Builders test'
package: Testing
type: module
version: 1.0

View File

@ -0,0 +1,101 @@
<?php
namespace Drupal\builders_test;
use Drupal\node\Entity\Node;
class ArticleBuilder {
private Node $node;
private int $typeId = 1;
private string $title = 'Title';
private string $description = 'Description';
private int $thumbnail = 1;
private int $authorId = 1;
private int $created = 1234567890;
private string $languageCode = 'en';
private string $summary;
private array $photos;
private array $videos;
private array $files;
private array $sources;
private array $links;
private string $facebookPage;
public function __construct() {
$this->node = Node::create([
'type' => 'article',
'langcode' => $this->languageCode,
'title' => $this->title,
'field_article_type' => $this->typeId,
'field_article_description' => $this->description,
'field_thumbnail' => $this->thumbnail,
'uid' => $this->authorId,
'created' => $this->created
]);
}
public static function create(): ArticleBuilder {
return new ArticleBuilder();
}
public function withLanguageCode(string $languageCode): ArticleBuilder {
$this->languageCode = $languageCode;
$this->node->set('langcode', $this->languageCode);
return $this;
}
public function withType(int $typeId): ArticleBuilder {
$this->typeId = $typeId;
$this->node->set('field_article_type', $this->typeId);
return $this;
}
public function withSummary(string $summary): ArticleBuilder {
$this->summary = $summary;
$this->node->set('field_summary', $this->summary);
return $this;
}
public function withPhotos(array $photos): ArticleBuilder {
$this->photos = $photos;
$this->node->set('field_article_photos', $this->photos);
return $this;
}
public function withVideos(array $videos): ArticleBuilder {
$this->videos = $videos;
$this->node->set('field_article_videos', $this->videos);
return $this;
}
public function withFiles(array $files): ArticleBuilder {
$this->files = $files;
$this->node->set('field_article_files', $this->files);
return $this;
}
public function withSources(array $sources): ArticleBuilder {
$this->sources = $sources;
$this->node->set('field_source', $this->sources);
return $this;
}
public function withLinks(array $links): ArticleBuilder {
$this->links = $links;
$this->node->set('field_url', $this->links);
return $this;
}
public function withFacebookPage(string $facebookPage): ArticleBuilder {
$this->facebookPage = $facebookPage;
$this->node->set('field_facebook_page', $this->facebookPage);
return $this;
}
public function build(): Node {
$this->node->save();
return $this->node;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace Drupal\builders_test;
use Drupal\taxonomy\Entity\Term;
class ArticleTypeBuilder {
private Term $term;
private string $languageCode = 'en';
private string $name = 'Type';
public function __construct() {
$this->term = Term::create([
'vid' => 'article_types',
'langcode' => $this->languageCode,
'name' => $this->name
]);
}
public static function create(): ArticleTypeBuilder {
return new ArticleTypeBuilder();
}
public function withLanguageCode(string $languageCode): ArticleTypeBuilder {
$this->languageCode = $languageCode;
$this->term->set('langcode', $this->languageCode);
return $this;
}
public function build(): Term {
$this->term->save();
return $this->term;
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Drupal\builders_test;
use Drupal\file\Entity\File;
class FileBuilder {
private File $file;
private string $baseUrl = 'https://example.com';
private string $fileName = 'filename.jpg';
public function __construct() {
$this->file = File::create([
'uri' => $this->baseUrl . '/' . $this->fileName
]);
}
public static function create(): FileBuilder {
return new FileBuilder();
}
public function withFileName(string $fileName): FileBuilder {
$this->fileName = $fileName;
$this->file->set('uri', $this->baseUrl . '/' . $this->fileName);
return $this;
}
public function build(): File {
$this->file->save();
return $this->file;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Drupal\builders_test;
use Drupal\node\Entity\Node;
class PageBuilder {
private Node $node;
private string $title = 'Title';
private string $languageCode = 'en';
public function __construct() {
$this->node = Node::create([
'type' => 'page',
'langcode' => $this->languageCode,
'title' => $this->title
]);
}
public static function create(): PageBuilder {
return new PageBuilder();
}
public function build(): Node {
$this->node->save();
return $this->node;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Drupal\builders_test;
use Drupal\user\Entity\User;
class UserBuilder {
private User $user;
private string $name = 'Name';
private string $surname = 'Surname';
public function __construct() {
$this->user = User::create([
'name' => $this->name . '@' . $this->surname . '.com',
'field_user_name' => $this->name,
'field_user_surname' => $this->surname
]);
}
public static function create(): UserBuilder {
return new UserBuilder();
}
public function build(): User {
$this->user->save();
return $this->user;
}
}

View File

@ -0,0 +1,6 @@
name: 'Article bundle test'
description: 'Article bundle test'
package: Testing
type: module
version: 1.0

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_description
- node.type.article
module:
- text
id: node.article.field_article_description
field_name: field_article_description
entity_type: node
bundle: article
label: 'Description'
description: ''
required: true
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long

View File

@ -0,0 +1,26 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_files
- node.type.article
module:
- file
id: node.article.field_article_files
field_name: field_article_files
entity_type: node
bundle: article
label: 'Files'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'txt rtf doc csv docx ppt pptx xls xlsx xlsm pdf odf odg odp ods odt fodt fods fodp fodg key numbers pages asc zip ppsx svg'
max_filesize: ''
description_field: false
handler: 'default:file'
handler_settings: { }
field_type: file

View File

@ -0,0 +1,37 @@
langcode: el
status: true
dependencies:
config:
- field.storage.node.field_article_photos
- node.type.article
module:
- image
id: node.article.field_article_photos
field_name: field_article_photos
entity_type: node
bundle: article
label: 'Photos'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'png gif jpg jpeg'
max_filesize: ''
max_resolution: ''
min_resolution: ''
alt_field: true
alt_field_required: true
title_field: true
title_field_required: false
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
handler: 'default:file'
handler_settings: { }
field_type: image

View File

@ -0,0 +1,28 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_type
- node.type.article
- taxonomy.vocabulary.article_types
id: node.article.field_article_type
field_name: field_article_type
entity_type: node
bundle: article
label: 'Article type'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
handler: 'default:taxonomy_term'
handler_settings:
target_bundles:
article_types: article_types
sort:
field: name
direction: asc
auto_create: false
auto_create_bundle: ''
field_type: entity_reference

View File

@ -0,0 +1,26 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_videos
- node.type.article
module:
- file
id: node.article.field_article_videos
field_name: field_article_videos
entity_type: node
bundle: article
label: 'Videos'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'mp4 ogv'
max_filesize: ''
description_field: false
handler: 'default:file'
handler_settings: { }
field_type: file

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_facebook_page
- node.type.article
module:
- link
id: node.article.field_facebook_page
field_name: field_facebook_page
entity_type: node
bundle: article
label: 'Facebook page'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
link_type: 17
title: 1
field_type: link

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_source
- node.type.article
module:
- link
id: node.article.field_source
field_name: field_source
entity_type: node
bundle: article
label: 'Sources'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
link_type: 17
title: 1
field_type: link

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_summary
- node.type.article
module:
- text
id: node.article.field_summary
field_name: field_summary
entity_type: node
bundle: article
label: 'Summary'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long

View File

@ -0,0 +1,37 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_thumbnail
- node.type.article
module:
- image
id: node.article.field_thumbnail
field_name: field_thumbnail
entity_type: node
bundle: article
label: 'Κεντρική φωτογραφία'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'png gif jpg jpeg'
max_filesize: ''
max_resolution: ''
min_resolution: ''
alt_field: true
alt_field_required: true
title_field: true
title_field_required: false
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
handler: 'default:file'
handler_settings: { }
field_type: image

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_url
- node.type.article
module:
- link
id: node.article.field_url
field_name: field_url
entity_type: node
bundle: article
label: 'Links'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
link_type: 17
title: 1
field_type: link

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
config:
- field.storage.user.field_user_name
module:
- user
id: user.user.field_user_name
field_name: field_user_name
entity_type: user
bundle: user
label: 'Name'
description: ''
required: true
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
config:
- field.storage.user.field_user_surname
module:
- user
id: user.user.field_user_surname
field_name: field_user_surname
entity_type: user
bundle: user
label: 'Surname'
description: ''
required: true
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- node
- text
id: node.field_article_description
field_name: field_article_description
entity_type: node
type: text_long
settings: { }
module: text
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
module:
- file
- node
id: node.field_article_files
field_name: field_article_files
entity_type: node
type: file
settings:
display_field: true
display_default: true
uri_scheme: public
target_type: file
module: file
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,29 @@
langcode: en
status: true
dependencies:
module:
- file
- image
- node
id: node.field_article_photos
field_name: field_article_photos
entity_type: node
type: image
settings:
uri_scheme: public
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
target_type: file
display_field: false
display_default: false
module: image
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
module:
- node
- taxonomy
id: node.field_article_type
field_name: field_article_type
entity_type: node
type: entity_reference
settings:
target_type: taxonomy_term
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
module:
- file
- node
id: node.field_article_videos
field_name: field_article_videos
entity_type: node
type: file
settings:
display_field: true
display_default: true
uri_scheme: public
target_type: file
module: file
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- link
- node
id: node.field_facebook_page
field_name: field_facebook_page
entity_type: node
type: link
settings: { }
module: link
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- link
- node
id: node.field_source
field_name: field_source
entity_type: node
type: link
settings: { }
module: link
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- node
- text
id: node.field_summary
field_name: field_summary
entity_type: node
type: text_long
settings: { }
module: text
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,29 @@
langcode: en
status: true
dependencies:
module:
- file
- image
- node
id: node.field_thumbnail
field_name: field_thumbnail
entity_type: node
type: image
settings:
uri_scheme: public
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
target_type: file
display_field: false
display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- link
- node
id: node.field_url
field_name: field_url
entity_type: node
type: link
settings: { }
module: link
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- user
id: user.field_user_name
field_name: field_user_name
entity_type: user
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- user
id: user.field_user_surname
field_name: field_user_surname
entity_type: user
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,9 @@
langcode: en
status: true
name: 'Article'
type: article
description: ''
help: ''
new_revision: false
preview_mode: 1
display_submitted: false

View File

@ -0,0 +1,41 @@
<?php
use Drupal\builders_test\ArticleTypeBuilder;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
class GetArticleTypesTest extends KernelTestBase {
public static $modules = [
'bundle_article',
'taxonomy',
'text',
'user'
];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('taxonomy_term');
}
public function testShouldReturnListOfArticleTypesInRequestedLanguage() {
ArticleTypeBuilder::create()->build();
ArticleTypeBuilder::create()->withLanguageCode('el')->build();
ArticleTypeBuilder::create()->build();
$request = Request::create('/type/article?languageCode=en');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","types":[{"id":"1","name":"Type"},{"id":"3","name":"Type"}]}', $response->getContent());
}
public function testShouldReturnErrorMessageWhenLanguageCodeQueryParameterIsMissing() {
$request = Request::create('/type/article');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(400, $response->getStatusCode());
$this->assertEquals('{"code":400,"message":"Query parameter \u0022languageCode\u0022 is mandatory and is missing."}', $response->getContent());
}
}

View File

@ -0,0 +1,134 @@
<?php
namespace Drupal\bundle_article\Tests\Kernel;
use Drupal\builders_test\ArticleBuilder;
use Drupal\builders_test\ArticleTypeBuilder;
use Drupal\builders_test\FileBuilder;
use Drupal\builders_test\PageBuilder;
use Drupal\builders_test\UserBuilder;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
class GetArticlesTest extends KernelTestBase {
public static $modules = [
'bundle_article',
'bundle_article_test',
'taxonomy',
'user',
'node',
'file',
'field',
'text',
'image',
'link',
'system'
];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('user');
$this->installSchema('system', ['sequences']);
$this->installEntitySchema('node');
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
$this->installConfig('bundle_article_test');
}
public function testShouldReturnListOfArticles() {
ArticleTypeBuilder::create()->build();
FileBuilder::create()->build();
UserBuilder::create()->build();
PageBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en');
$response = $this->container->get('http_kernel')->handle($request);
$secondArticleAsJson = '{"id":"2","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$thirdArticleAsJson = '{"id":"3","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $secondArticleAsJson . ',' . $thirdArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnListOfArticlesInRequestedLanguage() {
ArticleTypeBuilder::create()->build();
$photo = FileBuilder::create()->build();
$video = FileBuilder::create()->withFileName('filename.mp4')->build();
$file = FileBuilder::create()->withFileName('filename.pdf')->build();
UserBuilder::create()->build();
ArticleBuilder::create()->withSummary('Summary')
->withPhotos([$photo->id(), $photo->id(), $photo->id()])
->withVideos([$video->id(), $video->id(), $video->id()])
->withFiles([$file->id(), $file->id(), $file->id()])
->withSources(['https://example.com/source1', 'https://example.com/source2', 'https://example.com/source3'])
->withLinks(['https://example.com/link1', 'https://example.com/link2', 'https://example.com/link3'])
->withFacebookPage('https://facebook.com/event1')
->build();
ArticleBuilder::create()->withLanguageCode('el')->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en');
$response = $this->container->get('http_kernel')->handle($request);
$firstArticleAsJson = '{"id":"1","typeId":"1","typeName":"Type","title":"Title","summary":"Summary","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":["https:\/\/example.com\/filename.jpg","https:\/\/example.com\/filename.jpg","https:\/\/example.com\/filename.jpg"],"videos":["https:\/\/example.com\/filename.mp4","https:\/\/example.com\/filename.mp4","https:\/\/example.com\/filename.mp4"],"files":["https:\/\/example.com\/filename.pdf","https:\/\/example.com\/filename.pdf","https:\/\/example.com\/filename.pdf"],"sources":["https:\/\/example.com\/source1","https:\/\/example.com\/source2","https:\/\/example.com\/source3"],"links":["https:\/\/example.com\/link1","https:\/\/example.com\/link2","https:\/\/example.com\/link3"],"facebookEvent":"https:\/\/facebook.com\/event1","author":"Name Surname","date":"1234567890"}';
$thirdArticleAsJson = '{"id":"3","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $firstArticleAsJson . ',' . $thirdArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnArticleWithRequestedIdAndLanguage() {
ArticleTypeBuilder::create()->build();
FileBuilder::create()->build();
UserBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en&id=2');
$response = $this->container->get('http_kernel')->handle($request);
$secondArticleAsJson = '{"id":"2","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $secondArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnErrorWhenArticleForRequestedIdDoesNotExist() {
$request = Request::create('/articles?languageCode=en&id=1');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(404, $response->getStatusCode());
$this->assertEquals('{"code":404,"message":"Article with id 1 does not exist."}', $response->getContent());
}
public function testShouldReturnListOfArticlesForRequestedType() {
ArticleTypeBuilder::create()->build();
ArticleTypeBuilder::create()->build();
FileBuilder::create()->build();
UserBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->withType(2)->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en&typeId=1');
$response = $this->container->get('http_kernel')->handle($request);
$firstArticleAsJson = '{"id":"1","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$thirdArticleAsJson = '{"id":"3","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $firstArticleAsJson . ',' . $thirdArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnErrorMessageWhenLanguageCodeQueryParameterIsMissing() {
$request = Request::create('/articles');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(400, $response->getStatusCode());
$this->assertEquals('{"code":400,"message":"Query parameter \u0022languageCode\u0022 is mandatory and is missing."}', $response->getContent());
}
}

View File

@ -0,0 +1,18 @@
#!/bin/bash
SITE=${1}
NODE=${2}
BASE_DIR="/var/www/sites"
MODULES="modules/custom"
[ "$#" -lt 2 ] && echo "Argument missing" && exit
[ ! -d ${SITE} ] && echo "Directory ${SITE} does not exist" && exit
[ -d ${SITE}/web ] && SITE=${SITE}/web
echo -en " 🌈 Disable module ${B}bundle_${NODE}${E}"
cd /var/www/sites/${SITE}
../vendor/drush/drush/drush pmu "bundle_${NODE}"
echo -en " 📂 Delete directory ${B}${SITE}/modules/custom/bundle_${NODE}${E}"
rm "/var/www/sites/${SITE}/modules/custom/bundle_${NODE}" -rf

103
endpoints/endpoint-get.sh Executable file
View File

@ -0,0 +1,103 @@
#!/bin/bash
SITE=${1}
NODE=${2}
G="\e[0;32m"
B="\e[0;34m"
W="\e[0;97m"
E="\e[00m"
SOURCE="/root/dev/endpoints"
BASE_DIR="/var/www/sites"
MODULES="modules/custom"
[ "$#" -lt 2 ] && echo "Argument missing" && exit
[ ! -d ${SITE} ] && echo "Directory ${SITE} does not exist" && exit
[ -d ${SITE}/web ] && SITE=${SITE}/web
function log() {
[ $1 == 0 ] && echo -e " ${G}[ OK ]${E}"; return
echo -e " ${R}[FAIL]${E}"
exit
}
echo
echo -en " 📂 Copy template module dir to ${B}${SITE}${E}"
cp -r "${SOURCE}/endpoint_get_AAAAA" "${BASE_DIR}/${SITE}/${MODULES}/endpoint_get_${NODE}"
log $?
cd "${BASE_DIR}/${SITE}/${MODULES}/endpoint_get_${NODE}"
# Rename files
echo -en " 🍓 Rename ${B}endpoint_get_${NODE}.info.yml${E} file"
mv "endpoint_get_AAAAA.info.yml" "endpoint_get_${NODE}.info.yml"
log $?
echo -en " 🍓 Rename ${B}endpoint_get_${NODE}.routing.yml${E} file"
mv "endpoint_get_AAAAA.routing.yml" "endpoint_get_${NODE}.routing.yml"
log $?
# Edit files
echo -en " ⭐ Edit ${B}endpoint_get_${NODE}.info.yml${E} file"
sed -i "s/AAAAA/${NODE}/g" "endpoint_get_${NODE}.info.yml"
log $?
echo -en " ⭐ Edit ${B}endpoint_get_${NODE}.routing.yml${E} file"
sed -i "s/AAAAA/${NODE}/g" "endpoint_get_${NODE}.routing.yml"
log $?
echo -en " ⭐ Edit ${B}src/Controller/NodeController.php${E} file"
sed -i "s/AAAAA/${NODE}/g" "src/Controller/NodeController.php"
log $?
echo -en " ⭐ Edit ${B}src/Controller/NodesController.php${E} file"
sed -i "s/AAAAA/${NODE}/g" "src/Controller/NodesController.php"
log $?
echo -en " ⭐ Edit ${B}src/Controller/CategoryController.php${E} file"
sed -i "s/AAAAA/${NODE}/g" "src/Controller/CategoryController.php"
log $?
exit
# Enable module
echo -e " 🌈 Enable module"
cd /var/www/sites/${SITE}
../vendor/drush/drush/drush en "endpoint_get_${NODE}"
# Test endpoint
BASE_URL="http://$(ls -l /var/www/ | grep ${SITE} | awk {'print $9'}).vm7"
API_URL="api/el"
NODE_URL="${BASE_URL}/${API_URL}/${NODE}"
NODES_URL="${BASE_URL}/${API_URL}/${NODE}s"
cat "endpoint-get-${NODE}.routing.yml" | grep path
# echo "BASE_URL :" ${BASE_URL}
# echo "API_URL :" ${API_URL}
# echo "NODE :" ${NODE}
# echo "NODE_URL :" ${NODE_URL}
# echo "NODEs_URL:" ${NODES_URL}
ENDPOINTS=(
api/en/${NODE}s
api/el/${NODE}s
)
for ENDPOINT in ${ENDPOINTS[@]}; do
ENDPOINT_STATUS=$(curl -sI --location --request GET $BASE_URL/$ENDPOINT?_format=json \
-b cookie.txt \
--header "Content-type: application/json" | grep HTTP | awk {'print $2 " " $3'})
echo -e " 🍒 GET $ENDPOINT: $ENDPOINT_STATUS"
done

View File

@ -0,0 +1,18 @@
#!/bin/bash
SITE=${1}
NODE=${2}
BASE_DIR="/var/www/sites"
MODULES="modules/custom"
[ "$#" -lt 2 ] && echo "Argument missing" && exit
[ ! -d ${SITE} ] && echo "Directory ${SITE} does not exist" && exit
[ -d ${SITE}/web ] && SITE=${SITE}/web
echo -en " 🌈 Disable module ${B}bundle_${NODE}${E}"
cd /var/www/sites/${SITE}
../vendor/drush/drush/drush pmu "bundle_${NODE}"
echo -en " 📂 Delete directory ${B}${SITE}/modules/custom/bundle_${NODE}${E}"
rm "/var/www/sites/${SITE}/modules/custom/bundle_${NODE}" -rf

102
endpoints/endpoint-post.sh Executable file
View File

@ -0,0 +1,102 @@
#!/bin/bash
SITE=${1}
NODE=${2}
G="\e[0;32m"
B="\e[0;34m"
W="\e[0;97m"
E="\e[00m"
SOURCE="/root/Dev-Enviroment/toolbox/endpoints_maker"
BASE_DIR="/var/www/sites"
MODULES="modules/custom"
[ "$#" -lt 2 ] && echo "Argument missing" && exit
[ ! -d ${SITE} ] && echo "Directory ${SITE} does not exist" && exit
[ -d ${SITE}/web ] && SITE=${SITE}/web
function log() {
[ $1 == 0 ] && echo -e " ${G}[ OK ]${E}"; return
echo -e " ${R}[FAIL]${E}"
exit
}
echo
echo -en " 📂 Copy template module dir to ${B}${SITE}${E}"
cp -r "${SOURCE}/bundle_AAAAA" "${BASE_DIR}/${SITE}/${MODULES}/bundle_${NODE}"
log $?
cd "${BASE_DIR}/${SITE}/${MODULES}/bundle_${NODE}"
# Rename files
echo -en " 🍓 Rename ${B}bundle_${NODE}.info.yml${E} file"
mv "bundle_AAAAA.info.yml" "bundle_${NODE}.info.yml"
log $?
echo -en " 🍓 Rename ${B}bundle_${NODE}.routing.yml${E} file"
mv "bundle_AAAAA.routing.yml" "bundle_${NODE}.routing.yml"
log $?
# Edit files
echo -en " ⭐ Edit ${B}bundle_${NODE}.info.yml${E} file"
sed -i "s/AAAAA/${NODE}/g" "bundle_${NODE}.info.yml"
log $?
echo -en " ⭐ Edit ${B}bundle_${NODE}.routing.yml${E} file"
sed -i "s/AAAAA/${NODE}/g" "bundle_${NODE}.routing.yml"
log $?
echo -en " ⭐ Edit ${B}src/Controller/NodeController.php${E} file"
sed -i "s/AAAAA/${NODE}/g" "src/Controller/NodeController.php"
log $?
echo -en " ⭐ Edit ${B}src/Controller/NodesController.php${E} file"
sed -i "s/AAAAA/${NODE}/g" "src/Controller/NodesController.php"
log $?
echo -en " ⭐ Edit ${B}src/Controller/CategoryController.php${E} file"
sed -i "s/AAAAA/${NODE}/g" "src/Controller/CategoryController.php"
log $?
# Enable module
echo -e " 🌈 Enable module"
cd /var/www/sites/${SITE}
../vendor/drush/drush/drush en "bundle_${NODE}"
# Test endpoint
BASE_URL="http://$(ls -l /var/www/ | grep ${SITE} | awk {'print $9'}).vm7"
API_URL="api/el"
NODE_URL="${BASE_URL}/${API_URL}/${NODE}"
NODES_URL="${BASE_URL}/${API_URL}/${NODE}s"
cat "bundle_${NODE}.routing.yml" | grep path
# echo "BASE_URL :" ${BASE_URL}
# echo "API_URL :" ${API_URL}
# echo "NODE :" ${NODE}
# echo "NODE_URL :" ${NODE_URL}
# echo "NODEs_URL:" ${NODES_URL}
ENDPOINTS=(
api/en/${NODE}s
api/el/${NODE}s
)
for ENDPOINT in ${ENDPOINTS[@]}; do
ENDPOINT_STATUS=$(curl -sI --location --request GET $BASE_URL/$ENDPOINT?_format=json \
-b cookie.txt \
--header "Content-type: application/json" | grep HTTP | awk {'print $2 " " $3'})
echo -e " 🍒 GET $ENDPOINT: $ENDPOINT_STATUS"
done

View File

@ -0,0 +1,8 @@
name: 'Endpoint GET for AAAAA'
description: 'Endpoint GET for AAAAA'
package: DOTSOFT
type: module
version: 1.0
core_version_requirement: ^10

View File

@ -0,0 +1,39 @@
endpoint_get_AAAAA.node:
path: '/api/{lang}/AAAAAs/{alias}'
defaults:
_controller: 'Drupal\endpoint_get_AAAAA\Controller\NodeController::getNode'
methods: [GET]
requirements:
_access: 'TRUE'
options:
no_cache: 'TRUE'
endpoint_get_AAAAA.nodes:
path: '/api/{lang}/AAAAAs'
defaults:
_controller: 'Drupal\endpoint_get_AAAAA\Controller\NodesController::getNodes'
methods: [GET]
requirements:
_access: 'TRUE'
options:
no_cache: 'TRUE'
# endpoint_get_AAAAA.categories:
# path: '/api/{lang}/AAAAAs/categories'
# defaults:
# _controller: 'Drupal\endpoint_get_AAAAA\Controller\CategoryController::getCategories'
# methods: [GET]
# requirements:
# _access: 'TRUE'
# options:
# no_cache: 'TRUE'
# endpoint_get_AAAAA.nodes_category:
# path: '/api/{lang}/AAAAAs/categories/{category}'
# defaults:
# _controller: 'Drupal\endpoint_get_AAAAA\Controller\NodesController::getNodes'
# methods: [GET]
# requirements:
# _access: 'TRUE'
# options:
# no_cache: 'TRUE'

View File

@ -0,0 +1,65 @@
<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class CategoryController extends ControllerBase {
private const VOCABULARY = 'AAAAA_category'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
// MAIN
public function getCategories(Request $request, $lang) {
$this->response = [
'code' => $this->statusCode,
'lang' => $lang,
'categories' => $this->buildVocabulary($lang)];
return new JsonResponse($this->response, $this->statusCode);
}
// RESPONSE ARRAY
private function buildVocabulary($lang): array {
$terms = $this->loadTerms($lang);
$terms_response = [];
foreach ($terms as $type) {
$terms_response[] = [
'id' => $type->id(),
'name' => $type->getName()
];
}
return $terms_response;
}
// RESPONSE ARRAY VALUES
private function loadTerms($lang) {
// All terms from the vocabulary
$terms=\Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties([
'vid' => self::VOCABULARY,
]);
// Current language only
$termList=[];
foreach($terms as $term) {
if($term->hasTranslation($lang)){
$tid = $term->id();
$translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $lang);
$termList[$tid] = $translated_term;
}
}
return $termList;
}
}

View File

@ -0,0 +1,172 @@
<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
use Drupal\media\Plugin\media\Source;
use Drupal\media\Entity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TempStore;
class NodeController extends ControllerBase {
private const FIELD_CATEGORY = 'field_AAAAA_category'; // Editable
private const FIELD_SUBCATEGORY = 'field_AAAAA_subcategory'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_NOT_FOUND = 404;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
/* Main */
public function getNode(Request $request, $lang, $alias) {
/* check if alias exist in path */
if (empty($alias)) {
$this->errorAliasMissing();
return new JsonResponse($this->response, $this->statusCode);
}
/* check if alias exist in drupal */
$path_alias = '/'.$alias;
$path = \Drupal::service('path_alias.manager')->getPathByAlias($path_alias);
if ( $path_alias == $path) {
$this->errorNodeNotExist($alias, $path);
return new JsonResponse($this->response, $this->statusCode);
}
/* check if node has translation */
$nid = Url::fromUri('internal:' . $path_alias)->getRouteParameters()['node'];
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
if (! $node->hasTranslation($lang)) {
$this->errorTranslationNotExist($lang, $alias);
return new JsonResponse($this->response, $this->statusCode);
}
/* build response */
$this->buildNodeResponse($lang, $alias);
return new JsonResponse($this->response, $this->statusCode);
}
/* Response */
private function buildNodeResponse($lang, $alias) {
$path = \Drupal::service('path_alias.manager')->getPathByAlias($alias);
$nid = Url::fromUri('internal:/' . $path)->getRouteParameters()['node'];
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid)->getTranslation($lang);
/* user name */
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
/* absolute urls for body inline images */
$base_url = Url::fromRoute('<current>')->setAbsolute()->toString();
$url_components = parse_url($base_url);
$domain = $url_components['scheme'].'://'.$url_components['host'].':'.$url_components['port'];
$body = str_replace(
'/sites/default/',
$domain.'/sites/default/',
$node->get('body')->value
);
$this->response = [
'code' => $this->statusCode,
'alias' => $alias,
'path' => $path,
'nid' => $nid,
'title' => $node->get('title')->value,
'body' => $body,
'lang' => $node->get('langcode')->value,
'alias' => $node->get('path')->alias,
'created' => $node->get('created')->value,
'author' => $name,
// 'files' => $this->getFiles($node, 'field_file'),
// 'images' => $this->getImages($node, 'field_image'),
// 'category' => (
// $node
// ->get(self::FIELD_CATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_CATEGORY)->entity,
// $node->currentTranslation
// )->getName():'',
// 'subcategory' => $this->getTerms($node, self::FIELD_SUBCATEGORY)
];
}
/* Multiple value fields */
// private function getTerms(Node $node, string $field): array {
// $terms = $node->get($field)->referencedEntities();
// $response = [];
// foreach ($terms as $term) {
// $name = $term->getName();
// $tid = $term->id();
// $response[] = array(
// 'name' => $name,
// 'id' => $tid
// );
// }
// return $response;
// }
// private function getFiles(Node $node, string $field): array {
// $uris = [];
// foreach ($node->get($field) as $value) {
// $file = \Drupal::entityTypeManager()
// ->getStorage('file')
// ->load($value->getValue()['target_id']);
// $url = \Drupal::service('file_url_generator')
// ->generateAbsoluteString($file->getFileUri());
// $uris[] = array("url" => $url);
// }
// return $uris;
// }
// private function getImages(Node $node, string $field): array {
// $uris = [];
// foreach ($node->get($field)->getValue() as $value) {
// $file = \Drupal::entityTypeManager()
// ->getStorage('file')
// ->load($value['target_id']);
// $url = \Drupal::service('file_url_generator')
// ->generateAbsoluteString($file->getFileUri());
// $uris[] = array("url" => $url, "alt" => $value['alt']);
// }
// return $uris;
// }
/* Error functions */
private function errorNodeNotExist($alias, $path) {
$this->statusCode = self::HTTP_NOT_FOUND;
$this->response = [
'code' => $this->statusCode,
"message" => "Node with alias " . $alias . " does not exist." . $path
];
}
private function errorTranslationNotExist($lang, $alias) {
$this->statusCode = self::HTTP_NOT_FOUND;
$this->response = [
'code' => $this->statusCode,
"message" => "Node with alias " . $alias . " does not have a translation for language code " . $lang
];
}
private function errorAliasMissing() {
$this->statusCode = self::HTTP_BAD_REQUEST;
$this->response = [
'code' => $this->statusCode,
'message' => 'Query parameter "alias" is mandatory and is missing.'
];
}
// \Drupal::logger('hello')->notice(''.$nid);
}

View File

@ -0,0 +1,237 @@
<?php
namespace Drupal\bundle_article\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\Entity\Node;
use Drupal\media\Plugin\media\Source;
use Drupal\media\Entity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TempStore;
class NodesController extends ControllerBase {
private const NODE_TYPE = 'AAAAA'; // Editable
/*
* Used for : Taxonomy reference field
* Value : single ID of field_article_category value
* Url : optional URL argument - single value
* Example : /api/en/articles/1234
*/
// private const FIELD_CATEGORY = 'field_AAAAA_category'; // Editable
/* Used for : Taxonomy reference field
* Value : multiple ID's of field_article_subcategory values
* Url : optional URL query params - accept multiple values
* Example : /api/en/articles/1234?subcategory=55,66,77
*/
// private const FIELD_SUBCATEGORY = 'field_AAAAA_subcategory'; // Editable
private const HTTP_BAD_REQUEST = 400;
private const HTTP_NOT_FOUND = 404;
private const HTTP_OK = 200;
private array $response = [];
private int $statusCode = self::HTTP_OK;
/* Main */
public function getNodes(Request $request, $lang, $category = 'all') {
$nodes = $this->loadNodes($request, $lang, $category);
$nodes_response = $this->buildNodes($nodes, $lang, $category);
$this->response = [
'code' => $this->statusCode,
'count' => count($nodes_response),
'nodes' => $nodes_response
];
return new JsonResponse($this->response, $this->statusCode);
}
/* Response List */
private function buildNodes(array $nodes, $lang): array {
$nodes_response = [];
foreach ($nodes as $node) {
/* don't show node if it hasn't translation */
if ( $node->hasTranslation($lang)) {
$node = $node->getTranslation($lang);
$published = $node->get('status')->value;
/* get user name */
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
/* absolute urls for body inline images */
$base_url = Url::fromRoute('<current>')->setAbsolute()->toString();
$url_components = parse_url($base_url);
$domain = $url_components['scheme'].'://'.$url_components['host'].':'.$url_components['port'];
$body = str_replace(
'/sites/default/',
$domain.'/sites/default/',
$node->get('body')->value
);
if ($published == 1) {
$nodes_response[] = [
'id' => $node->id(),
'title' => $node->getTitle(),
'body' => $body,
'lang' => $node->get('langcode')->value,
'created' => $node->get('created')->value,
'alias' => $node->get('path')->alias,
'author' => $name,
// 'file' => $this->getFiles($node, 'field_file'),
// 'image' => $this->getImages($node, 'field_image'),
// 'category_id' => (
// $node
// ->get(self::FIELD_CATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_CATEGORY)->entity,
// $node->currentTranslation
// )->id():'',
// 'category_label' => (
// $node
// ->get(self::FIELD_CATEGORY)
// ->entity)?\Drupal::service('entity.repository')
// ->getTranslationFromContext(
// $node->get(self::FIELD_CATEGORY)->entity,
// $node->currentTranslation
// )->getName():'',
// 'subcategory' => $this->getTerms($node, self::FIELD_SUBCATEGORY)
];
}
}
}
return $nodes_response;
}
/* Multivalue fields */
// private function getTerms(Node $node, string $field): array {
// $terms = $node->get($field)->referencedEntities();
// $response = [];
// foreach ($terms as $term) {
// $name = $term->getName();
// $tid = $term->id();
// $response[] = array(
// 'name' => $name,
// 'id' => $tid
// );
// }
// return $response;
// }
// private function getFiles(Node $node, string $field): array {
// $uris = [];
// foreach ($node->get($field) as $value) {
// $file = \Drupal::entityTypeManager()
// ->getStorage('file')
// ->load($value->getValue()['target_id']);
// $url = \Drupal::service('file_url_generator')
// ->generateAbsoluteString($file->getFileUri());
// $uris[] = array("url" => $url);
// }
// return $uris;
// }
// private function getImages(Node $node, string $field): array {
// $uris = [];
// foreach ($node->get($field)->getValue() as $value) {
// $file = \Drupal::entityTypeManager()
// ->getStorage('file')
// ->load($value['target_id']);
// $url = \Drupal::service('file_url_generator')
// ->generateAbsoluteString($file->getFileUri());
// $uris[] = array("url" => $url, "alt" => $value['alt']);
// }
// return $uris;
// }
/* get response data */
private function loadNodes($request, $lang, $category) {
/* build query for nodes */
$query = \Drupal::entityTypeManager()
->getStorage('node')
->getQuery()
->accessCheck(false);
/* category is a URL parameter, matched with a taxonomy field */
if ($category != 'all'){
$query->condition(self::FIELD_CATEGORY, $category);
}
/* add subcategory URL query filter, matched with a taxonomy field */
if ($request->query->get('subcategory')){
$or_group = $query->orConditionGroup();
$terms = explode(',', $request->query->get('subcategory'));
foreach ($terms as $term) {
$or_group->condition(self::FIELD_SUBCATEGORY.'.target_id', $term);
}
$query->condition($or_group);
}
/* add pager */
$query->range($request->get('start'), $request->get('length'));
/* sort results by DESC or ASC */
if ($request->get('sort')) {
$sort = $request->get('sort');
if(strcasecmp($sort, 'desc') == 0 || strcasecmp($sort, 'asc') == 0){
$sort = $request->get('sort');
}
else{
$sort = 'DESC';
}
}
else{
$sort = 'DESC';
}
/* sort results by field */
if ($request->get('sortby')) {
$sortby = $request->get('sortby');
if(strcasecmp($sortby, 'title') == 0 || strcasecmp($sortby, 'created') == 0){
$sortby = $request->get('sortby');
}
else{
$sortby = 'created';
}
}
else{
$sortby = 'created';
}
/* execute query to get node ids */
$nodeIds = $query
->condition('type', self::NODE_TYPE)
->sort($sortby, $sort, $lang)
->execute();
/* get nodes from ids */
$nodes=\Drupal::entityTypeManager()
->getStorage('node')
->loadMultiple($nodeIds);
/* Response List */
$nodeList=[];
foreach ($nodes as $node) {
$tid = $node->id();
$nodeList[$tid] = $node->hasTranslation($lang) ? $node->getTranslation($lang) : $node;
$node->currentTranslation = $lang;
}
return $nodeList;
}
// \Drupal::logger('Bundle AAAAA')->notice(''.$some_var);
}

View File

@ -0,0 +1,6 @@
name: 'Builders test'
description: 'Builders test'
package: Testing
type: module
version: 1.0

View File

@ -0,0 +1,101 @@
<?php
namespace Drupal\builders_test;
use Drupal\node\Entity\Node;
class ArticleBuilder {
private Node $node;
private int $typeId = 1;
private string $title = 'Title';
private string $description = 'Description';
private int $thumbnail = 1;
private int $authorId = 1;
private int $created = 1234567890;
private string $languageCode = 'en';
private string $summary;
private array $photos;
private array $videos;
private array $files;
private array $sources;
private array $links;
private string $facebookPage;
public function __construct() {
$this->node = Node::create([
'type' => 'article',
'langcode' => $this->languageCode,
'title' => $this->title,
'field_article_type' => $this->typeId,
'field_article_description' => $this->description,
'field_thumbnail' => $this->thumbnail,
'uid' => $this->authorId,
'created' => $this->created
]);
}
public static function create(): ArticleBuilder {
return new ArticleBuilder();
}
public function withLanguageCode(string $languageCode): ArticleBuilder {
$this->languageCode = $languageCode;
$this->node->set('langcode', $this->languageCode);
return $this;
}
public function withType(int $typeId): ArticleBuilder {
$this->typeId = $typeId;
$this->node->set('field_article_type', $this->typeId);
return $this;
}
public function withSummary(string $summary): ArticleBuilder {
$this->summary = $summary;
$this->node->set('field_summary', $this->summary);
return $this;
}
public function withPhotos(array $photos): ArticleBuilder {
$this->photos = $photos;
$this->node->set('field_article_photos', $this->photos);
return $this;
}
public function withVideos(array $videos): ArticleBuilder {
$this->videos = $videos;
$this->node->set('field_article_videos', $this->videos);
return $this;
}
public function withFiles(array $files): ArticleBuilder {
$this->files = $files;
$this->node->set('field_article_files', $this->files);
return $this;
}
public function withSources(array $sources): ArticleBuilder {
$this->sources = $sources;
$this->node->set('field_source', $this->sources);
return $this;
}
public function withLinks(array $links): ArticleBuilder {
$this->links = $links;
$this->node->set('field_url', $this->links);
return $this;
}
public function withFacebookPage(string $facebookPage): ArticleBuilder {
$this->facebookPage = $facebookPage;
$this->node->set('field_facebook_page', $this->facebookPage);
return $this;
}
public function build(): Node {
$this->node->save();
return $this->node;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace Drupal\builders_test;
use Drupal\taxonomy\Entity\Term;
class ArticleTypeBuilder {
private Term $term;
private string $languageCode = 'en';
private string $name = 'Type';
public function __construct() {
$this->term = Term::create([
'vid' => 'article_types',
'langcode' => $this->languageCode,
'name' => $this->name
]);
}
public static function create(): ArticleTypeBuilder {
return new ArticleTypeBuilder();
}
public function withLanguageCode(string $languageCode): ArticleTypeBuilder {
$this->languageCode = $languageCode;
$this->term->set('langcode', $this->languageCode);
return $this;
}
public function build(): Term {
$this->term->save();
return $this->term;
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace Drupal\builders_test;
use Drupal\file\Entity\File;
class FileBuilder {
private File $file;
private string $baseUrl = 'https://example.com';
private string $fileName = 'filename.jpg';
public function __construct() {
$this->file = File::create([
'uri' => $this->baseUrl . '/' . $this->fileName
]);
}
public static function create(): FileBuilder {
return new FileBuilder();
}
public function withFileName(string $fileName): FileBuilder {
$this->fileName = $fileName;
$this->file->set('uri', $this->baseUrl . '/' . $this->fileName);
return $this;
}
public function build(): File {
$this->file->save();
return $this->file;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Drupal\builders_test;
use Drupal\node\Entity\Node;
class PageBuilder {
private Node $node;
private string $title = 'Title';
private string $languageCode = 'en';
public function __construct() {
$this->node = Node::create([
'type' => 'page',
'langcode' => $this->languageCode,
'title' => $this->title
]);
}
public static function create(): PageBuilder {
return new PageBuilder();
}
public function build(): Node {
$this->node->save();
return $this->node;
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace Drupal\builders_test;
use Drupal\user\Entity\User;
class UserBuilder {
private User $user;
private string $name = 'Name';
private string $surname = 'Surname';
public function __construct() {
$this->user = User::create([
'name' => $this->name . '@' . $this->surname . '.com',
'field_user_name' => $this->name,
'field_user_surname' => $this->surname
]);
}
public static function create(): UserBuilder {
return new UserBuilder();
}
public function build(): User {
$this->user->save();
return $this->user;
}
}

View File

@ -0,0 +1,6 @@
name: 'Article bundle test'
description: 'Article bundle test'
package: Testing
type: module
version: 1.0

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_description
- node.type.article
module:
- text
id: node.article.field_article_description
field_name: field_article_description
entity_type: node
bundle: article
label: 'Description'
description: ''
required: true
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long

View File

@ -0,0 +1,26 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_files
- node.type.article
module:
- file
id: node.article.field_article_files
field_name: field_article_files
entity_type: node
bundle: article
label: 'Files'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'txt rtf doc csv docx ppt pptx xls xlsx xlsm pdf odf odg odp ods odt fodt fods fodp fodg key numbers pages asc zip ppsx svg'
max_filesize: ''
description_field: false
handler: 'default:file'
handler_settings: { }
field_type: file

View File

@ -0,0 +1,37 @@
langcode: el
status: true
dependencies:
config:
- field.storage.node.field_article_photos
- node.type.article
module:
- image
id: node.article.field_article_photos
field_name: field_article_photos
entity_type: node
bundle: article
label: 'Photos'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'png gif jpg jpeg'
max_filesize: ''
max_resolution: ''
min_resolution: ''
alt_field: true
alt_field_required: true
title_field: true
title_field_required: false
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
handler: 'default:file'
handler_settings: { }
field_type: image

View File

@ -0,0 +1,28 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_type
- node.type.article
- taxonomy.vocabulary.article_types
id: node.article.field_article_type
field_name: field_article_type
entity_type: node
bundle: article
label: 'Article type'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
handler: 'default:taxonomy_term'
handler_settings:
target_bundles:
article_types: article_types
sort:
field: name
direction: asc
auto_create: false
auto_create_bundle: ''
field_type: entity_reference

View File

@ -0,0 +1,26 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_article_videos
- node.type.article
module:
- file
id: node.article.field_article_videos
field_name: field_article_videos
entity_type: node
bundle: article
label: 'Videos'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'mp4 ogv'
max_filesize: ''
description_field: false
handler: 'default:file'
handler_settings: { }
field_type: file

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_facebook_page
- node.type.article
module:
- link
id: node.article.field_facebook_page
field_name: field_facebook_page
entity_type: node
bundle: article
label: 'Facebook page'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
link_type: 17
title: 1
field_type: link

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_source
- node.type.article
module:
- link
id: node.article.field_source
field_name: field_source
entity_type: node
bundle: article
label: 'Sources'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
link_type: 17
title: 1
field_type: link

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_summary
- node.type.article
module:
- text
id: node.article.field_summary
field_name: field_summary
entity_type: node
bundle: article
label: 'Summary'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: text_long

View File

@ -0,0 +1,37 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_thumbnail
- node.type.article
module:
- image
id: node.article.field_thumbnail
field_name: field_thumbnail
entity_type: node
bundle: article
label: 'Κεντρική φωτογραφία'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: 'png gif jpg jpeg'
max_filesize: ''
max_resolution: ''
min_resolution: ''
alt_field: true
alt_field_required: true
title_field: true
title_field_required: false
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
handler: 'default:file'
handler_settings: { }
field_type: image

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_url
- node.type.article
module:
- link
id: node.article.field_url
field_name: field_url
entity_type: node
bundle: article
label: 'Links'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
link_type: 17
title: 1
field_type: link

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
config:
- field.storage.user.field_user_name
module:
- user
id: user.user.field_user_name
field_name: field_user_name
entity_type: user
bundle: user
label: 'Name'
description: ''
required: true
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
config:
- field.storage.user.field_user_surname
module:
- user
id: user.user.field_user_surname
field_name: field_user_surname
entity_type: user
bundle: user
label: 'Surname'
description: ''
required: true
translatable: false
default_value: { }
default_value_callback: ''
settings: { }
field_type: string

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- node
- text
id: node.field_article_description
field_name: field_article_description
entity_type: node
type: text_long
settings: { }
module: text
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
module:
- file
- node
id: node.field_article_files
field_name: field_article_files
entity_type: node
type: file
settings:
display_field: true
display_default: true
uri_scheme: public
target_type: file
module: file
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,29 @@
langcode: en
status: true
dependencies:
module:
- file
- image
- node
id: node.field_article_photos
field_name: field_article_photos
entity_type: node
type: image
settings:
uri_scheme: public
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
target_type: file
display_field: false
display_default: false
module: image
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
module:
- node
- taxonomy
id: node.field_article_type
field_name: field_article_type
entity_type: node
type: entity_reference
settings:
target_type: taxonomy_term
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,22 @@
langcode: en
status: true
dependencies:
module:
- file
- node
id: node.field_article_videos
field_name: field_article_videos
entity_type: node
type: file
settings:
display_field: true
display_default: true
uri_scheme: public
target_type: file
module: file
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- link
- node
id: node.field_facebook_page
field_name: field_facebook_page
entity_type: node
type: link
settings: { }
module: link
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- link
- node
id: node.field_source
field_name: field_source
entity_type: node
type: link
settings: { }
module: link
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- node
- text
id: node.field_summary
field_name: field_summary
entity_type: node
type: text_long
settings: { }
module: text
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,29 @@
langcode: en
status: true
dependencies:
module:
- file
- image
- node
id: node.field_thumbnail
field_name: field_thumbnail
entity_type: node
type: image
settings:
uri_scheme: public
default_image:
uuid: ''
alt: ''
title: ''
width: null
height: null
target_type: file
display_field: false
display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,18 @@
langcode: en
status: true
dependencies:
module:
- link
- node
id: node.field_url
field_name: field_url
entity_type: node
type: link
settings: { }
module: link
locked: false
cardinality: -1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- user
id: user.field_user_name
field_name: field_user_name
entity_type: user
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,20 @@
langcode: en
status: true
dependencies:
module:
- user
id: user.field_user_surname
field_name: field_user_surname
entity_type: user
type: string
settings:
max_length: 255
is_ascii: false
case_sensitive: false
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,9 @@
langcode: en
status: true
name: 'Article'
type: article
description: ''
help: ''
new_revision: false
preview_mode: 1
display_submitted: false

View File

@ -0,0 +1,41 @@
<?php
use Drupal\builders_test\ArticleTypeBuilder;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
class GetArticleTypesTest extends KernelTestBase {
public static $modules = [
'bundle_article',
'taxonomy',
'text',
'user'
];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('taxonomy_term');
}
public function testShouldReturnListOfArticleTypesInRequestedLanguage() {
ArticleTypeBuilder::create()->build();
ArticleTypeBuilder::create()->withLanguageCode('el')->build();
ArticleTypeBuilder::create()->build();
$request = Request::create('/type/article?languageCode=en');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","types":[{"id":"1","name":"Type"},{"id":"3","name":"Type"}]}', $response->getContent());
}
public function testShouldReturnErrorMessageWhenLanguageCodeQueryParameterIsMissing() {
$request = Request::create('/type/article');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(400, $response->getStatusCode());
$this->assertEquals('{"code":400,"message":"Query parameter \u0022languageCode\u0022 is mandatory and is missing."}', $response->getContent());
}
}

View File

@ -0,0 +1,134 @@
<?php
namespace Drupal\bundle_article\Tests\Kernel;
use Drupal\builders_test\ArticleBuilder;
use Drupal\builders_test\ArticleTypeBuilder;
use Drupal\builders_test\FileBuilder;
use Drupal\builders_test\PageBuilder;
use Drupal\builders_test\UserBuilder;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
class GetArticlesTest extends KernelTestBase {
public static $modules = [
'bundle_article',
'bundle_article_test',
'taxonomy',
'user',
'node',
'file',
'field',
'text',
'image',
'link',
'system'
];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('user');
$this->installSchema('system', ['sequences']);
$this->installEntitySchema('node');
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
$this->installConfig('bundle_article_test');
}
public function testShouldReturnListOfArticles() {
ArticleTypeBuilder::create()->build();
FileBuilder::create()->build();
UserBuilder::create()->build();
PageBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en');
$response = $this->container->get('http_kernel')->handle($request);
$secondArticleAsJson = '{"id":"2","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$thirdArticleAsJson = '{"id":"3","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $secondArticleAsJson . ',' . $thirdArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnListOfArticlesInRequestedLanguage() {
ArticleTypeBuilder::create()->build();
$photo = FileBuilder::create()->build();
$video = FileBuilder::create()->withFileName('filename.mp4')->build();
$file = FileBuilder::create()->withFileName('filename.pdf')->build();
UserBuilder::create()->build();
ArticleBuilder::create()->withSummary('Summary')
->withPhotos([$photo->id(), $photo->id(), $photo->id()])
->withVideos([$video->id(), $video->id(), $video->id()])
->withFiles([$file->id(), $file->id(), $file->id()])
->withSources(['https://example.com/source1', 'https://example.com/source2', 'https://example.com/source3'])
->withLinks(['https://example.com/link1', 'https://example.com/link2', 'https://example.com/link3'])
->withFacebookPage('https://facebook.com/event1')
->build();
ArticleBuilder::create()->withLanguageCode('el')->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en');
$response = $this->container->get('http_kernel')->handle($request);
$firstArticleAsJson = '{"id":"1","typeId":"1","typeName":"Type","title":"Title","summary":"Summary","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":["https:\/\/example.com\/filename.jpg","https:\/\/example.com\/filename.jpg","https:\/\/example.com\/filename.jpg"],"videos":["https:\/\/example.com\/filename.mp4","https:\/\/example.com\/filename.mp4","https:\/\/example.com\/filename.mp4"],"files":["https:\/\/example.com\/filename.pdf","https:\/\/example.com\/filename.pdf","https:\/\/example.com\/filename.pdf"],"sources":["https:\/\/example.com\/source1","https:\/\/example.com\/source2","https:\/\/example.com\/source3"],"links":["https:\/\/example.com\/link1","https:\/\/example.com\/link2","https:\/\/example.com\/link3"],"facebookEvent":"https:\/\/facebook.com\/event1","author":"Name Surname","date":"1234567890"}';
$thirdArticleAsJson = '{"id":"3","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $firstArticleAsJson . ',' . $thirdArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnArticleWithRequestedIdAndLanguage() {
ArticleTypeBuilder::create()->build();
FileBuilder::create()->build();
UserBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en&id=2');
$response = $this->container->get('http_kernel')->handle($request);
$secondArticleAsJson = '{"id":"2","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $secondArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnErrorWhenArticleForRequestedIdDoesNotExist() {
$request = Request::create('/articles?languageCode=en&id=1');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(404, $response->getStatusCode());
$this->assertEquals('{"code":404,"message":"Article with id 1 does not exist."}', $response->getContent());
}
public function testShouldReturnListOfArticlesForRequestedType() {
ArticleTypeBuilder::create()->build();
ArticleTypeBuilder::create()->build();
FileBuilder::create()->build();
UserBuilder::create()->build();
ArticleBuilder::create()->build();
ArticleBuilder::create()->withType(2)->build();
ArticleBuilder::create()->build();
$request = Request::create('/articles?languageCode=en&typeId=1');
$response = $this->container->get('http_kernel')->handle($request);
$firstArticleAsJson = '{"id":"1","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$thirdArticleAsJson = '{"id":"3","typeId":"1","typeName":"Type","title":"Title","summary":"","description":"Description","thumbnail":"https:\/\/example.com\/filename.jpg","photos":[],"videos":[],"files":[],"sources":[],"links":[],"facebookEvent":"","author":"Name Surname","date":"1234567890"}';
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('{"code":200,"languageCode":"en","articles":[' . $firstArticleAsJson . ',' . $thirdArticleAsJson . ']}', $response->getContent());
}
public function testShouldReturnErrorMessageWhenLanguageCodeQueryParameterIsMissing() {
$request = Request::create('/articles');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(400, $response->getStatusCode());
$this->assertEquals('{"code":400,"message":"Query parameter \u0022languageCode\u0022 is mandatory and is missing."}', $response->getContent());
}
}

View File

@ -0,0 +1,7 @@
name: 'Endpoint Post for PPPPP'
description: 'Endpoint Post for PPPPP'
package: DOTSOFT
type: module
version: 1.0
core_version_requirement: ^10

View File

@ -0,0 +1,7 @@
endpoint_post.PPPPP:
path: 'api/post/PPPPP'
defaults:
_controller: 'Drupal\dotsoft\Controller\PostController::post'
methods: [POST]
requirements:
_access: 'TRUE'

View File

@ -0,0 +1,54 @@
<?php
namespace Drupal\dotsoft\Controller;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class PostController
{
public function post(Request $request): JsonResponse
{
$requestContent = json_decode($request->getContent(), true);
// if (array_key_exists('user_custom_field', $requestContent)) {
// $this->createUser(
// $requestContent['email'],
// $requestContent['password'],
// $requestContent['user_custom_field']
// );
// } else {
// $exportDirectory = Node::create([
// 'type' => 'user_custom_field',
// 'title' => $requestContent['export_directory_title']
// ]);
// $exportDirectory->save();
// $user = $this->createUser(
// $requestContent['email'],
// $requestContent['password'],
// $exportDirectory->id()
// );
// $exportDirectory->set(
// 'uid',
// $user->id()
// );
// $exportDirectory->save();
// }
return new JsonResponse('Post data accepted successfully');
}
// private function createUser(string $email, string $password, int $exportDirectoryId): User
// {
// $user = User::create([
// 'name' => $email,
// 'mail' => $email,
// 'pass' => $password,
// 'roles' => ['member'],
// 'field_export_directory' => $exportDirectoryId
// ]);
// $user->save();
// return $user;
// }
}

View File

@ -0,0 +1,29 @@
langcode: en
status: true
dependencies:
config:
- field.storage.user.field_export_directory
- node.type.export_directory
module:
- user
id: user.user.field_export_directory
field_name: field_export_directory
entity_type: user
bundle: user
label: 'Export Directory'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
handler: 'default:node'
handler_settings:
target_bundles:
export_directory: export_directory
sort:
field: _none
direction: ASC
auto_create: false
auto_create_bundle: ''
field_type: entity_reference

View File

@ -0,0 +1,19 @@
langcode: en
status: true
dependencies:
module:
- node
- user
id: user.field_export_directory
field_name: field_export_directory
entity_type: user
type: entity_reference
settings:
target_type: node
module: core
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false

View File

@ -0,0 +1,7 @@
name: ''
description: ''
package: ''
type: module
version: 1.0
core_version_requirement: 9.x

View File

@ -0,0 +1,80 @@
<?php
namespace Drupal\Tests\dotsoft\Kernel;
use Drupal\Core\Url;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\node\Traits\NodeCreationTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class PostMemberRegistrationTest extends KernelTestBase
{
use NodeCreationTrait;
protected static $modules = [
'dotsoft',
'dotsoft_config_user',
'field',
'node',
'user'
];
protected function setUp(): void
{
parent::setUp();
$this->installEntitySchema('node');
$this->installEntitySchema('user');
$this->installSchema('node', ['node_access']);
$this->installConfig([
'dotsoft_config_user'
]);
}
/** @test */
public function member_account_is_created_when_export_directory_exists(): void
{
$exportDirectory = $this->createNode(['type' => 'export_directory']);
$uri = Url::fromRoute('dotsoft.users.register')->toString();
$request = Request::create($uri, 'POST', [], [], [], [], '{"email":"johndoe@example.com","password":"12345","export_directory":' . $exportDirectory->id() . '}');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(Response::HTTP_OK, $response->getStatusCode());
$this->assertEquals('"Member account is created successfully"', $response->getContent());
$account = current(\Drupal::entityTypeManager()
->getStorage('user')
->loadByProperties(['mail' => 'johndoe@example.com']));
$this->assertNotEmpty($account);
$this->assertEquals(['member'], $account->getRoles(true));
$this->assertNotEmpty($account->get('field_export_directory')->getValue());
$this->assertEquals($exportDirectory->id(), $account->get('field_export_directory')->getValue()[0]['target_id']);
}
/** @test */
public function member_account_is_created_when_export_directory_does_not_exist(): void
{
$uri = Url::fromRoute('dotsoft.users.register')->toString();
$request = Request::create($uri, 'POST', [], [], [], [], '{"email":"johndoe@example.com","password":"12345","export_directory_title":"DOTSOFT"}');
$response = $this->container->get('http_kernel')->handle($request);
$this->assertEquals(Response::HTTP_OK, $response->getStatusCode(), $response->getContent());
$this->assertEquals('"Member account is created successfully"', $response->getContent());
$account = current(\Drupal::entityTypeManager()
->getStorage('user')
->loadByProperties(['mail' => 'johndoe@example.com']));
$this->assertNotEmpty($account);
$this->assertEquals(['member'], $account->getRoles(true));
$exportDirectory = current(\Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties([
'type' => 'export_directory',
'title' => 'DOTSOFT'
]));
$this->assertNotEmpty($exportDirectory);
$this->assertEquals($account->id(), $exportDirectory->get('uid')->getValue()[0]['target_id']);
$this->assertNotEmpty($account->get('field_export_directory')->getValue());
$this->assertEquals($exportDirectory->id(), $account->get('field_export_directory')->getValue()[0]['target_id']);
}
}

View File

@ -1,14 +1,14 @@
#!/bin/bash
RED="\e[0;31m"
GRN="\e[0;32m"
BLU="\e[0;34m"
WHT="\e[0;97m"
BOLDRED="\e[1;31m"
BOLDGRN="\e[1;32m"
BOLDBLU="\e[1;34m"
BOLDWHT="\e[1;97m"
END="\e[00m"
R="\e[0;31m"
G="\e[0;32m"
B="\e[0;34m"
W="\e[0;97m"
BR="\e[1;31m"
BG="\e[1;32m"
BB="\e[1;34m"
BW="\e[1;97m"
E="\e[00m"
DBUSER="root"
DBPASS="1234"
@ -16,12 +16,9 @@ DBPASS="1234"
SRC=$1
DST=$2
function ok() {
echo -e "${BOLDGRN} [ OK ]${END}"
}
function fail() {
echo -e "${BOLDRED} [FAIL]${END}"
function log() {
[ $1 == 0 ] && echo -e " ${G}[ OK ]${E}"; return
echo -e " ${R}[FAIL]${E}"
exit
}
@ -29,42 +26,45 @@ echo
read -p "Note for destination $DST.log: " NOTE
echo
echo -ne " 🍄 Copy files from $SRC to $DST"
cp -rp $SRC $DST
[ -f "$SRC.copy.log" ] && cp $SRC.copy.log $DST.copy.log
echo >> $DST.copy.log
echo "`date +'%d/%m/%Y %H:%M:%S'` Copy from $SRC to $DST" >> $DST.copy.log
echo $NOTE >> $DST.copy.log
if [ $? = 0 ]; then ok; else fail; fi
log $?
echo -ne " 🐬 Export old database $SRC"
mysqldump -u${DBUSER} -p${DBPASS} $SRC > $SRC.sql
if [ $? = 0 ]; then ok; else fail; fi
log $?
echo -ne " 🐬 Create new database $DST"
mysql -u${DBUSER} -p${DBPASS} -e "create database $DST"
if [ $? = 0 ]; then ok; else fail; fi
log $?
echo -ne " 🐬 Create database user $DST with password '1234'"
mysql -uroot -p1234 -e "CREATE USER $DST@localhost IDENTIFIED BY \"1234\""
mysql -uroot -p1234 -e "GRANT ALL ON $DST.* TO $DST@localhost"
mysql -uroot -p1234 -e "FLUSH PRIVILEGES"
if [ $? = 0 ]; then ok; else fail; fi
log $?
echo -ne " 🐬 Import old database $SRC to new $DST"
mysql -u${DBUSER} -p${DBPASS} $DST < $SRC.sql
if [ $? = 0 ]; then ok; else fail; fi
log $?
echo -ne " 🍒 Drupal settings.php"
cd $DST
if [ -f "sites/default/settings.php" ]
then
CONFIG="sites/default/settings.php"
else
CONFIG="web/sites/default/settings.php"
fi
sed -i "s/$SRC/$DST/g" $CONFIG
if [ $? = 0 ]; then ok; else fail; fi
log $?
# echo -ne " 🍒 link html to $DST"
# unlink /var/www/html

View File

@ -4,6 +4,7 @@ df -h
rm -rf $1
rm -r $1.sql
rm -r $1.info
rm -r $1.copy.log
rm -r $1.composer.log

View File

@ -52,7 +52,7 @@ log $?
echo -ne " 🐬 Drush clear cache "
cd $BASE_PATH/sites/$1
scl enable php82 bash
# scl enable php82 bash
if [ -f ./vendor/drush/drush/drush ]
then
@ -62,7 +62,8 @@ then
echo
else
echo "using global drush"
drush cr &> /dev/null
# drush cr &> /dev/null
drush cr
log $?
echo
fi

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 0
/root/dev/toolbox/site.sh $1 0

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 1
/root/dev/toolbox/site.sh $1 1

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 2
/root/dev/toolbox/site.sh $1 2

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 3
/root/dev/toolbox/site.sh $1 3

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 4
/root/dev/toolbox/site.sh $1 4

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 6
/root/dev/toolbox/site.sh $1 6

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 7
/root/dev/toolbox/site.sh $1 7

View File

@ -1,3 +1,3 @@
#!/bin/bash
/root/Dev-Enviroment/toolbox/site.sh $1 8
/root/dev/toolbox/site.sh $1 8

Some files were not shown because too many files have changed in this diff Show More