Fixed the environment for unit tests to work.

First unit test is working. Also all database migrations get executed automatically when running the unit tests.
develop
Hecht 6 years ago
parent 53d3066230
commit b8a8fbdc4b

13
.env

@ -1,19 +1,26 @@
# This file defines all environment variables that the application needs.
# DO NOT DEFINE PRODUCTION SECRETS IN THIS FILE.
# Use ".env.local" for local overrides during development.
# Use real environment variables when deploying to production.
# https://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=558a40bd107371e7f7f25b4adf2d0da9
APP_SECRET=879a6adeceeccbdc835a19f7e3aad7e8
#TRUSTED_PROXIES=127.0.0.1,127.0.0.2
#TRUSTED_HOSTS=localhost,example.com
#TRUSTED_HOSTS='^localhost|example\.com$'
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
# Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# Configure your db driver and server_version in config/packages/doctrine.yaml
#DATABASE_URL=pgsql://db_user:db_password@127.0.0.1:5432/db_name
DATABASE_URL=sqlite:///%kernel.project_dir%/var/data.db
###< doctrine/doctrine-bundle ###
###> symfony/swiftmailer-bundle ###
# For Gmail as a transport, use: "gmail://username:password@localhost"
# For a generic SMTP server, use: "smtp://localhost:25?encryption=&auth_mode="
# Delivery is disabled by default via "null://localhost"
MAILER_URL=null://localhost
###< symfony/swiftmailer-bundle ###

@ -0,0 +1,24 @@
# This file is a "template" of which env vars need to be defined for your application
# Copy this file to .env file for development, create environment variables when deploying to production
# https://symfony.com/doc/current/best_practices/configuration.html#infrastructure-related-configuration
###> symfony/framework-bundle ###
APP_ENV=dev
APP_SECRET=9d74944d92d8155f1c870695def94464
#TRUSTED_PROXIES=127.0.0.1,127.0.0.2
#TRUSTED_HOSTS=localhost,example.com
###< symfony/framework-bundle ###
###> doctrine/doctrine-bundle ###
# Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# Configure your db driver and server_version in config/packages/doctrine.yaml
DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name
###< doctrine/doctrine-bundle ###
###> symfony/swiftmailer-bundle ###
# For Gmail as a transport, use: "gmail://username:password@localhost"
# For a generic SMTP server, use: "smtp://localhost:25?encryption=&auth_mode="
# Delivery is disabled by default via "null://localhost"
MAILER_URL=null://localhost
###< symfony/swiftmailer-bundle ###

@ -1,6 +1,4 @@
# define your env variables for the test env here
KERNEL_CLASS=App\\Kernel
KERNEL_CLASS='App\Kernel'
APP_SECRET='s$cretf0rt3st'
SHELL_VERBOSITY=-1
SYMFONY_DEPRECATIONS_HELPER=999999
SYMFONY_PHPUNIT_VERSION=6.5

8
.gitignore vendored

@ -7,11 +7,11 @@
/vendor/
###< symfony/framework-bundle ###
###> symfony/web-server-bundle ###
/.web-server-pid
###< symfony/web-server-bundle ###
###> symfony/phpunit-bridge ###
.phpunit
/phpunit.xml
###< symfony/phpunit-bridge ###
###> symfony/web-server-bundle ###
/.web-server-pid
###< symfony/web-server-bundle ###

@ -3,6 +3,7 @@
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Debug\Debug;
set_time_limit(0);
@ -10,11 +11,21 @@ set_time_limit(0);
require dirname(__DIR__).'/vendor/autoload.php';
if (!class_exists(Application::class)) {
throw new \RuntimeException('You need to add "symfony/framework-bundle" as a Composer dependency.');
throw new RuntimeException('You need to add "symfony/framework-bundle" as a Composer dependency.');
}
Kernel::bootstrapCli($_SERVER['argv']);
Kernel::bootstrapEnv();
$input = new ArgvInput();
if (null !== $_ENV['APP_ENV'] = $input->getParameterOption(['--env', '-e'], null, true)) {
putenv('APP_ENV='.$_ENV['APP_ENV']);
// force loading .env files when --env is defined
$_SERVER['APP_ENV'] = null;
}
if ($input->hasParameterOption('--no-debug', true)) {
putenv('APP_DEBUG='.$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0');
}
require dirname(__DIR__).'/src/.bootstrap.php';
if ($_SERVER['APP_DEBUG']) {
umask(0000);
@ -26,4 +37,4 @@ if ($_SERVER['APP_DEBUG']) {
$kernel = new Kernel($_SERVER['APP_ENV'], $_SERVER['APP_DEBUG']);
$application = new Application($kernel);
$application->run();
$application->run($input);

@ -6,10 +6,9 @@ if (!file_exists(dirname(__DIR__).'/vendor/symfony/phpunit-bridge/bin/simple-php
exit(1);
}
$classLoader = require dirname(__DIR__).'/vendor/autoload.php';
App\Kernel::bootstrapEnv('test');
$classLoader->unregister();
if (false === getenv('SYMFONY_PHPUNIT_VERSION')) {
putenv('SYMFONY_PHPUNIT_VERSION=6.5');
}
if (false === getenv('SYMFONY_PHPUNIT_REMOVE')) {
putenv('SYMFONY_PHPUNIT_REMOVE=');
}

@ -6,25 +6,32 @@
"ext-ctype": "*",
"ext-iconv": "*",
"friendsofsymfony/rest-bundle": "^2.4",
"sensio/framework-extra-bundle": "^5.2",
"sensio/framework-extra-bundle": "^5.1",
"symfony/asset": "4.1.*",
"symfony/console": "4.1.*",
"symfony/expression-language": "4.1.*",
"symfony/flex": "^1.1",
"symfony/form": "4.1.*",
"symfony/framework-bundle": "4.1.*",
"symfony/monolog-bundle": "^3.3",
"symfony/orm-pack": "^1.0",
"symfony/monolog-bundle": "^3.1",
"symfony/orm-pack": "*",
"symfony/process": "4.1.*",
"symfony/security-bundle": "4.1.*",
"symfony/serializer-pack": "^1.0",
"symfony/serializer-pack": "*",
"symfony/swiftmailer-bundle": "^3.1",
"symfony/translation": "4.1.*",
"symfony/twig-bundle": "4.1.*",
"symfony/validator": "4.1.*",
"symfony/web-link": "4.1.*",
"symfony/yaml": "4.1.*"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.0",
"symfony/debug-pack": "^1.0",
"symfony/debug-pack": "*",
"symfony/dotenv": "4.1.*",
"symfony/maker-bundle": "^1.9",
"symfony/profiler-pack": "^1.0",
"symfony/test-pack": "^1.0",
"symfony/maker-bundle": "^1.0",
"symfony/profiler-pack": "*",
"symfony/test-pack": "*",
"symfony/web-server-bundle": "4.1.*"
},
"config": {

1102
composer.lock generated

File diff suppressed because it is too large Load Diff

@ -2,17 +2,18 @@
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\WebServerBundle\WebServerBundle::class => ['dev' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class => ['all' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
FOS\RestBundle\FOSRestBundle::class => ['all' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle::class => ['all' => true],
Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
Symfony\Bundle\DebugBundle\DebugBundle::class => ['dev' => true, 'test' => true],
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
Symfony\Bundle\WebServerBundle\WebServerBundle::class => ['dev' => true],
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
FOS\RestBundle\FOSRestBundle::class => ['all' => true],
];

@ -1,6 +1,6 @@
App\Entity\Hero:
type: entity
repositoryClass: App\Entity\Repository\HeroRepository
repositoryClass: App\Repository\HeroRepository
table: hero
id:
id:

@ -1,6 +1,6 @@
App\Entity\User:
type: entity
repositoryClass: App\Entity\Repository\UserRepository
repositoryClass: App\Repository\UserRepository
table: user
id:
id:

@ -0,0 +1,4 @@
# See https://symfony.com/doc/current/email/dev_environment.html
swiftmailer:
# send all emails to a specific address
#delivery_addresses: ['me@example.com']

@ -10,7 +10,7 @@ doctrine:
# configure these for your database server
driver: 'pdo_sqlite'
charset: utf8
url: '%env(resolve:DATABASE_URL)%'
orm:
auto_generate_proxy_classes: true

@ -31,4 +31,4 @@ framework:
serializer: { enable_annotations: true }
templating:
engines: ['twig']
engines: ['twig']

@ -18,7 +18,7 @@ security:
stateless: true
main:
anonymous: true
# activate different ways to authenticate
# http_basic: true

@ -0,0 +1,3 @@
swiftmailer:
url: '%env(MAILER_URL)%'
spool: { type: 'memory' }

@ -0,0 +1,2 @@
swiftmailer:
disable_delivery: true

@ -0,0 +1,3 @@
framework:
validation:
email_validation_mode: html5

@ -27,9 +27,5 @@ services:
resource: '../src/Controller'
tags: ['controller.service_arguments']
App\Entity\Repository\:
resource: '../src/Entity/Repository'
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones

@ -5,10 +5,13 @@
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.5/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
bootstrap="src/.bootstrap.php"
>
<php>
<ini name="error_reporting" value="-1" />
<env name="APP_ENV" value="test" />
<env name="SHELL_VERBOSITY" value="-1" />
<env name="SYMFONY_DEPRECATIONS_HELPER" value="weak_vendors" />
</php>
<testsuites>

@ -4,9 +4,7 @@ use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
require dirname(__DIR__).'/vendor/autoload.php';
Kernel::bootstrapEnv();
require dirname(__DIR__).'/src/.bootstrap.php';
if ($_SERVER['APP_DEBUG']) {
umask(0000);
@ -19,7 +17,7 @@ if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ??
}
if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
Request::setTrustedHosts(explode(',', $trustedHosts));
Request::setTrustedHosts([$trustedHosts]);
}
$kernel = new Kernel($_SERVER['APP_ENV'], $_SERVER['APP_DEBUG']);

@ -0,0 +1,51 @@
<?php
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
if (!array_key_exists('APP_ENV', $_SERVER)) {
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] ?? null;
}
if ('prod' !== $_SERVER['APP_ENV']) {
if (!class_exists(Dotenv::class)) {
throw new RuntimeException('The "APP_ENV" environment variable is not set to "prod". Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
}
$path = dirname(__DIR__).'/.env';
$dotenv = new Dotenv();
if (method_exists($dotenv, 'loadEnv')) {
$dotenv->loadEnv($path);
} else {
// fallback code in case your Dotenv component is not 4.2 or higher (when loadEnv() was added)
if (file_exists($path) || !file_exists($p = "$path.dist")) {
$dotenv->load($path);
} else {
$dotenv->load($p);
}
if (null === $env = $_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) {
$dotenv->populate(array('APP_ENV' => $env = 'dev'));
}
if ('test' !== $env && file_exists($p = "$path.local")) {
$dotenv->load($p);
$env = $_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? $env;
}
if (file_exists($p = "$path.$env")) {
$dotenv->load($p);
}
if (file_exists($p = "$path.$env.local")) {
$dotenv->load($p);
}
}
}
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $_SERVER['APP_ENV'] ?: $_ENV['APP_ENV'] ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';

@ -2,10 +2,9 @@
namespace App\Controller;
use App\Entity\Repository\HeroRepository;
use App\Repository\HeroRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
@ -25,7 +24,7 @@ class HeroController extends FOSRestController
*/
public function cgetAction()
{
$heros = $this->heroRepository->findAll();
return $this->view($heros, Response::HTTP_OK);
$heroes = $this->heroRepository->findAll();
return $this->view($heroes, Response::HTTP_OK);
}
}

@ -2,10 +2,9 @@
namespace App\Controller;
use App\Entity\Repository\UserRepository;
use App\Repository\UserRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**

@ -10,8 +10,10 @@ class UserFixtures extends Fixture
{
public const ADMIN_USER_REFERENCE = 'admin-user';
public const ADMIN_USER_TOKEN = 'ItsHammerTime!';
public const DUDE_USER_REFERENCE = 'dummy-user';
public const DUDE_USER_TOKEN = 'ItsDuderzeit!';
private $passwordEncoder;
@ -25,13 +27,13 @@ class UserFixtures extends Fixture
$userAdmin = new User();
$userAdmin->setUsername('admin');
$this->setPassword($userAdmin, '123456789');
$userAdmin->setApiToken('ItsHammerTime!');
$userAdmin->setApiToken(self::ADMIN_USER_TOKEN);
$manager->persist($userAdmin);
$userDude = new User();
$userDude->setUsername('dude');
$this->setPassword($userDude, '1234');
$userDude->setApiToken('ItsDuderzeit!');
$userDude->setApiToken(self::DUDE_USER_TOKEN);
$manager->persist($userDude);
$manager->flush();

@ -6,7 +6,6 @@ use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
@ -30,7 +29,7 @@ class Kernel extends BaseKernel
{
$contents = require $this->getProjectDir().'/config/bundles.php';
foreach ($contents as $class => $envs) {
if (isset($envs['all']) || isset($envs[$this->environment])) {
if ($envs[$this->environment] ?? $envs['all'] ?? false) {
yield new $class();
}
}
@ -59,82 +58,4 @@ class Kernel extends BaseKernel
$routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}
public static function bootstrapCli(array &$argv)
{
// consume --env and --no-debug from the command line
// when using symfony/console v4.2 or higher, this should
// be replaced by a call to Application::bootstrapEnv()
for ($i = 0; $i < \count($argv) && '--' !== $v = $argv[$i]; ++$i) {
if ('--no-debug' === $v) {
putenv('APP_DEBUG='.$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = '0');
$argvUnset[$i] = true;
break;
}
}
for ($i = 0; $i < \count($argv) && '--' !== $v = $argv[$i]; ++$i) {
if (!$v || '-' !== $v[0] || !preg_match('/^-(?:-env(?:=|$)|e=?)(.*)$/D', $v, $v)) {
continue;
}
if (!empty($v[1]) || !empty($argv[1 + $i])) {
putenv('APP_ENV='.$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = empty($v[1]) ? $argv[1 + $i] : $v[1]);
$argvUnset[$i] = $argvUnset[$i + empty($v[1])] = true;
}
break;
}
if (!empty($argvUnset)) {
$argv = array_values(array_diff_key($argv, $argvUnset));
}
}
public static function bootstrapEnv($env = null)
{
if (null !== $env) {
putenv('APP_ENV='.$_SERVER['APP_ENV'] = $env);
}
if ('prod' !== $_SERVER['APP_ENV'] = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : (isset($_ENV['APP_ENV']) ? $_ENV['APP_ENV'] : null)) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('The "APP_ENV" environment variable is not defined. You need to set it or run "composer require symfony/dotenv" to load it from a ".env" file.');
}
// when using symfony/dotenv v4.2 or higher, this call and the related methods
// below should be replaced by a call to the new Dotenv::loadEnv() method
self::loadEnv(new Dotenv(), \dirname(__DIR__).'/.env');
}
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : 'dev';
$_SERVER['APP_DEBUG'] = isset($_SERVER['APP_DEBUG']) ? $_SERVER['APP_DEBUG'] : (isset($_ENV['APP_DEBUG']) ? $_ENV['APP_DEBUG'] : 'prod' !== $_SERVER['APP_ENV']);
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
}
private static function loadEnv(Dotenv $dotenv, $path)
{
if (file_exists($path) || !file_exists($p = "$path.dist")) {
$dotenv->load($path);
} else {
$dotenv->load($p);
}
if (null === $env = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : (isset($_ENV['APP_ENV']) ? $_ENV['APP_ENV'] : null)) {
$dotenv->populate(array('APP_ENV' => $env = 'dev'));
}
if ('test' !== $env && file_exists($p = "$path.local")) {
$dotenv->load($p);
$env = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : (isset($_ENV['APP_ENV']) ? $_ENV['APP_ENV'] : $env);
}
if (file_exists($p = "$path.$env")) {
$dotenv->load($p);
}
if (file_exists($p = "$path.$env.local")) {
$dotenv->load($p);
}
}
}

@ -0,0 +1,35 @@
<?php declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20181118195745 extends AbstractMigration
{
public function up(Schema $schema) : void
{
// this up() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'sqlite', 'Migration can only be executed safely on \'sqlite\'.');
$this->addSql('CREATE TABLE hero (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, user_id INTEGER NOT NULL, name VARCHAR(32) NOT NULL)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_51CE6E865E237E06 ON hero (name)');
$this->addSql('CREATE INDEX IDX_51CE6E86A76ED395 ON hero (user_id)');
$this->addSql('CREATE TABLE user (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username VARCHAR(32) NOT NULL, password VARCHAR(255) NOT NULL, api_token VARCHAR(255) DEFAULT NULL, roles CLOB NOT NULL --(DC2Type:json)
)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D649F85E0677 ON user (username)');
$this->addSql('CREATE UNIQUE INDEX UNIQ_8D93D6497BA2F5EB ON user (api_token)');
}
public function down(Schema $schema) : void
{
// this down() migration is auto-generated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'sqlite', 'Migration can only be executed safely on \'sqlite\'.');
$this->addSql('DROP TABLE hero');
$this->addSql('DROP TABLE user');
}
}

@ -1,6 +1,6 @@
<?php
namespace App\Entity\Repository;
namespace App\Repository;
use App\Entity\Hero;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

@ -1,6 +1,6 @@
<?php
namespace App\Entity\Repository;
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

@ -2,11 +2,8 @@
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\UserRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
@ -17,11 +14,14 @@ use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class TokenAuthenticator extends AbstractGuardAuthenticator
{
private $em;
/**
* @var UserRepository
*/
private $userRepository;
public function __construct(EntityManagerInterface $em)
public function __construct(UserRepository $userRepository)
{
$this->em = $em;
$this->userRepository = $userRepository;
}
/**
@ -54,8 +54,7 @@ class TokenAuthenticator extends AbstractGuardAuthenticator
}
// if a User object, checkCredentials() is called
return $this->em->getRepository(User::class)
->findOneBy(['apiToken' => $apiToken]);
return $this->userRepository->findOneBy(['apiToken' => $apiToken]);
}
public function checkCredentials($credentials, UserInterface $user)

@ -86,6 +86,15 @@
"ref": "70062abc2cd58794d2a90274502f81b55cd9951b"
}
},
"egulias/email-validator": {
"version": "2.1.6"
},
"facebook/webdriver": {
"version": "1.6.0"
},
"fig/link-util": {
"version": "1.0.0"
},
"friendsofsymfony/rest-bundle": {
"version": "2.2",
"recipe": {
@ -108,7 +117,7 @@
"version": "1.3.0"
},
"ocramius/proxy-manager": {
"version": "2.2.2"
"version": "2.1.1"
},
"phpdocumentor/reflection-common": {
"version": "1.0.1"
@ -125,6 +134,9 @@
"psr/container": {
"version": "1.0.0"
},
"psr/link": {
"version": "1.0.0"
},
"psr/log": {
"version": "1.0.2"
},
@ -140,6 +152,12 @@
"ref": "fb7e19da7f013d0d422fa9bce16f5c510e27609b"
}
},
"swiftmailer/swiftmailer": {
"version": "v6.1.3"
},
"symfony/asset": {
"version": "v4.1.7"
},
"symfony/browser-kit": {
"version": "v4.1.7"
},
@ -155,7 +173,7 @@
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "3.3",
"ref": "b5026d7ffdb43b4d66f4cc091b1e6f94e6023986"
"ref": "181d766db0eb468f41337f9b2d9d5b61ba1ee441"
}
},
"symfony/css-selector": {
@ -191,6 +209,9 @@
"symfony/event-dispatcher": {
"version": "v4.1.7"
},
"symfony/expression-language": {
"version": "v4.1.7"
},
"symfony/filesystem": {
"version": "v4.1.7"
},
@ -203,16 +224,19 @@
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "1.0",
"ref": "b96338eb5155c5b97a80e7705abf30aa09c29167"
"ref": "5f8a51c0fad684396f6b6c0fd770e043439cb632"
}
},
"symfony/form": {
"version": "v4.1.7"
},
"symfony/framework-bundle": {
"version": "3.3",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "3.3",
"ref": "2230e9f42b10616b91a28d15ed3a2d984e0b6c10"
"ref": "9ec493d6f3575c54671493d635fa4b68658022ab"
}
},
"symfony/http-foundation": {
@ -224,6 +248,9 @@
"symfony/inflector": {
"version": "v4.1.7"
},
"symfony/intl": {
"version": "v4.1.7"
},
"symfony/maker-bundle": {
"version": "1.0",
"recipe": {
@ -245,18 +272,27 @@
"ref": "18ebf5a940573a20de06f9c4060101eeb438cf3d"
}
},
"symfony/options-resolver": {
"version": "v4.1.7"
},
"symfony/orm-pack": {
"version": "v1.0.5"
},
"symfony/panther": {
"version": "v0.2.0"
},
"symfony/phpunit-bridge": {
"version": "4.1",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "4.1",
"ref": "e637a1337f5faf0b2529b1c9a47de5e8286679f0"
"ref": "b4c7d939cac9a67e02366fa7971746e9cbf1dad0"
}
},
"symfony/polyfill-intl-icu": {
"version": "v1.10.0"
},
"symfony/polyfill-mbstring": {
"version": "v1.10.0"
},
@ -305,11 +341,20 @@
"symfony/stopwatch": {
"version": "v4.1.7"
},
"symfony/swiftmailer-bundle": {
"version": "2.5",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "2.5",
"ref": "3db029c03e452b4a23f7fc45cec7c922c2247eb8"
}
},
"symfony/templating": {
"version": "v4.1.7"
},
"symfony/test-pack": {
"version": "v1.0.2"
"version": "v1.0.4"
},
"symfony/translation": {
"version": "3.3",
@ -332,9 +377,21 @@
"ref": "369b5b29dc52b2c190002825ae7ec24ab6f962dd"
}
},
"symfony/validator": {
"version": "4.1",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "4.1",
"ref": "0cdc982334f45d554957a6167e030482795bf9d7"
}
},
"symfony/var-dumper": {
"version": "v4.1.7"
},
"symfony/web-link": {
"version": "v4.1.7"
},
"symfony/web-profiler-bundle": {
"version": "3.3",
"recipe": {

@ -2,7 +2,12 @@
namespace App\Tests\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\BrowserKit\Client;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\NullOutput;
class RestTestBase extends WebTestCase
{
@ -21,6 +26,7 @@ class RestTestBase extends WebTestCase
protected function reloadDoctrineFixtures()
{
self::runCommand('doctrine:migration:migrate');
self::runCommand('doctrine:fixtures:load --purge-with-truncate -n');
}

@ -0,0 +1,31 @@
<?php
namespace App\Tests\Controller;
use App\DataFixtures\UserFixtures;
class UserControllerTest extends RestTestBase
{
/**
* This test verifies that requesting
*/
public function testRetrieveUser()
{
$this->createRequestBuilder()
->setMethod('GET')
->setUri('/api/users')
->setAcceptType('application/json')
->addServerParameter('HTTP_X-AUTH-TOKEN', UserFixtures::ADMIN_USER_TOKEN)
->request();
$response = $this->client->getResponse();
$this->assertTrue(
$response->headers->contains('Content-Type', 'application/json'),
'the "Content-Type" header is "' . $response->headers->get('Content-Type') . '"' // optional message shown on failure
);
$this->assertEquals(200, $response->getStatusCode(), 'Status code was ' . $response->getStatusCode() . ' but expected 200: ' . $response->getContent());
}
}
Loading…
Cancel
Save