better endpoint fields

This commit is contained in:
Ste Vaidis 2024-02-20 12:18:45 +02:00
parent bee9f98667
commit f5abdd8ed9
45 changed files with 625 additions and 1532 deletions

View File

@ -0,0 +1,274 @@
<?php
namespace Drupal\endpoint_get_publication\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 = 'publication'; // 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_publication_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_publication_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;
/* USER - get user name */
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
// AUTO_ADD_CODE_BELLOW_extractor
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$manager = '';
if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
$manager = $node->get('manager')->value;
}
$body = '';
if ($node->hasField('body') && !$node->get('body')->isEmpty()) {
$body = $node->get('body')->value;
}
if ($published == 1) {
$nodes_response[] = [
'id' => intval($node->id()),
'title' => $node->getTitle(),
'lang' => $node->get('langcode')->value,
'alias' => $node->get('path')->alias,
'author' => $name,
// AUTO_ADD_CODE_BELLOW_response
'manager' => $manager,
'manager' => $manager,
'manager' => $manager,
'manager' => $manager,
'manager' => $manager,
'manager' => $manager,
'manager' => $manager,
'manager' => $manager,
'created' => $node->get('created')->value
];
}
}
}
return $nodes_response;
}
//
// FIELD_EXPLODE
//
/*
*
* 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 nodes
*
*/
private function loadNodes($request, $lang, $category) {
/* build the query for nodes */
$query = \Drupal::entityTypeManager()
->getStorage('node')
->getQuery()
->accessCheck(false);
/* if category exist as URL parameter, create a query condition */
if ($category != 'all'){
$query->condition(self::FIELD_CATEGORY, $category);
}
/* if subcategory exist as URL query, create the query condition */
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 = 'title';
}
/* 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 publication')->notice(''.$some_var);
}

View File

@ -0,0 +1,289 @@
<?php
namespace Drupal\endpoint_get_publication\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 = 'publication'; // 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_publication_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_publication_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;
/* USER - get user name */
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
//
// FIELD_EXTRACT
//
$body = '';
if ($node->hasField('body') && !$node->get('body')->isEmpty()) {
$body = $node->get('body')->value;
}
/* BODY Field - 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
// );
/* LINK Field */
// $field_link = [];
// if ($node->hasField('field_link') && !$node->get('field_link')->isEmpty()) {
// $link_field = $node->get('field_link')->first();
// $url = $link_field->getUrl();
// $title = $link_field->getTitle();
// if ($url) {
// $field_link['url'] = $url->toString();
// }
// if ($title) {
// $field_link['title'] = $link_field->getTitle();
// } else {
// $field_link['title'] = $url->toString();;
// }
// }
/* GEOLOCATION Field */
// $field_geolocation = [];
// if ($node->hasField('field_geolocation') && !$node->get('field_geolocation')->isEmpty()) {
// $geolocation_field = $node->get('field_geolocation')->first();
// $latitude = $geolocation_field->lat;
// $longitude = $geolocation_field->lng;
// if ($latitude && $longitude) {
// $field_geolocation['lat'] = $latitude;
// $field_geolocation['lng'] = $longitude;
// }
// }
if ($published == 1) {
$nodes_response[] = [
'id' => intval($node->id()),
'title' => $node->getTitle(),
'lang' => $node->get('langcode')->value,
'alias' => $node->get('path')->alias,
'author' => $name,
//
// FIELD_RESPONSE
//
// 'field_geolocation' => $field_geolocation,
// 'field_link' => $field_link,
'body' => $body,
// '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)
'created' => $node->get('created')->value
];
}
}
}
return $nodes_response;
}
//
// FIELD_EXPLODE
//
/*
*
* 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 nodes
*
*/
private function loadNodes($request, $lang, $category) {
/* build the query for nodes */
$query = \Drupal::entityTypeManager()
->getStorage('node')
->getQuery()
->accessCheck(false);
/* if category exist as URL parameter, create a query condition */
if ($category != 'all'){
$query->condition(self::FIELD_CATEGORY, $category);
}
/* if subcategory exist as URL query, create the query condition */
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 = 'title';
}
/* 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 publication')->notice(''.$some_var);
}

View File

@ -3,7 +3,7 @@
#
# example:
#
# add-fields.sh klimatologia4/web/modules/custom/src/Nodes.php manager string
# add-fields.sh klimatologia4/web/modules/custom/src/Nodes.php string manager
#
#
@ -14,54 +14,65 @@ B="\e[0;34m"
W="\e[0;97m"
E="\e[00m"
# Check parameters
# Check for 3 parameters
[ $# -ne 3 ] && echo 'Parameter missing' && exit
# Check Target file
PHP="${1}"
[ ! -f ${PHP} ] && echo 'File ${PHP} does not exist' && exit
DST_FILE="${1}"
[ ! -f ${DSTS_FILE} ] && echo 'File ${DSTS_FILE} does not exist' && exit
# Field name
NAME="${2}"
NAME="${3}"
# Field source files
TYPE="${3}"
TYPE="${2}"
FIELD_DIR="/root/dev/endpoints/endpoint_get_fields/"
ls -1 $FIELD_DIR | grep -E "${TYPE}_(extractor|response|splitter)" > /dev/null
ls -1 $FIELD_DIR | grep -E "${TYPE}-(extractor|response|splitter)" > /dev/null
[ "$?" -ne 0 ] && echo -e "File for field ${R}${TYPE}${E} not found"
#
# Iterate source files
#
for FILE in `ls -1 $FIELD_DIR | grep -E "^${TYPE}_(extractor|response|splitter)"`; do
COMMENT=$(echo ${FILE} | awk -F_ '{print $2}')
COMMENT=$(echo ${FILE} | awk -F_ '{print $2}')
echo Adding 🍓 ${FILE} to 📦 $(basename ${PHP})
for SRC_FILE in `ls -1 $FIELD_DIR | grep -E "^${TYPE}-(extractor|response|splitter)"`; do
COMMENT=$(echo ${SRC_FILE} | awk -F- '{print "// AUTO_ADD_CODE_BELLOW_"$2}')
NEW_CODE=$(cat ${FIELD_DIR}/${SRC_FILE} | sed -e "s/FFFFF/${NAME}/g")
COMMENT_LINE=$(grep -n "$COMMENT" "$DST_FILE" | cut -d ":" -f 1)
INSERT_LINE=$((${COMMENT_LINE} + 1))
echo -e " 📦 ${W}SOURCE :${E} ${SRC_FILE}"
echo -e " 📦 ${W}DESTGINATION :${E} $(basename ${DST_FILE})"
echo -e " 🏁 ${W}AFTER COMMENT :${E} ${COMMENT}"
echo -e " 🏁 ${W}INSERT LINE :${E} ${INSERT_LINE}"
echo -e " 🧩 ${W}CODE :${E} ${NEW_CODE}"
awk -v insert="${INSERT_LINE}" -v text="${NEW_CODE}" 'NR == insert {print text} {print}' "$DST_FILE" > tmpfile && mv tmpfile "$DST_FILE"
echo
done
exit
comment="// FIELDS " ${}
exit
new_code=$(cat << 'EOF'
<?php
// Your new code here
$new_variable = 'New value';
?>
EOF
)
# new_code=$(cat << 'EOF'
# <?php
# // Your new code here
# $new_variable = 'New value';
# ?>
# EOF
# )
# Find the line number of the comment
comment_line=$(grep -n "$comment" "$php_file" | cut -d ":" -f 1)
comment_line=$(grep -n "$comment" "$DST_FILE" | cut -d ":" -f 1)
if [[ -n "$comment_line" ]]; then
# Calculate the line number to insert the new code
insert_line=$((comment_line + 1))
# Insert the new code into the PHP file
awk -v insert="$insert_line" -v text="$new_code" 'NR == insert {print text} {print}' "$php_file" > tmpfile && mv tm
pfile "$php_file"
awk -v insert="$insert_line" -v text="$NEW_CODE" 'NR == insert {print text} {print}' "$DST_FILES" > tmpfile && mv tmpfile "$DST_FILE"
echo "New code added successfully!"
else

View File

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

View File

@ -1,39 +0,0 @@
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

@ -1,65 +0,0 @@
<?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

@ -1,163 +0,0 @@
<?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

@ -1,238 +0,0 @@
<?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

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

View File

@ -1,101 +0,0 @@
<?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

@ -1,36 +0,0 @@
<?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

@ -1,34 +0,0 @@
<?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

@ -1,30 +0,0 @@
<?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

@ -1,30 +0,0 @@
<?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

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

View File

@ -1,20 +0,0 @@
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

@ -1,26 +0,0 @@
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

@ -1,37 +0,0 @@
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

@ -1,28 +0,0 @@
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

@ -1,26 +0,0 @@
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

@ -1,22 +0,0 @@
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

@ -1,22 +0,0 @@
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

@ -1,20 +0,0 @@
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

@ -1,37 +0,0 @@
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

@ -1,22 +0,0 @@
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

@ -1,19 +0,0 @@
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

@ -1,19 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,22 +0,0 @@
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

@ -1,29 +0,0 @@
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

@ -1,19 +0,0 @@
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

@ -1,22 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,29 +0,0 @@
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

@ -1,18 +0,0 @@
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

@ -1,20 +0,0 @@
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

@ -1,20 +0,0 @@
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

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

View File

@ -1,41 +0,0 @@
<?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

@ -1,134 +0,0 @@
<?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

@ -13,7 +13,9 @@ MODULES="modules/custom"
cd /var/www/sites/${SITE}
echo
# if module does not exist
#
# module exist
#
../vendor/drush/drush/drush pml --fields=name,status | grep "endpoint_get_${NODE}"
if [ $? -ne 0 ];then
echo -n " 🌈 Cannot find module ${B}endpoint_get_${NODE}${E}"
@ -21,27 +23,35 @@ if [ $? -ne 0 ];then
fi
echo -e " 🍓 Found module ${B}endpoint_get_${NODE}${E}"
#
# Clear cache
#
../vendor/drush/drush/drush cr
# if is enabled, disable it
#
# if module is enabled, disable it
#
../vendor/drush/drush/drush pml --fields=name,status > /tmp/.drush.pml
cat /tmp/.drush.pml | grep -e "Enabled" | grep "endpoint_get_${NODE}"
# cat ./drush.pml | grep -e "Enabled" | grep "(endpoint_get_${NODE})" &> /dev/null
if [ $? -eq 0 ];then
echo -n " 🍓 Disabling module ${B}endpoint_get_${NODE}${E}"
echo -n "\e 🍓 Disabling module ${B}endpoint_get_${NODE}${E}"
../vendor/drush/drush/drush pmu "endpoint_get_${NODE}"
fi
#
# if is not disabled, dont delete it
#
../vendor/drush/drush/drush pml --fields=name,status > /tmp/.drush.pml
cat ./drush.pml | grep -e "Enabled" | grep "endpoint_get_${NODE}"
if [ $? -eq 0 ];then
echo -n " 🌈 Cannot delete enabled module ${B}endpoint_get_${NODE}${E}"
echo -n "\n 🌈 Cannot delete enabled module ${B}endpoint_get_${NODE}${E}"
../vendor/drush/drush/drush pml --fields=name,status | grep "endpoint_get_${NODE}"
exit
fi
#
# delete the damn thing
#
rm "/var/www/sites/${SITE}/modules/custom/endpoint_get_${NODE}" -rf
if [ $? -eq 0 ];then
echo -e " 🍓 Directory ${B}${SITE}/modules/custom/endpoint_get_${NODE}${E} deleted"

View File

@ -2,6 +2,7 @@
C="\e[0;36m"
G="\e[0;32m"
R="\e[0;31m"
B="\e[0;34m"
W="\e[0;97m"
E="\e[00m"
@ -13,6 +14,7 @@ BASE_DIR="/var/www/sites"
MODULES="modules/custom"
SITE=${1}
SITE_COMPOSER=${1}
NODE=${2}
IFS=$'\n'
@ -38,7 +40,7 @@ function log() {
echo -e "${G}[ OK ]${E}"
return 0
else
echo -e "${G}[FAIL]${E}"
echo -e "${R}[FAIL]${E}"
return 1
fi
}
@ -111,7 +113,6 @@ function file_permissions() {
}
function enable_module() {
return 0
echo
echo -en " 🌈 Enable module"
cd /var/www/sites/${SITE}
@ -136,23 +137,27 @@ function test_module() {
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'})
RESPONSE=$(curl -s --location --request GET $BASE_URL/$ENDPOINT | head -c100)
if [ "${ENDPOINT_STATUS}" == "200" ];then
echo -e "\n 🍒 GET $BASE_URL/$ENDPOINT $ENDPOINT_STATUS"
[ "${ENDPOINT_STATUS}" == "200" ] && curl -s --location --request GET $BASE_URL/$ENDPOINT | head -c75
echo
curl -s --location --request GET $BASE_URL/$ENDPOINT | head -c75
echo -e "${G}[ OK ]${E}"
else
echo -e "\n 🍒 GET $BASE_URL/$ENDPOINT $ENDPOINT_STATUS ${R}[FAIL]${E}"
return 1
fi
done
echo
return 0
}
function add_fields () {
for FIELD in $(bash ${SCRIPT_DIR}/get-fields.sh ${SITE} node ${NODE});do
for FIELD in $(bash ${SCRIPT_DIR}/get-fields.sh ${SITE_COMPOSER} node ${NODE});do
FIELD_NAME=$(echo $FIELD | awk '{print $1}')
FIELD_TYPE=$(echo $FIELD | awk '{print $2}')
echo
echo -en "Add field ${C}${FIELD_NAME}${E} of type ${C}${FIELD_TYPE}${E} ? [y/n] "
echo -en " 🍏 Add field ${C}${FIELD_NAME}${E} of type ${C}${FIELD_TYPE}${E} ? [y/n] "
read -n 1 response
echo
if [[ "$response" =~ ^([yY])$ ]]

View File

@ -17,16 +17,9 @@ NAME=$3
cd /var/www/sites/$SITE_DIR
for FIELD in $(../vendor/drush/drush/drush fi ${TYPE} ${NAME} | tail -n +3 | grep -v '\-\-\-'); do
for FIELD in $(vendor/drush/drush/drush --fields="Field name","Field type" fi ${TYPE} ${NAME} | tail -n +3 | grep -v '\-\-\-'); do
NAME=$(echo $FIELD | awk '{print $1}')
TYPE=$(echo $FIELD | awk '{print $2}')
COUNT=$(echo $TYPE | wc -c)
THIRD=$(echo $FIELD | awk '{print $3}')
if [ "$COUNT" -lt 5 ] && [ -z "${SECOND// }" ]; then
TYPE=$THIRD
fi
echo "$NAME $TYPE"
done