Commit 6d9e20da authored by aaa's avatar aaa

180312d - 1.fixed POST fwd , 2. Using my own guzzlehttp class

parent 9b688a72
......@@ -10,7 +10,7 @@ Note : for relay_headers to work you need the modified guzzlerestgenerator modul
At this point you must manually enable guzzlenode_user_api_access and guzzlenode_role_api_access FIELDS from
http://mydrupalsite/admin/structure/types/manage/guzzle_rest/form-display
###Access rights:
### Access rights:
This is a general permission to be able to access ALL guzzlenodes/external APIs (but not use them - you will need to specify usernames/roles inside EACH guzzlenode). Note 1: this ENABLES/DISABLES everything for everyone.So, you MUST have this permission in order to do anything. Note 2: From "RESTful Web Services" you can further control access to Drupal GET,POST,PATCH REST points. The final check is done when you check if the current USERNAME is declared in the specific guzzlenode
- Give permissions /admin/people/permissions to Drupal REST -> from here allow GET,POST,PATCH REST access to this drupal guzzlenode
......@@ -47,15 +47,39 @@ this will relay/forward your request as :
## Usage external-client-side #2:
###Parameters :
-
-
-
##To Do:
### Forward POST
If you POST to the
**http://mydrupal.com/api/relay/post/3**
and you have POST/Payload body forward enabled then, the body you have post will be forwarded to the external API call.
### Forward Headers
If you have enabled this :
If you post a header named
**authorisation2:...**
then it will be forwarded as a standard
**authorisation:..**
header to the external API
### Args :
**http://mydrupal.com/api/relay/getalbums?_format=json&arg[2]=world&arg[1]=hello**
will send to the external API a request like
**http://myexternalserver/hello/world**
At this point we accept up to 5 args : arg[1]...arg[5].
### Parameters :
Pass parameters to External API url
eg
**http://mydrupal.com/api/relay/3?_format=json&param_name[1]=hello&param_value[1]=55555555&param_name[2]=world&param_value[2]=44444**
Will produce :
**http://myexternalserver?hello=55555555&world=44444**
At this point we accept up to 5 params : param_name[1],param_value[1]...param_name[5],param_value[5]
## To Do:
- Allow FIXED payload to accept variables from drupal rest call API point
- replace use Drupal\guzzlerestgenerator\Http\GuzzleDrupalHttp with a local one
- Implement POST
- Implement PUT
- Implement access per SPECIFIC guzzle_node (per role or user)
......
......@@ -11,29 +11,30 @@ use Drupal\Core\Routing\RouteMatchInterface;
* Implements hook_rest_entity_form_alter(). ENABLE the 2 new guzzlenode fields
*/
function d8_guzzlenode_rest_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
//ENABLE all our custom fileds.(we do that because this module add the fields to an already existing form -so /config/install/optional will NOT work)
$fields_to_enable=array('field_guzzlenode_user_api_access',
'field_guzzlenode_role_api_access',
'field_guzzlenode_call_limit',
'field_gnode_allow_arg_fwd',
'field_gnode_allow_head_fwd',
'field_gnode_allow_param_fwd',
'field_gnode_allow_payload_fwd'
);
foreach ($fields_to_enable as $field) {
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.guzzle_rest.default') //orig ->load('user.user.default')
->setComponent($field
/*, [
//'type' => 'string',
'label' => 'above',
//'settings' => ['link_to_entity' => 'false'],
]
*/
)->save();
}//END of foreach ($fields_to_enable as $field) {
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.guzzle_rest.default') //orig ->load('user.user.default')
->setComponent('field_guzzlenode_user_api_access'
/* , [
'type' => 'string',
'label' => 'above',
'settings' => ['link_to_entity' => 'false'],
]*/
)->save();
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.guzzle_rest.default') //orig ->load('user.user.default')
->setComponent('field_guzzlenode_role_api_access'
/* , [
'type' => 'string',
'label' => 'above',
'settings' => ['link_to_entity' => 'false'],
]*/
)->save();
// \Drupal::logger('DEBUG d8_guzzlenode_rest')->notice("jon CUSTOM entity_form_display "); //DEBUG
} // END of function d8_guzzlenode_rest_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
......
<?php
namespace Drupal\d8_guzzlenode_rest\Http;
use GuzzleHttp\Client;
use GuzzleHttp;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Get a response code from any URL using Guzzle in Drupal 8!
*
* Usage:
* In the head of your document:
*
* use Drupal\guzzle_rest\Http\GuzzleDrupalHttp;
*
* In the area you want to return the result, using any URL for $url:
*
* $check = new GuzzleDrupalHttp();
* $response = $check->performRequest($requestUrl, $requestMethod, $requestHeaders, $requestPayloadData);
*
**/
class GuzzleDrupalHttp {
use StringTranslationTrait;
public function performRequest($requestUrl, $requestMethod = 'GET', $requestHeaders = '', $requestPayloadData = '') {
$client = new \GuzzleHttp\Client();
try {
// Massage $requestHeaders to generate $headers array, ready for REST call
$requestHeaders = preg_replace(array('/\n/', '/\r/'), '#PH#', $requestHeaders);
//foreach(explode("\r\n", $requestHeaders) as $row) {
foreach(explode('#PH#', $requestHeaders) as $row) {
$matches= explode(':', $row);
if($matches[0]!=null) $headers[$matches[0]] = $matches[1]; //jon 180222a
/*
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$headers[$matches[0]] = $matches[1];
} */
// if($matches[0]!=null) \Drupal::logger('HEADERS got ')->notice("$matches[0]=$matches[1] ,AAAAAAAAAAAA row=$row , requestHeaders=$requestHeaders");
}
if($requestPayloadData != ''){
$body=$requestPayloadData;
// Massage $requestPayloadData to generate $body array, ready for REST call
/* ORIGINAL code
foreach(explode("\r\n", $requestPayloadData) as $row) {
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$body[$matches[1]] = $matches[2];
}
}
*/ //END of ORIGINAL code
}else{
$body = '';
}
switch($requestMethod){
case "GET":
$res = $client->get($requestUrl, [
'http_errors' => false,
'headers' => $headers
]);
break;
case "POST":
\Drupal::logger('d8_guzzlenode_rest')->notice("OWN GuzzleDrupalHttp requestPayloadData=$requestPayloadData ||| res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
// NOTE *** $body must be a VALID be a JSON string
//NOTE *** REMOVE $body PARSING FROM above **
// SAMPLE CODE that accepts : "userId": '9',"title": "AAAAAAAAAAtitle", "body": "AAAAAAAAAAAAABODY aliquidmagnam sint"
$string = $body; //"business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe";
///$string = str_replace(array("\n", "\r" , '"',"'"), '', $body); //remove \n \r and "
// $string = str_replace(array("\n", "\r" ), '', $body); //remove \n \r and " ?????????? Maybe remove this
$finalArray=json_decode($string,true);
$res = $client->request('POST', $requestUrl,['json' => $finalArray ,'headers' => $headers ]); //OK Works
\Drupal::logger('CASE POST 444')->notice(" ||headers=".json_encode($headers,true)." ||||||||| requestUrl=$requestUrl ||| requestMethod=$requestMethod ||| finalarray=".json_encode($finalArray,true));
/* //ORIGINAL LINE 'body' json deprecated
$res = $client->post($requestUrl, [
'http_errors' => false,
'headers' => $headers,
//'body' => $body
] //,[ GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']]
);
*/
break;
case 'PUT':
$res = $client->put($requestUrl, [
'http_errors' => false,
'headers' => $headers,
'body' => $body
]);
break;
default:
throw new Exception('Invalid Request Method');
}
return($res);
} catch (RequestException $e) {
return($this->t('Error'));
}
}
}
\ No newline at end of file
<?php
namespace Drupal\guzzlerestgenerator\Http;
use GuzzleHttp\Client;
use GuzzleHttp;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Get a response code from any URL using Guzzle in Drupal 8!
*
* Usage:
* In the head of your document:
*
* use Drupal\guzzle_rest\Http\GuzzleDrupalHttp;
*
* In the area you want to return the result, using any URL for $url:
*
* $check = new GuzzleDrupalHttp();
* $response = $check->performRequest($requestUrl, $requestMethod, $requestHeaders, $requestPayloadData);
*
**/
class GuzzleDrupalHttp {
use StringTranslationTrait;
public function performRequest($requestUrl, $requestMethod = 'GET', $requestHeaders = '', $requestPayloadData = '') {
$client = new \GuzzleHttp\Client();
try {
// Massage $requestHeaders to generate $headers array, ready for REST call
$requestHeaders = preg_replace(array('/\n/', '/\r/'), '#PH#', $requestHeaders);
//foreach(explode("\r\n", $requestHeaders) as $row) {
foreach(explode('#PH#', $requestHeaders) as $row) {
$matches= explode(':', $row);
if($matches[0]!=null) $headers[$matches[0]] = $matches[1]; //jon 180222a
/*
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$headers[$matches[0]] = $matches[1];
} */
// if($matches[0]!=null) \Drupal::logger('HEADERS got ')->notice("$matches[0]=$matches[1] ,AAAAAAAAAAAA row=$row , requestHeaders=$requestHeaders");
}
if($requestPayloadData != ''){
$body=$requestPayloadData;
// Massage $requestPayloadData to generate $body array, ready for REST call
/* ORIGINAL code
foreach(explode("\r\n", $requestPayloadData) as $row) {
if(preg_match('/(.*?): (.*)/', $row, $matches)) {
$body[$matches[1]] = $matches[2];
}
}
*/ //END of ORIGINAL code
}else{
$body = '';
}
//\Drupal::logger('GUZRESTGEN-ORIG before switch')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
//if ($requestMethod=='POST') \Drupal::logger('GUZRESTGEN-ORIG POSTTTTT')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
switch($requestMethod){
case "GET":
//\Drupal::logger('CASE GET')->notice("res".json_decode($res,true) ."||| requestPayloadData=$requestPayloadData ||||||||| requestMethod=$requestMethod");
$res = $client->get($requestUrl, [
'http_errors' => false,
'headers' => $headers
]);
break;
case "POST":
//\Drupal::logger('GUZRESTGEN-ORIG POSTTTTT22222')->notice("requestPayloadData=$requestPayloadData ||| res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
//$res = $client->request('POST', $requestUrl, ['json' => ['foo' => 'bar']]); //ok works
// NOTE *** $body must be a VALID be a JSON string
// RELAY JSON from $body { "userId": "9", "title": "AAAAAAAAAAtitle", "body": "AAAAAAAAAAAAABODY aliquidmagnam sint", "id": 101 } //THIS IS VALID JSON
//$res = $client->request('POST', $requestUrl, [ 'json' => ["userId"=> '9', "title"=> "AAAAAAAAAAtitle", "body"=> "AAAAAAAAAAAAABODY aliquidmagnam sint"] ]); //ΟΚ Works 100%
//NOTE *** REMOVE $body PARSING FROM above **
// SAMPLE CODE that accepts : "userId": '9',"title": "AAAAAAAAAAtitle", "body": "AAAAAAAAAAAAABODY aliquidmagnam sint"
$string = $body; //"business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe";
///$string = str_replace(array("\n", "\r" , '"',"'"), '', $body); //remove \n \r and "
// $string = str_replace(array("\n", "\r" ), '', $body); //remove \n \r and " ?????????? Maybe remove this
/*$string='
{
"type":[{"target_id":"article",
"target_type": "node_type",
"target_uuid": "ff9b4624-1224-49f6-be47-d19a22664f8e"
}],
"title":[{"value":"Hello World222222222"}],
"body":[{"value":"How are you?222222222"}]
}
' ; */
$finalArray=json_decode($string,true);
// \Drupal::logger('GUZRESTGEN-ORIG POSTTTTT22222 bbb ')->notice("res=".json_encode($body,true) ." ||||||||| requestUrl=$requestUrl |||| requestMethod=$requestMethod");
//$response = $check->performRequest($requestUrl, 'POST', $requestHeaders, $requestPayloadData);
//$response = $client->request('POST', $requestUrl, ['json' => $finalArray ,'headers' => $headers ]);
// \Drupal::logger('CASE POST 3333')->notice(" ||headers=".json_encode($headers,true)." ||||||||| requestUrl=$requestUrl ||| requestMethod=$requestMethod ||| finalarray=".json_encode($finalArray,true));
$res = $client->request('POST', $requestUrl,['json' => $finalArray ,'headers' => $headers ]); //OK Works
\Drupal::logger('CASE POST 444')->notice(" ||headers=".json_encode($headers,true)." ||||||||| requestUrl=$requestUrl ||| requestMethod=$requestMethod ||| finalarray=".json_encode($finalArray,true));
/* //ORIGINAL LINE 'body' json deprecated
$res = $client->post($requestUrl, [
'http_errors' => false,
'headers' => $headers,
//'body' => $body
] //,[ GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar']]
);
*/
break;
case 'PUT':
$res = $client->put($requestUrl, [
'http_errors' => false,
'headers' => $headers,
'body' => $body
]);
break;
default:
throw new Exception('Invalid Request Method');
\Drupal::logger('GUZRESTGEN-ORIG DEFAULT switch')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
}
\Drupal::logger('GUZRESTGEN-ORIG AFTER switch')->notice("res".json_decode($res,true) ." ||||||||| requestMethod=$requestMethod");
return($res);
} catch (RequestException $e) {
return($this->t('Error'));
}
}
}
\ No newline at end of file
......@@ -10,7 +10,8 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Psr\Log\LoggerInterface;
use Drupal\guzzlerestgenerator\Http\GuzzleDrupalHttp; // DEPENDS on guzzlerestgenerator module
//use Drupal\guzzlerestgenerator\Http\GuzzleDrupalHttp; // DEPENDS on guzzlerestgenerator module
use Drupal\d8_guzzlenode_rest\Http\GuzzleDrupalHttp;
use Symfony\Component\HttpFoundation\Request;
//* "https://www.drupal.org/link-relations/create" = "/api/relay/post/{nid}"
......@@ -43,6 +44,10 @@ class GuzzlenodeRestResource extends ResourceBase {
protected $currentRequest;
//protected $nid=0;
//protected $arg1=0;
//protected $arg2=0;
/**
* Constructs a new GuzzlenodeRestResource object.
*
......@@ -101,35 +106,10 @@ class GuzzlenodeRestResource extends ResourceBase {
*/
//public function get() { //ORIGINAL
public function get($nid=0,$data) {
return $this->do_request($nid,$data,"GET");
//return new ResourceResponse("Implement REST State GET!");
}
protected function is_in_subarray($val, $entity_get_values){
$entity_get_values=array_filter($entity_get_values);
if(empty($entity_get_values)) return false;
foreach($entity_get_values as $one_value){
if($val==$one_value['target_id']) return true;
}
return false;
} //end of function is_in_subarray($val, $entity_get_values){
protected function is_in_subarray2($val, $entity_get_values){
$entity_get_values=array_filter($entity_get_values);
if(empty($entity_get_values)) return false;
$encoded=json_encode($entity_get_values,true); //[{"target_id":3714},{"target_id":1114},{"target_id":1082}]
$exploded = preg_split( '/(},{"target_id":|{"target_id":|}]|\[|\")| /', $encoded );
//var_dump(array_intersect($val, $exploded));
\Drupal::logger('is_in_subarray2')->notice("val encoded=".json_encode($val,true)." , encoded=$encoded || exploded =".json_encode($exploded,true) );
if (array_intersect($val, $exploded)) \Drupal::logger('INTERSECT is_in_subarray2 check OK')->notice("val=".json_encode($val,true)." IS INSIDE encoded=$encoded ||");
//if (in_array($val, $exploded,true)) return true;
if (array_intersect($val, $exploded)) return true;
return false;
} //end of function is_in_subarray($val, $entity_get_values){
/**
* Responds to POST requests.
......@@ -140,9 +120,7 @@ class GuzzlenodeRestResource extends ResourceBase {
* Throws exception expected.
*/
public function post($nid=0,$data) {
return $this->do_request($nid,$data,"POST");
}
/**
......@@ -155,7 +133,6 @@ class GuzzlenodeRestResource extends ResourceBase {
*/
public function patch($nid=0,$data) {
$this->do_request($nid,$data,"PATCH");
} // END of public function patch($nid=0,$data) {
......@@ -174,10 +151,11 @@ class GuzzlenodeRestResource extends ResourceBase {
protected function do_request($nid,$data=null,$method="GET") {
//PUT common code here
\Drupal::logger('guzzlenodeRest DO_REQUEST ok')->notice("ok $method nid=".$nid ." || DATA=".json_encode($data,true));
$request_method=$method;
//########## SECURITY CHECK Level #1 : user must have a general permission to view NODES
// You must to implement the logic of your REST Resource here.
// Use current user after pass authentication to validate access.
if (!$this->currentUser->hasPermission('access content')) {
throw new AccessDeniedHttpException();
......@@ -187,11 +165,17 @@ class GuzzlenodeRestResource extends ResourceBase {
\Drupal::logger('guzzlenode_rest ACCESS debug')->notice("NOOOO we DO NOT have guzzlenode allow access to ext API guzzlenodes PERMISSION");
} else { \Drupal::logger('guzzlenode_rest ACCESS debug')->notice("OK we HAVE guzzlenode allow access to ext API guzzlenodes PERMISSION"); }
//$entities = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple(); //ORIG WORKED
$entities = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['type' => 'guzzle_rest']); //LOAD ONLY guzzle nodes
//->loadMultiple();
//$entities = \Drupal::entityTypeManager()->getStorage('external_entity_type')->loadByProperties(['type' => 'extent001']); // get specific entity JON TEST
//$node_id_from_arg = $nid;
//$node_id_from_alias=\Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$nid); //GET path alias from node_ideg drupal.com/restapi/myalbum
//Todo Do some chech if $nid is number
$node_id_from_alias="0";
//if ($nid!=0)
$node_id_from_alias=\Drupal::service('path.alias_manager')->getPathByAlias('/'.$nid); //GET node_id from path alias drupal.com/restapi/myalbum
......@@ -236,6 +220,7 @@ class GuzzlenodeRestResource extends ResourceBase {
// END of NOW we check extra permissions: @@@@ ________________________________________________________
// Ok Access is allowed. Now we proceed and get the rest settings:
//$gnode_allow_arg_fwd= $entity->get('field_gnode_allow_arg_fwd')->getValue()[0]['value'];
$gnode_allow_arg_fwd= $entity->get('field_gnode_allow_arg_fwd')->value;
$gnode_allow_head_fwd= $entity->get('field_gnode_allow_head_fwd')->value;
$gnode_allow_param_fwd= $entity->get('field_gnode_allow_param_fwd')->value;
......@@ -258,31 +243,31 @@ class GuzzlenodeRestResource extends ResourceBase {
// Check if Arg Forward is selected
if ($gnode_allow_arg_fwd=="1"){
// Arguments are SEND to the client in this format : http://externalapi.com/arg1/arg2
$get_arg1 = $this->currentRequest->get('arg1'); //get URL REST node id drupal.com/restapi/?myname=john
$get_arg2 = $this->currentRequest->get('arg2'); //get URL REST node id drupal.com/restapi/?myname=john
//get URL REST relay headers to the next request ? (this is used for requesting a drupal api FROM INSIDE drupal API - kind like subreqiests)
// ARGUMENTS
if (isset($get_arg1)){
$endpoint_url=$endpoint_url.'/'.$get_arg1; // ******** Might need to sanitaze
if (isset($get_arg2)){
$endpoint_url=$endpoint_url.'/'.$get_arg2; // ******** Might need to sanitaze
}
}// END of if (isset($get_arg1)){
// Arguments are SEND to the client in this format : http://externalapi.com/arg1/arg2
//get URL REST relay headers to the next request ? (this is used for requesting a drupal api FROM INSIDE drupal API - kind like subreqiests)
$args_array=$this->currentRequest->get('arg');
$count_args=count($args_array);
if($count_args>0 ){
if ($count_args>5) $count_args=5; // we check the first 5 arga are arg[1],arg[2]...arg[5]
for ($i=1;$i<=5;$i++){
if (isset($args_array[$i]))
{
$endpoint_url=$endpoint_url.'/'.$args_array[$i]; // ******** Might need to sanitaze
}
}
$endpoint_url=$endpoint_url.'/'; //Add a trailing slash to the end of the external URL <-----
}// END of if($count_args>0 ){
} // END OF if ($gnode_allow_arg_fwd=="1"){
// Check for headers foowrward . Forward "Authorization:"" header to External Request"
if ($gnode_allow_head_fwd=="1"){
// Pass headers to the next request (used for internal subrequests -mainly for authentication)
$get_relay_headers = $this->currentRequest->get('relay_headers');
//$get_relay_headers = $this->currentRequest->get('relay_headers');
$get_relay_headers ='yes';
if ($get_relay_headers=='yes'){
//Relay Authorization Header... NOTE to NOT overwrite ORiginal
//ToDO: ralay ALL headers to next request @@@@
$currentRequestAuthorizationHeader=$this->currentRequest->headers->get( 'Authorization' );
///$currentRequestAuthorizationHeader=$this->currentRequest->headers->get( 'Authorization' );
$currentRequestAuthorizationHeader=$this->currentRequest->headers->get( 'Authorization2' );
if ($currentRequestAuthorizationHeader!=null) {
$raw_headers=$raw_headers."\r\n".'Authorization:'.$currentRequestAuthorizationHeader;
}
......@@ -294,21 +279,28 @@ class GuzzlenodeRestResource extends ResourceBase {
if ($method=="POST" && $gnode_allow_payload_fwd=="1"){
//$payload_to_forward = $entity->get('field_guzzle_data_payload')->value;
// NOTE @@@@@@@@@@ payload_data handling must be fixed in ORIGINAL
//\Drupal::logger('DEBUG guzzlenode_rest ok POST FWD')->notice(" payload_BEFORE=".json_encode($payload_data,true));
$payload_data=json_encode($data,true);
} // END Of if ($gnode_allow_param_fwd=="1"){
// Check if PARAM Forward (as GET url encoded)is selected
// Check if PARAM Forward (as GET url encoded)is selected // params (might need to sanitize)
if ($gnode_allow_param_fwd=="1"){
// params (might need to sanitize)
/*
if (isset($get_param1_name) && isset($get_param1_value) ){
$get_external_request_array = array(($get_param1_name => $get_param1_value);
if (isset($get_param2_name) && isset($get_param2_value) ){
$get_external_request_array[$get_param2_name]= $get_param2_value;
}
$get_tail=http_build_query($get_external_request_array);
$param_names_array=$this->currentRequest->get('param_name');
$param_values_array=$this->currentRequest->get('param_value');
$count_params=count($param_names_array);
$get_external_request_params_array=array();
if($count_params>0 ){
if ($count_params>5) $count_params=5; // we check ONLY the first 5
for ($i=1;$i<=5;$i++){
if (isset($param_names_array[$i]) && isset($param_values_array[$i] ))
{
$get_external_request_params_array [$param_names_array[$i]]= $param_values_array[$i];
//$endpoint_url=$endpoint_url.'/'.$param_names_array[$i]; // ******** Might need to sanitaze
}
} //end of for ($i=1;$i<=5;$i++){
$get_tail=http_build_query($get_external_request_params_array);
$pos = strpos($endpoint_url, '?'); //check if our external API URL already contains '?' Note: This check might NOT be needed
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
......@@ -316,18 +308,17 @@ class GuzzlenodeRestResource extends ResourceBase {
$endpoint_url=$endpoint_url.'?'.$get_tail;
} else {
$endpoint_url=$endpoint_url.'&'.$get_tail;
}
} // END of if (isset($get_param1_name) && isset($get_param1_value) ){
*/
} //END OF if ($gnode_allow_param_fwd=="1"){
}
}// END of if($count_args>0 ){
} //END OF if ($gnode_allow_param_fwd=="1"){
//ALL
// Perform GuzzleDrupalHttp request
$check = new GuzzleDrupalHttp();
// Function call to retrieve cities
$response = $check->performRequest($endpoint_url,$request_method,$raw_headers,$payload_data);
//$response = $check->performRequest($endpoint_url,$request_method,$raw_headers,$payload_data);
$response = $check->performRequest($endpoint_url,$method,$raw_headers,$payload_data);
$contents = (string) $response->getBody();
if($response->getStatusCode() == '200'){
if($contents != ''){
......@@ -364,7 +355,35 @@ class GuzzlenodeRestResource extends ResourceBase {
$response->addCacheableDependency($result);
return $response;
// $response= new ResourceResponse(array (0=>"do_request Hello nid=$nid",$data));
// return $response;
}//protected function do_request() {
protected function is_in_subarray($val, $entity_get_values){
$entity_get_values=array_filter($entity_get_values);
if(empty($entity_get_values)) return false;
foreach($entity_get_values as $one_value){
if($val==$one_value['target_id']) return true;
}
return false;
} //end of function is_in_subarray($val, $entity_get_values){
protected function is_in_subarray2($val, $entity_get_values){
$entity_get_values=array_filter($entity_get_values);
if(empty($entity_get_values)) return false;
$encoded=json_encode($entity_get_values,true); //[{"target_id":3714},{"target_id":1114},{"target_id":1082}]
$exploded = preg_split( '/(},{"target_id":|{"target_id":|}]|\[|\")| /', $encoded );
//var_dump(array_intersect($val, $exploded));
\Drupal::logger('is_in_subarray2')->notice("val encoded=".json_encode($val,true)." , encoded=$encoded || exploded =".json_encode($exploded,true) );
if (array_intersect($val, $exploded)) \Drupal::logger('INTERSECT is_in_subarray2 check OK')->notice("val=".json_encode($val,true)." IS INSIDE encoded=$encoded ||");
//if (in_array($val, $exploded,true)) return true;
if (array_intersect($val, $exploded)) return true;
return false;
} //end of function is_in_subarray($val, $entity_get_values){
}
<?php
namespace Drupal\d8_guzzlenode_rest\Plugin\rest\resource;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Psr\Log\LoggerInterface;