We have the following middleware. We know the middleware works since testing the application in browser is working. Sadly when writing HTTP test case, blade is saying that the variable defined by the middleware is not there.
<?php
namespace App\Http\Middleware;
use App\Repository\UserContract;
use Closure;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Illuminate\Support\Facades\View;
class Authenticate
{
/**
* @var UserContract
*/
private $userRepository;
/**
* @var ViewFactory
*/
private $view;
public function __construct(UserContract $userRepository, ViewFactory $view)
{
$this->userRepository = $userRepository;
$this->view = $view;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle($request, Closure $next)
{
$userId = null;
$username = null;
if ($request->hasCookie('auth')) {
$secret = $request->cookie('auth');
// dump($secret);
$userId = $this->userRepository->getUserIdBySecret($secret);
$username = $this->userRepository->getUsername($userId);
}
$this->view->share('username', $username);
// \View::share('username', $username);
$request['_user_id'] = $userId;
$request['_username'] = $username;
return $next($request);
}
}
We doing a PHPUnit test as following:
/**
* @test
*/
public function it_shows_logged_in_username()
{
// $this->withoutMiddleware(EncryptCookies::class);
// $this->withMiddleware(\Illuminate\View\Middleware\ShareErrorsFromSession::class);
// $this->withMiddleware(Authenticate::class);
$app = $this->createApplication();
/** @var Encrypter $encrypter */
$encrypter = $app->get(Encrypter::class);
$userRepository = $app->make(UserContract::class);
$userRepository->addUser('jane', 'secret');
$secret = $encrypter->encrypt('secret', false);
$response = $this->call('GET', '/', [], ['auth' => $secret], [], [], null);
// $response->dumpHeaders();
// $response->dump();
$response->assertSeeText('jane');
}
error
ErrorException {#980
#message: "Undefined variable: username"
#code: 0
#file: "./storage/framework/views/db4b9232a3b0957f912084f26d9041e8a510bd6c.php"
#line: 3
#severity: E_NOTICE
trace: {
./storage/framework/views/db4b9232a3b0957f912084f26d9041e8a510bd6c.php:3 {
› <?php dump($comments); ?>
› <?php dump($username); ?>
Any advice would be appreciated?
Aucun commentaire:
Enregistrer un commentaire