I want to use this function function like this.
class UrlInspectionIndex extends \Google\Service\Resource
{
/**
* Index inspection. (index.inspect)
*
* #param InspectUrlIndexRequest $postBody
* #param array $optParams Optional parameters.
* #return InspectUrlIndexResponse
*/
public function inspect(InspectUrlIndexRequest $postBody, $optParams = [])
{
$params = ['postBody' => $postBody];
$params = array_merge($params, $optParams);
return $this->call('inspect', [$params], InspectUrlIndexResponse::class);
}
}
This is how I use
$service= new SearchConsole($client);
$postBody=[
'inspectionUrl'=>'myinspectionUrl',
'siteUrl'=>env('APP_URL')
];
$result=$service->urlInspection_index->inspect($postBody);
The error I got
TypeError
Google\Service\SearchConsole\Resource\UrlInspectionIndex::inspect(): Argument #1 ($postBody) must be of type Google\Service\SearchConsole\InspectUrlIndexRequest, array given, called in /var/www/vhosts/habertema.com/httpdocs/app/Http/Controllers/IntegratedController.php on line 648
what is the type InspectUrlIndexRequest ?
Related
I generated flag link
$flag_link = [
'#lazy_builder' => ['flag.link_builder:build', [
$product->getEntityTypeId(),
$product->id(),
'product_like',
]],
'#create_placeholder' => TRUE,
];
Flag link is generated successfully. But while I click flag link , I got error message as response
{message: "'csrf_token' URL query argument is invalid."}
message: "'csrf_token' URL query argument is invalid."
I found a temporary solution. Not sure if this is a bug in Flag that needs to be addressed by the module maintainers, or if this is working as intended, since this is a REST response, and not a typical Drupal call for a view or display mode.
In the ModuleRestResource.php file (In my case, the ModuleRestResource.php file is located at:
{{DRUPAL_ROOT}}/web/modules/custom/{{Module_Name}}/src/Plugin/rest/resource/{{Module_Name}}RestResource.php):
use Drupal\rest\ModifiedResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\EntityInterface;
use Drupal\flag\FlagService;
use Drupal\Core\Render\RenderContext;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ModuleRestResource extends ResourceBase {
/**
* A current user instance.
*
* #var \Drupal\Core\Session\AccountProxyInterface
*/
protected $currentUser;
/**
* #var $entityTypeManager \Drupal\Core\Entity\EntityTypeManager
*/
protected $entityTypeManager;
/**
* #var \Drupal\flag\FlagService
*/
protected $flagService;
/**
* #var Drupal\Core\Access\CsrfTokenGenerator
*/
protected $csrfService;
/**
* {#inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->logger = $container->get('logger.factory')->get('module');
$instance->currentUser = $container->get('current_user');
$instance->entityTypeManager = $container->get('entity_type.manager');
$instance->flagService = $container->get('flag');
$instance->csrfService = $container->get('csrf_token');
return $instance;
}
/**
* Responds to GET requests.
*
* #param string $payload
*
* #return \Drupal\rest\ResourceResponse
* The HTTP response object.
*
* #throws \Symfony\Component\HttpKernel\Exception\HttpException
* Throws exception expected.
*/
public function get($payload) {
// 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();
}
if (!is_numeric($payload)) {
throw new BadRequestHttpException();
}
/*
* This is the object that will be returned with the node details.
*/
$obj = new \stdClass();
// First load our node.
/**
* #var \Drupal\Core\Entity\EntityInterface
*/
$node = $this->entityTypeManager->getStorage('node')->load($payload);
/**
* FIX STARTS HERE !!!!!
*/
/**
* Because we are rending code early in the process, we need to wrap in executeInRenderContext
*/
$render_context = new RenderContext();
$fl = \Drupal::service('renderer')->executeInRenderContext($render_context, function() use ($node, $payload) {
/**
* Get the flag we need and check if the selected node has been flagged by the current user
*
* Set the path to create a token. This is the value that is missing by default that creates an
* invalid CSRF Token. Important to note that the leading slash should be left off for token generation
* and then added to to the links href attribute
*
*/
$flag = $this->flagService->getFlagById('bookmark');
$is_flagged = (bool) $this->flagService->getEntityFlaggings($flag, $node, \Drupal::currentUser() );
$path = 'flag/'. ($is_flagged ? 'un' : '') .'flag/bookmark/' . $node->id();
$token = $this->csrfService->get($path);
$flag_link = $flag->getLinkTypePlugin()->getAsFlagLink($flag, $node);
$flag_link['#attributes']['href'] = '/' . $path . '?destination&token=' . $token;
/**
* Render the link into HTML
*/
return \Drupal::service('renderer')->render($flag_link);
});
/**
* This is required to bubble metadata
*/
if (!$render_context->isEmpty()) {
$bubbleable_metadata = $render_context->pop();
\Drupal\Core\Render\BubbleableMetadata::createFromObject($fl)
->merge($bubbleable_metadata);
}
/*
* !!!!! FIX ENDS HERE !!!!!
*/
$obj->flag_link = $fl;
return new ResourceResponse((array)$obj, 200);
}
}
Anyone who can get module maintainers to address this would be nice.
I am new to PHP unit testing and I need some clarity on how can we mock non-existent Interface. Basically, In my project, I want to test one protected method which is expecting two arguments one is Interface and another is a string.
I want to understand how can I pass Interface as an argument in a method. I tried to Mock the Interface but it's not working for me.
This is my main class
namespace App\Models;
class VerifyNs {
protected function NsCheck(SomeInterface $url, string $domain) {
$answer= dns_get_record($domain, DNS_NS);
if (!empty($answer[0]['target']), ('example.com' == substr($answer[0]['target'], -11)) {
$result = 'NS verification for #url passed., ['#url ' => $url ->getName()]';
return $result
}
return 'failed;
}
}
Here is the test case
class VerifyNsTest extends \PHPUnit\Framework\TestCase
{
/**
* To call protected method
* #param $object
* #param string $method
* #param array $parameters
* #return mixed
* #throws \Exception
*/
private function callMethod($object, string $method , array $parameters = [])
{
try {
$className = get_class($object);
$reflection = new \ReflectionClass($className);
} catch (\ReflectionException $e) {
throw new \Exception($e->getMessage());
}
$method = $reflection->getMethod($method);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
/**
* Tests for verifying NS of the domain.
*
* #dataProvider providerTestNsCheck
*/
public function testCheckNs($site, $url, $expected_result) {
$site_name = $this->getMockBuilder(SomeInterface::class)
->setMethods(['getName'])
->getMock();
$site_name->method('getName')->willReturn($site);
$verifyNs = new \App\Models\VerifyNs();
$this->assertEquals($expected_result, $this->callMethod($verifyNs, 'NsCheck', [ $site_name, $url]));
}
/**
* Data provider for testCheckNs().
*
*/
public function providerTestNsCheck() {
return [
[
'mysite',
'example.com',
'NS verification for mysite passed.',
], [
'google',
'google.com',
'failed.'
]
],
];
}
}
After running this, it's giving me an error
TypeError: Argument 1 passed to App\Models\VerifyNs::NsCheck() must be an instance of App\Models\SomeInterface, instance of Mock_SomeInterface_1ee04960 given
Can someone please help here? Is it possible to mock non_existent Interface and pass it as an argument to the method?
I was able to resolve this issue using prophesize
$site = $this->prophesize(SomeInterface::class);
$object =$site->reveal()
then passing $object in the callMethod.
I am finding extremely difficult to modify mock objects that are cloned by the class I am testing.
Here is my test:
$firstDocument = array('type' => 'venue', 'name'=> "first venue");
$venueContent = $this->getMockBuilder('My\Class\Namespace\VenueContent')->disableOriginalConstructor()->getMock();
$setValues = function($document) use(&$venueContent){
$venueContent->expects($this->any())->method('getDocument')->will($this->returnValue($document));
$venueContent->expects($this->any())->method('getName')->will($this->returnValue($document->name));
};
$venueContent->expects($this->any())->method('setDocument')->will($this->returnCallback($setValues));
$this->object = new ContentFactory();
$this->object->registerContentType('venue', $venueContent);
$firstVenue = $this->object->create($firstDocument);
This is the ContentFactory class:
class ContentFactory
{
/**
* #var array classMap
*/
private $contentTypes = array();
/**
* Register a document map for use in creating & validating documents
* #param string $name
* #param array $type
*/
public function registerContentType($name, $type)
{
$this->contentTypes[$name] = $type;
}
/**
* Create & validate a document
* #param array $document
* #throws \InvalidArgumentException
* #return ContentInterface
*/
public function create(array $document)
{
if (!isset($document['type'])) {
throw new \InvalidArgumentException('Unknown content type');
}
$documentType = $document['type'];
if (!\array_key_exists($documentType, $this->contentTypes)) {
throw new \InvalidArgumentException('Unmapped content service');
}
$contentModel = clone $this->contentTypes[$documentType];
$contentDocument = $this->createContentDocument($document);
$contentModel->setDocument($contentDocument);
return $contentModel;
}
/**
* Create underlying ContentDocument
* #param array $document
* #return ContentDocument
*/
private function createContentDocument($document)
{
return new ContentDocument($document);
}
}
My problem is that everytime I do a clone of the object, I cannot modify it in the callback of the test because the object I am passing in the USE statement is the original object (the one I use to clone).
Does anybody know how the callback can access the caller object so that I can modify it no matter what instance it is without using debug_backtrace?
Hi i am trying to set a a test to test my database calls. I want to pass a variables in url but cant seem to get it to work.
I wanted to do this
public function testDb()
{
$response = $this->call('GET', '/searchAvailability?keyword=test product');
$content = $response->getContent();
$this->assertEquals('[{"name":"test product"}]',$content );
}
But i keep getting "Undefined variable : keyword" when i try. It works in the browser just not when i run phpunit. Anyone got any ideas on why this is not working thanks.
The answer here is you need to specify the parameters differently in your call method:
$this->call('GET', '/searchAvailability', array('keyword' => 'test product'));
Below is the implementation of Illuminate\Foundation\Testing\TestCase::call method:
/**
* Call the given URI and return the Response.
*
* #param string $method
* #param string $uri
* #param array $parameters
* #param array $files
* #param array $server
* #param string $content
* #param bool $changeHistory
* #return \Illuminate\Http\Response
*/
public function call()
{
call_user_func_array(array($this->client, 'request'), func_get_args());
return $this->client->getResponse();
}
I like clean docs and phpdoc will automagically look up the type. When documenting a controller function that returns View::make, I have no idea what type to use for the #return in my documentation.
<?php
class FooController extends BaseController {
/**
* Show a view.
*
* #return ??? description of the view
*/
public function show(){
return View::make('bar');
}
}
What is the type here or is there a better way to document the function for this purpose?
The return value is
Illuminate\View\View
I traced through the ServiceProvider which lead me to
Illuminate\View\Environment::make
Which is line 113 of vendor/laravel/framework/src/Illuminate/View/Environment.php (in 4.1 at least)
/**
* Get a evaluated view contents for the given view.
*
* #param string $view
* #param array $data
* #param array $mergeData
* #return \Illuminate\View\View
*/
public function make($view, $data = array(), $mergeData = array())
{
$path = $this->finder->find($view);
$data = array_merge($mergeData, $this->parseData($data));
$this->callCreator($view = new View($this, $this->getEngineFromPath($path), $view, $path, $data));
return $view;
}