better endpoints

This commit is contained in:
Ste Vaidis 2024-03-15 17:02:56 +02:00
parent 72dadb5523
commit 0abcd1cbc1
20 changed files with 201 additions and 225 deletions

View File

@ -1,10 +1,17 @@
#!/bin/bash
#
# example:
# Add code for field in a controller
#
# add-fields.sh klimatologia4/web/modules/custom/src/Nodes.php string manager
#
# Usage:
#
# ./add-fields.sh [controller file] [field type] [field name]
#
#
# Example:
#
# ./add-fields.sh klimatologia4/web/modules/custom/src/Nodes.php string manager
#
C="\e[0;36m"
@ -14,37 +21,41 @@ B="\e[0;34m"
W="\e[0;97m"
E="\e[00m"
# CHECK 3 parameters
[ $# -ne 3 ] && echo 'Parameter missing. All I got is: ' && exit
APP_DIR="/root/dev"
# CHECK target file
DST_FILE="${1}"
[ ! -f ${DSTS_FILE} ] && echo 'File ${DSTS_FILE} does not exist' && exit
# CHECK 3 parameters
[ $# -ne 3 ] && echo "I expect 3 parameters, I've got ${#}." && exit
# CHECK controller file
CONTROLLER_FILE="${1}"
[ ! -f ${CONTROLLER_FILE} ] && echo -e "Controller file ${CONTROLLER_FILE} does not exist" && exit
# CHECK source files
TYPE="${2}"
FIELD_DIR="/root/dev/endpoints/endpoint_get_fields/"
ls -1 $FIELD_DIR | grep -E "${TYPE}-(extractor|response|splitter)" > /dev/null
[ "$?" -ne 0 ] && echo -e "File for field ${R}${TYPE}${E} not found"
FIELD_TYPE="${2}"
FIELD_CODE_DIR="${APP_DIR}/endpoints/endpoint_get_fields/"
ls -1 $FIELD_CODE_DIR | grep -E "${FIELD_TYPE}-(extractor|response|splitter)" > /dev/null
[ "$?" -ne 0 ] && echo -e "File for field ${R}${FIELD_TYPE}${E} not found"
NAME="${3}"
# Field name
FIELD_NAME="${3}"
#
# Add source to destination
#
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))
for SRC_FILE in `ls -1 $FIELD_CODE_DIR | grep -E "^${FIELD_TYPE}-(extractor|response|splitter)"`; do
ADDING_MARK=$(echo ${SRC_FILE} | awk -F- '{print "// AUTO_ADD_CODE_BELLOW_"$2}')
NEW_CODE=$(cat ${FIELD_CODE_DIR}/${SRC_FILE} | sed -e "s/FFFFF/${FIELD_NAME}/g")
MARK_LINE=$(grep -n "$ADDING_MARK" "$CONTROLLER_FILE" | cut -d ":" -f 1)
INSERT_LINE=$((${MARK_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}"
echo -e " 📦 ${W}SOURCE :${E} ${SRC_FILE}"
echo -e " 📦 ${W}DESTINATION :${E} $(basename ${CONTROLLER_FILE})"
echo -e " 🏁 ${W}ADDING_MARK :${E} ${ADDING_MARK}"
echo -e " 🏁 ${W}INSERT LINE :${E} ${INSERT_LINE}"
echo -e " 🧩 ${W}CODE :${E}"
echo -e "${G}${NEW_CODE}${E}"
awk -v insert="${INSERT_LINE}" -v text="${NEW_CODE}" 'NR == insert {print text} {print}' "$DST_FILE" > tmpfile && mv tmpfile "$DST_FILE"
awk -v insert="${INSERT_LINE}" -v text="${NEW_CODE}" 'NR == insert {print text} {print}' "$CONTROLLER_FILE" > tmpfile && mv tmpfile "$CONTROLLER_FILE"
echo
done

View File

@ -42,7 +42,7 @@ 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}"
cat /tmp/.drush.pml | grep -e "Enabled" | grep "endpoint_get_${NODE}"
if [ $? -eq 0 ];then
echo -n "\n 🌈 Cannot delete enabled module ${B}endpoint_get_${NODE}${E}"
../vendor/drush/drush/drush pml --fields=name,status | grep "endpoint_get_${NODE}"

View File

@ -18,6 +18,14 @@ SITE_COMPOSER=${1}
NODE=${2}
IFS=$'\n'
# echo -e "SCRIPT_PATH :" ${SCRIPT_PATH}
# echo -e "SCRIPT_DIR :" ${SCRIPT_DIR}
# echo -e "SOURCE :" ${SOURCE}
# echo -e "BASE_DIR :" ${BASE_DIR}
# echo -e "MODULES :" ${MODULES}
# echo -e "SITE_COMPOSER :" ${SITE_COMPOSER}
# echo -e "NODE :" ${NODE}
function quit() {
echo
echo -e "Syntax:"
@ -153,24 +161,33 @@ function test_module() {
function add_fields () {
for FIELD in $(bash ${SCRIPT_DIR}/get-fields.sh ${SITE_COMPOSER} node ${NODE});do
echo -e "Get fields for node ${NODE}"
for FIELD in $(bash ${SCRIPT_DIR}/get-fields.sh ${BASE_DIR}/${SITE_COMPOSER} node ${NODE}); do
FIELD_NAME=$(echo $FIELD | awk '{print $1}')
FIELD_TYPE=$(echo $FIELD | awk '{print $2}')
DST_FILES=("NodesController.php" "NodeController.php")
DST_PATH="${BASE_DIR}/${SITE}/${MODULES}/endpoint_get_${NODE}/src/Controller"
# echo
# echo -e "FIELD :" ${FIELD}
# echo -e "FIELD_NAME :" ${FIELD_NAME}
# echo -e "FIELD_TYPE :" ${FIELD_TYPE}
# echo -e "DST_FILES :" ${DST_FILES}
# echo -e "DST_PATH :" ${DST_PATH}
for DST_FILE in ${DST_FILES}; do
echo
echo -en " 🍄 ${W}${DST_FILE}${E} : Add field ${B}${FIELD_TYPE}${E} with name ${B}${FIELD_NAME}${E}? [y/n] "
read -n 1 response
echo
if [[ "$response" =~ ^([yY])$ ]]; then
echo ${DST_PATH}/${DST_FILE}
echo ${FIELD_TYPE}
echo ${FIELD_NAME}
# echo ${DST_PATH}/${DST_FILE}
# echo ${FIELD_TYPE}
# echo ${FIELD_NAME}
${SCRIPT_DIR}/add-fields.sh "${DST_PATH}/${DST_FILE}" ${FIELD_TYPE} ${FIELD_NAME}
fi
done
done
}
@ -184,7 +201,6 @@ function main() {
fi
fi
fi
echo
echo -e "Relmember to check the settings for:"
echo -e " - Permissions"

View File

@ -25,11 +25,8 @@ class NodeController extends ControllerBase {
private int $statusCode = self::HTTP_OK;
/*
*
* Main
*
*/
public function getNode(Request $request, $lang, $alias) {
/* Quit if alias not exist in path */
@ -67,11 +64,8 @@ class NodeController extends ControllerBase {
}
/*
*
* Node Response
*
*/
private function buildNodeResponse($lang, $alias, $nid) {
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid)->getTranslation($lang);
@ -79,45 +73,15 @@ class NodeController extends ControllerBase {
$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
// );
// $manager = '';
// if ($node->hasField('manager') && !$node->get('manager')->isEmpty()) {
// $manager = $node->get('manager')->value;
// }
// AUTO_ADD_CODE_BELLOW_extractor
$this->response = [
'code' => $this->statusCode,
'alias' => $alias,
// 'path' => $path,
'nid' => $nid,
'author' => $name,
'title' => $node->get('title')->value,
// 'manager' => $manager,
// 'body' => $node->get('body')->value,
// 'body' => $body,
// 'lang' => $node->get('langcode')->value,
// 'alias' => $node->get('path')->alias,
// '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)
// AUTO_ADD_CODE_BELLOW_response
'created' => $node->get('created')->value
];
}
@ -128,53 +92,13 @@ class NodeController extends ControllerBase {
* 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;
// }
// AUTO_ADD_CODE_BELLOW_splitter
/*
*
* Error functions
*
*/
private function errorNodeNotExist($alias) {
$this->statusCode = self::HTTP_NOT_FOUND;
$this->response = [

View File

@ -11,8 +11,32 @@ use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\TempStore;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\File\FileUrlGeneratorInterface;
use Drupal\node\NodeInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class NodesController extends ControllerBase {
class NodesController extends ControllerBase implements ContainerInjectionInterface {
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('file_url_generator')
);
}
protected $entityTypeManager;
protected $fileUrlGenerator;
public function __construct(
EntityTypeManagerInterface $entityTypeManager,
FileUrlGeneratorInterface $fileUrlGenerator
) {
$this->entityTypeManager = $entityTypeManager;
$this->fileUrlGenerator = $fileUrlGenerator;
}
private const NODE_TYPE = 'AAAAA'; // Editable
@ -38,9 +62,7 @@ class NodesController extends ControllerBase {
private int $statusCode = self::HTTP_OK;
/*
*
* Main
*
*/
public function getNodes(Request $request, $lang, $category = 'all') {
$nodes = $this->loadNodes($request, $lang, $category);
@ -55,9 +77,7 @@ class NodesController extends ControllerBase {
}
/*
*
* Response List
*
*/
private function buildNodes(array $nodes, $lang): array {
$nodes_response = [];
@ -71,46 +91,7 @@ class NodesController extends ControllerBase {
$uid = $node->getOwnerId();
$user = \Drupal\user\Entity\User::load($uid);
$name = $user->getDisplayName();
//
// FIELD_EXTRACT
//
/* 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;
// }
// }
// AUTO_ADD_CODE_BELLOW_extractor
if ($published == 1) {
$nodes_response[] = [
@ -119,31 +100,7 @@ class NodesController extends ControllerBase {
'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)
// AUTO_ADD_CODE_BELLOW_response
'created' => $node->get('created')->value
];
}
@ -152,54 +109,12 @@ class NodesController extends ControllerBase {
return $nodes_response;
}
//
// FIELD_EXPLODE
//
/*
*
* Multivalue fields
*
* FIELD_EXPLODE
*/
// 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;
// }
// AUTO_ADD_CODE_BELLOW_splitter
// 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;
// }
/*
*

View File

@ -0,0 +1,11 @@
/* 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
);

View File

@ -0,0 +1 @@
'file' => $this->getFiles($node, 'field_file'),

View File

@ -0,0 +1,15 @@
private function getFiles(NodeInterface $node, string $field): array {
$files = [];
foreach ($node->get($field)->getValue() as $value) {
$file = $this->entityTypeManager
->getStorage('file')
->load($value['target_id']);
if ($file) {
$url = $this->fileUrlGenerator
->generateAbsoluteString($file->getFileUri());
$files[] = array("url" => $url);
}
}
return $files;
}

View File

@ -0,0 +1,12 @@
/* 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;
}
}

View File

@ -0,0 +1,2 @@
'field_geolocation' => $field_geolocation,

View File

@ -0,0 +1 @@
'image' => $this->getImages($node, 'field_image'),

View File

@ -0,0 +1,14 @@
private function getImages(NodeInterface $node, string $field): array {
$images = [];
foreach ($node->get($field)->getValue() as $value) {
$file = $this->entityTypeManager
->getStorage('file')
->load($value['target_id']);
if ($file) {
$url = $this->fileUrlGenerator
->generateAbsoluteString($file->getFileUri());
$images[] = array("url" => $url, "alt" => $value['alt']);
}
}
return $images;
}

View File

@ -0,0 +1,16 @@
/* 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();;
}
}

View File

@ -0,0 +1,2 @@
'field_link' => $field_link,

View File

@ -0,0 +1,10 @@
/* 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
);

View File

@ -0,0 +1,15 @@
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;
}

View File

@ -1 +1 @@
'FFFFF' => $FFFFF,
'FFFFF' => $FFFFF,

View File

@ -1,10 +1,19 @@
#!/bin/bash
#
# example:
# list the fields of a specific node type
#
#
#
# Usage:
# ./get-fields.sh [drupal] [entity type] [entity name]
#
#
#
# Example:
# ./get-fields.sh klimatologia4 node edition
#
# Result:
# body text_with_summary
# field_author string
# field_file file
@ -15,7 +24,9 @@ SITE_DIR=$1
TYPE=$2
NAME=$3
cd /var/www/sites/$SITE_DIR
[ ! -d ${SITE_DIR} ] && echo "Cannot find directory ${SITE_DIR}" && exit 1
cd $SITE_DIR
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}')