I am trying to build my first no-framework PHP application and I am following this tutorial.
I am relatively new to some concepts described in the tutorial. Despite this, I decided to use, as Dependency Injector, PHP-DI instead of the suggested one (rdlowrey/auryn).
I have created everything according to the tutorial except for the file Bootstrap.php (and the file Dependencies.php:
<?php declare(strict_types = 1);
require(__DIR__ . '/../vendor/autoload.php');
...
$container = include('Dependencies.php');
$request = $container->make('Http\HttpRequest');
$response = $container->make('Http\HttpResponse');
...
switch ($routeInfo[0]) {
...
case \FastRoute\Dispatcher::FOUND:
$className = $routeInfo[1][0];
$method = $routeInfo[1][1];
$vars = $routeInfo[2];
$class = $container->make($className);
$class->$method($vars); // (**)
break;
}
echo $response->getContent(); // (*)
$class can be only an instance of a Homepage class which has only one method (show()), called in (**):
class Homepage
{
private $request;
private $response;
private $renderer;
public function __construct(
Request $request,
Response $response,
Renderer $renderer
) {
$this->request = $request;
$this->response = $response;
$this->renderer = $renderer;
}
public function show() {
$data = [
'name' => $this->request->getParameter('name', 'stranger'),
];
$html = $this->renderer->render('Homepage', $data);
$this->response->setContent($html); // (***)
}
}
With all that said, the application returns a 200 HTTP response with an empty body [here (*)]
but if I try to print the content of the HTTP response after (***) I get the correct response.
This could mean that there are two different instances of an HttpResponse class. (Is that right?)
By using rdlowrey/auryn, the author of the tutorial, used the method share() to share the same HttpReponse instance among classes, as shown in the "original" Dependencies.php file:
<?php declare(strict_types = 1);
use \Auryn\Injector;
...
$injector = new Injector;
$injector->alias('Http\Response', 'Http\HttpResponse');
$injector->share('Http\HttpResponse');
...
return $injector;
Is there a way to get the same behavior using PHP-DI (with PHP definitions)?
Here's my version of Dependencies.php:
<?php declare(strict_types = 1);
$definitions = [
'Http\Request' => DI\create('Http\HttpRequest')->constructor(
$_GET, $_POST, $_COOKIE, $_FILES, $_SERVER),
'Http\HttpRequest' => function () {
$r = new Http\HttpRequest($_GET, $_POST, $_COOKIE, $_FILES, $_SERVER);
return $r;
},
'Http\Response' => DI\create('Http\HttpResponse'),
'Twig\Environment' => function () {
$loader = new Twig\Loader\FilesystemLoader(
dirname(__DIR__) . '/templates');
$twig = new Twig\Environment($loader);
return $twig;
},
'Example\Template\TwigRenderer' => function (Twig\Environment $renderer) {
return new Example\Template\TwigRenderer($renderer);
},
'Example\Template\Renderer' => DI\create(
'Example\Template\TwigRenderer')->constructor(
DI\get('Twig\Environment')),
];
$containerBuilder = new DI\ContainerBuilder;
$containerBuilder->addDefinitions($definitions);
$container = $containerBuilder->build();
return $container;
In Bootstrap.php, getting (get()) HttpRequest/HttpResponse instances, instead of making (make()) them, solved the problem.
...
$container = include('Dependencies.php');
$request = $container->get('Http\HttpRequest');
$response = $container->get('Http\HttpResponse');
...
As clearly stated in the documentation:
The make() method works like get() except it will resolve the entry
every time it is called. [..] if the entry is an object, an new instance will be created every time [..]
Related
In a Laravel project (Laravel 8 on PHP 8.0) I have a feature test in which I test an internal endpoint. The endpoint has a Controller calls a method on a Service. The Service then tries to call a third-party endpoint. It is this third-party endpoint that I would like to mock. The situation currently looks like this:
Internal Endpoint Feature Test
public function testStoreInternalEndpointSuccessful(): void
{
// arrange, params & headers are not important in this problem
$params = [];
$headers = [];
// act
$response = $this->json('POST', '/v1/internal-endpoint', $params, $headers);
// assert
$response->assertResponseStatus(Response::HTTP_OK);
}
Internal Endpoint Controller
class InternalEndpointController extends Controller
{
public function __construct(protected InternalService $internalService)
{
}
public function store(Request $request): InternalResource
{
$data = $this.internalService->fetchExternalData();
return new InternalResource($data); // etc.
}
}
Internal Service
use GuzzleHttp\ClientInterface;
class InternalService
{
public function __construct(protected ClientInterface $client)
{
}
public function fetchExternalData()
{
$response = $this->httpClient->request('GET', 'v1/external-data');
$body = json_decode($response->getBody()->getContents(), false, 512, JSON_THROW_ON_ERROR);
return $body;
}
}
I have looked at Guzzle's documentation, but it seems like the MockHandler strategy requires you to execute the http request inside of the test, which is not wat I want in my test. I want Guzzle's http client to be mocked and to return a custom http response that I can specify in my test. I have tried to mock Guzzle's http client like this:
public function testStoreInternalEndpointSuccessful(): void
{
// arrange, params & headers are not important in this problem
$params = [];
$headers = [];
$mock = new MockHandler([
new GuzzleResponse(200, [], $contactResponse),
]);
$handlerStack = HandlerStack::create($mock);
$client = new Client(['handler' => $handlerStack]);
$mock = Mockery::mock(Client::class);
$mock
->shouldReceive('create')
->andReturn($client);
// act
$response = $this->json('POST', '/v1/internal-endpoint', $params, $headers);
// assert
$response->assertResponseStatus(Response::HTTP_OK);
}
But the InternalService does not seem to hit this mock in the test.
I have also considered and tried to use Http Fake, but it didn't work and I assume Guzzle's http client does not extend Laravel's http client.
What would be the best way to approach this problem and mock the third-party endpoint?
Edit
Inspired by this StackOverflow question, I have managed to solve this problem by injecting a Guzzle client with mocked responses into my service. The difference to the aforementioned StackOverflow question is that I had to use $this->app->singleton instead of $this->app->bind because my DI was configured differently:
AppServiceProvider.php
namespace App\Providers;
use App\Service\InternalService;
use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
// my app uses ->singleton instead of ->bind
$this->app->singleton(InternalService::class, function () {
return new InternalService(new Client([
'base_uri' => config('app.internal.base_url'),
]));
});
}
}
Depending on your depending injection, you want to bind or singleton-ify your InternalService with a custom Guzzle http client that returns mocked responses, e.g. like this:
public function testStoreInternalEndpointSuccessful(): void
{
// depending on your DI configuration,
// this could be ->bind or ->singleton
$this->app->singleton(InternalService::class, function($app) {
$mockResponse = json_encode([
'data' => [
'id' => 0,
'name' => 'Jane Doe',
'type' => 'External',
'description' => 'Etc. you know the drill',
]
]);
$mock = new GuzzleHttp\Handler\MockHandler([
new GuzzleHttp\Psr7\Response(200, [], $mockResponse),
]);
$handlerStack = GuzzleHttp\HandlerStack::create($mock);
$client = new GuzzleHttp\Client(['handler' => $handlerStack]);
return new InternalService($client);
});
// arrange, params & headers are not important in this problem
$params = [];
$headers = [];
// act
$response = $this->json('POST', '/v1/internal-endpoint', $params, $headers);
// assert
$response->assertResponseStatus(Response::HTTP_OK);
}
See also: Unit Testing Guzzle inside of Laravel Controller with PHPUnit
I'm trying to upgrade my website's code from Slim v2 to v4. I'm not a hardcore programmer so I'm facing issues.
In Slim v2 I had some middleware where I was able to assign parameters to the Twig view before the route code executed.
Now I'm trying to manage the same with Slim v4 but without success.
I have a container:
$container = new \DI\Container();
I have the view:
$container->set('view', function(\Psr\Container\ContainerInterface $container) {
return Twig::create(__DIR__ . '/views');
});
I try to use this from middleware:
$this->get('view')->offsetSet('fbloginurl', $loginUrl);
But nothing append when the view rendered.
If I try to use the same from the route inside, its working fine.
Example route:
$app->get('/', function ($request, $response, $args) {
$params = array(...);
return $this->get('view')->render($response, 'index.html', $params);
});
There are two possible failures. First, the DI container may always return a new instance, thus it doesn't store the variables in the correct instance and they are not rendered in the twig template. Second, you use a different approach in your route sample. You pass the variables via your $params variable and they are given into the template by this way.
So you may store $this->get('view') in a variable or pass the variables as the third parameter of $params.
EDIT: You could also check, if your variable in your DI\Container already exists and then just return the instance.
So this is a test code:
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Routing\RouteContext;
require 'vendor/autoload.php';
require 'config.php';
lib\Cookie::init();
$container = new \DI\Container();
$container->set('view', function($container) {
return Twig::create(__DIR__ . '/views');
});
$container->set('flash', function ($container) {
return new \Slim\Flash\Messages();
});
$container->get('view')->getEnvironment()->addGlobal('flash', $container->get('flash'));
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->addErrorMiddleware(true, false, false);
$fb = new Facebook\Facebook([
'app_id' => '...',
'app_secret' => '...',
'default_graph_version' => '...',
]);
$beforeMiddleware = function (Request $request, RequestHandler $handler) use ($fb) {
$response = $handler->handle($request);
if (!isset($_SESSION['fbuser'])) {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email'];
$loginUrl = $helper->getLoginUrl('...', $permissions);
$this->get('view')->offsetSet('fbloginurl', $loginUrl);
}
else {
$this->get('view')->offsetSet('fbuser', $_SESSION['fbuser']);
}
$uri = $request->getUri();
$this->get('view')->offsetSet('currenturl', $uri);
return $response;
};
$app->add($beforeMiddleware);
$app->get('/test', function (Request $request, Response $response, $args) {
$oViewParams = new \lib\ViewParams("home", "", "", "", "");
$oProfession = new \models\Profession();
$oBlogPost = new models\BlogPost();
$oBlogTopic = new models\BlogTopic();
$professions = $oProfession->getProfessionsWithLimit(14);
$posts = $oBlogPost->getMainPagePosts();
echo $this->get('view')->offsetGet('fbloginurl');
$params = array('professions' => $professions,
'posts' => $posts,
'viewp' => $oViewParams->getMassParams());
return $this->get('view')->render($response, 'index.html', $params);
});
$app->run();
When I use echo $this->get('view')->offsetGet('fbloginurl'); within the middleware it shows up. When I use the same within the route there is nothing show up...
I'm doing some programming in Silex with the symfony components and I think I have found a bug with the symfony/serializer and the symfony/validator components.
First let me explain what I'm traing to achieve, then let's go to the code.
My objective is to annotate a class with information like serialization directives as well as validation directives. As the reading of these annotations can cost a litle cpu, I like to cache them in memory. For this purpose, I'm using memcache wrapper in the Doctrine/Common/Cache package.
The problem I face is that both the symfony/serializer and the symfony/validator write Metadata to the cache using the class name as key. When they try to retrieve the metadata later, they throw an exception, because the cache has invalid metadata, either an instance of Symfony\Component\Validator\Mapping\ClassMetadata or Symfony\Component\Serializer\Mapping\ClassMetadataInterface.
Following is a reproductible example (sorry if its big, I tried to make as small as possible):
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
class Foo
{
/**
* #var int
* #Assert\NotBlank(message="This field cannot be empty")
*/
private $someProperty;
/**
* #return int
* #Groups({"some_group"})
*/
public function getSomeProperty() {
return $this->someProperty;
}
}
use Doctrine\Common\Annotations\AnnotationReader;
use \Memcache as MemcachePHP;
use Doctrine\Common\Cache\MemcacheCache as MemcacheWrapper;
$loader = require_once __DIR__ . '/../vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
$memcache = new MemcachePHP();
if (! $memcache->connect('localhost', '11211')) {
throw new \Exception('Unable to connect to memcache server');
}
$cacheDriver = new MemcacheWrapper();
$cacheDriver->setMemcache($memcache);
$app = new \Silex\Application();
$app->register(new Silex\Provider\SerializerServiceProvider());
$app['serializer.normalizers'] = function () use ($app, $cacheDriver) {
$classMetadataFactory = new Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory(
new Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader(new AnnotationReader()), $cacheDriver);
return [new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer($classMetadataFactory) ];
};
$app->register(new Silex\Provider\ValidatorServiceProvider(), [
'validator.mapping.class_metadata_factory' =>
new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(
new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader(new AnnotationReader()),
new \Symfony\Component\Validator\Mapping\Cache\DoctrineCache($cacheDriver)
)
]);
$app->get('/', function(\Silex\Application $app) {
$foo = new Foo();
$app['validator']->validate($foo);
$json = $app['serializer']->serialize($foo, 'json');
return new \Symfony\Component\HttpFoundation\JsonResponse($json, \Symfony\Component\HttpFoundation\Response::HTTP_OK, [], true);
});
$app->error(function (\Exception $e, \Symfony\Component\HttpFoundation\Request $request, $code) {
return new \Symfony\Component\HttpFoundation\Response('We are sorry, but something went terribly wrong.' . $e->getMessage());
});
$app->run();
After running this example you get fatal errors.
Can anyone confirm that I'm not making a hard mistake here?
Currently my workaround for this is rewrite the DoctrineCache class making use of a namespace for the cache keys. Its working, but I think its ugly.
I think what you need to do is two separate CacheDrivers. See https://github.com/doctrine/cache/blob/master/lib/Doctrine/Common/Cache/CacheProvider.php for how namespaces are used there.
You could:
$validatorCacheDriver = new MemcacheWrapper();
$validatorCacheDriver->setMemcache($memcache);
$validatorCacheDriver->setNamespace('symfony_validator');
$serializerCacheDriver = new MemcacheWrapper();
$serializerCacheDriver->setMemcache($memcache);
$serializerCacheDriver->setNamespace('symfony_serializer');
// note that the two drivers are using the same memcache instance,
// so only one connection will be used.
$app['serializer.normalizers'] = function () use ($app, $serializerCacheDriver) {
$classMetadataFactory = new Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory(
new Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader(new AnnotationReader()), $serializerCacheDriver);
return [new Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer($classMetadataFactory) ];
};
$app->register(new Silex\Provider\ValidatorServiceProvider(), [
'validator.mapping.class_metadata_factory' =>
new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(
new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader(new AnnotationReader()),
new \Symfony\Component\Validator\Mapping\Cache\DoctrineCache($validatorCacheDriver)
)
]);
I've trimmed the code to only show the parts that play some part in the solution. I hope this helps!
I'm trying to create a controller action that results in two responses. The SwiftMailer uses the kernel.terminate event to accomplish this. I can build an event listener for the event but I don't know how to tell it what I want it to do. I know what it takes to create and download a pdf file, but how will the listener know when to do it?
Edit:
The "tell it" is found here in SO by doing this:
if ($nextAction) {
$request->attributes->set('household_id', $id);
}
But it is not at all clear how to get the event listener to do all of this (copied from a controller, but for the first line):
$em = $this->container->get('doctrine.orm.default_entity_manager');
$household = $em->getRepository('ManaClientBundle:Household')->find($id);
$fname = $household->getHead()->getFname();
$sname = $household->getHead()->getSname();
$filename = $sname . $fname . 'card.pdf';
$stylesheetXml = $this->renderView('ManaClientBundle:Test:pdfstyle.xml.twig', array());
$facade = $this->get('ps_pdf.facade');
$response = new Response();
$this->render('ManaClientBundle:Test:card.pdf.twig', array(
'household' => $household,
'date' => date_create(),
), $response);
$xml = $response->getContent();
$content = $facade->render($xml, $stylesheetXml);
header('content-type:application/pdf;' .
'Content-Disposition:attachment; filename=' . $filename);
echo $content;
Form includes:
->add('save', 'submit')
->add('saveCreate', 'submit')
Controller includes:
$nextAction = $form->get('saveCreate')->isClicked();
if ($nextAction) {
// tell event to create and download a pdf file using $id
}
return $this->redirect($this->generateUrl('household_show', array('id' => $id)));
service:
listener.pdfresponse:
class: Mana\ClientBundle\EventListener\PdfListenerSubscriber
arguments: [ #service_container ]
tags:
- { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }
Listener
namespace Mana\ClientBundle\EventListener;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PdfListenerSubscriber implements EventSubscriberInterface {
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function onKernelTerminate(PostResponseEvent $event) {
//create and download pdf file
}
static public function getSubscribedEvents()
{
return array(
KernelEvents::TERMINATE => 'onKernelTerminate');
}
}
Two responses to an HTTP request would never be possible - once the first request has been responded to, the connection is dropped by the web server so there would be nowhere for the second response to be sent.
I'm trying to write some PHPUnit tests for my small slim framework app, but don't see anywhere in the docs that point to a way to do a full request and assert on the response (either containing text or a 200 status, or anything, really).
Is there any way to do this that anyone has found/used?
Here is example how you may test your Slim application:
https://github.com/mac2000/SlimTestable
Suppose we have simple application:
<?php
use Slim\Slim;
require_once 'vendor/autoload.php';
$app = new Slim();
$app->get('/', function(){
echo 'home';
})->name('home');
$app->get('/hello/:name', function($name){
echo "hello $name";
})->name('hello');
$app->map('/login', function() use($app) {
if($app->request()->params('login')) {
$app->flash('success', 'Successfully logged in');
$app->redirect($app->urlFor('hello', array('name' => $app->request()->params('login'))));
} else {
$app->flash('error', 'Wrong login');
$app->redirect($app->urlFor('home'));
}
})->via('GET', 'POST');
$app->run();
How do we test it?
Create App class:
<?php // src/App.php
use Slim\Slim;
class App extends Slim {
function __construct(array $userSettings = array())
{
parent::__construct($userSettings);
$this->get('/', function(){
echo 'home';
})->name('home');
$this->get('/hello/:name', function($name){
echo "hello $name";
})->name('hello');
$this->map('/login', function() {
if($this->request()->params('login')) {
$this->flash('success', 'Successfully logged in');
$this->redirect($this->urlFor('hello', array('name' => $this->request()->params('login'))));
} else {
$this->flash('error', 'Wrong login');
$this->redirect($this->urlFor('home'));
}
})->via('GET', 'POST');
}
/**
* #return \Slim\Http\Response
*/
public function invoke() {
$this->middleware[0]->call();
$this->response()->finalize();
return $this->response();
}
}
Notice that we move all our routes to new class constructor, also notice new invoke method, which do the same as run method except it returns response rather than echoing it out.
Now your index.php file might be like this one:
<?php
require_once 'vendor/autoload.php';
$app = new App();
$app->run();
And now it is time for tests:
<?php // tests/ExampleTest.php
use Slim\Environment;
class ExampleTest extends PHPUnit_Framework_TestCase {
private $app;
public function setUp()
{
$_SESSION = array();
$this->app = new App();
}
public function testHome() {
Environment::mock(array(
'PATH_INFO' => '/'
));
$response = $this->app->invoke();
$this->assertContains('home', $response->getBody());
}
public function testHello() {
Environment::mock(array(
'PATH_INFO' => '/hello/world'
));
$response = $this->app->invoke();
$this->assertTrue($response->isOk());
$this->assertContains('hello world', $response->getBody());
}
public function testNotFound() {
Environment::mock(array(
'PATH_INFO' => '/not-exists'
));
$response = $this->app->invoke();
$this->assertTrue($response->isNotFound());
}
public function testLogin() {
Environment::mock(array(
'PATH_INFO' => '/login'
));
$response = $this->app->invoke();
$this->assertTrue($response->isRedirect());
$this->assertEquals('Wrong login', $_SESSION['slim.flash']['error']);
$this->assertEquals('/', $response->headers()->get('Location'));
}
public function testPostLogin() {
Environment::mock(array(
'REQUEST_METHOD' => 'POST',
'PATH_INFO' => '/login',
'slim.input' => 'login=world'
));
$response = $this->app->invoke();
$this->assertTrue($response->isRedirect());
$this->assertEquals('Successfully logged in', $_SESSION['slim.flash']['success']);
$this->assertEquals('/hello/world', $response->headers()->get('Location'));
}
public function testGetLogin() {
Environment::mock(array(
'PATH_INFO' => '/login',
'QUERY_STRING' => 'login=world'
));
$response = $this->app->invoke();
$this->assertTrue($response->isRedirect());
$this->assertEquals('Successfully logged in', $_SESSION['slim.flash']['success']);
$this->assertEquals('/hello/world', $response->headers()->get('Location'));
}
}
You should notice few things:
While setting up test we are creating $_SESSION array for test purposes and instantiate our App class object.
In tests rather than run we are calling invoke which do the same, but returns response object.
Environment::mock used to mock requests which are processed with our application.
Ok, so I was able to rough it and make it work. Here's an example of an endpoint test class.
Assuming you're working in a development environment, you can execute curl requests to your own localhost, thus testing before committing to a repo.
First, create your class:
class ApiEndpointsTest extends PHPUnit_Framework_TestCase
{
protected $api_url = "http://localhost/api/v1";
//create a function that will allow you to call API endpoints at-will.
private function loadEndpoint($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return array(
'body' => $output,
'info' => $info
);
}
//this allows you to write messages in the test output
private function printToConsole($statement) {
fwrite(STDOUT, $statement."\n");
}
Using this, you can write a test function for a particular endpoint response:
//this will test the actual body of the response against something expected.
public function testGetUserResponse() {
$this->printToConsole(__METHOD__);
$url = $this->api_url."/users/124";
$response = $this->loadEndpoint($url);
$expected = '[{"name":"John Smith","email":"john#acme.com"}]';
$this->assertEquals($response['body'], $expected);
}
In a separate test, you can test any other property of the API call's response:
public function testGetUserMimeType() {
$this->printToConsole(__METHOD__);
$url = $this->api_url."/users/124";
$response = $this->loadEndpoint($url);
$this->assertEquals($response['info']['content_type'], 'application/json');
}
Your info property options can be found here: http://php.net/manual/en/function.curl-getinfo.php
Side note: if anyone reading this is an expert at PHPUnit and knows a better way, I'm interested in learning about it -- I'm new to PHPUnit.