I'm trying to set up unittests, but I'm having no luck at all. I created TestHelper.php in a tests folder. This file looks like this:
<?php
use Phalcon\Di;
use Phalcon\Di\FactoryDefault;
ini_set('display_errors',1);
error_reporting(E_ALL);
define('ROOT_PATH', __DIR__);
define('PATH_LIBRARY', __DIR__ . '/../app/library/');
define('PATH_SERVICES', __DIR__ . '/../app/services/');
define('PATH_RESOURCES', __DIR__ . '/../app/resources/');
define('BASE_DIR', dirname(__DIR__));
define('APP_DIR', BASE_DIR . '/app');
set_include_path(
ROOT_PATH . PATH_SEPARATOR . get_include_path()
);
// Required for phalcon/incubator
include __DIR__ . "/../vendor/autoload.php";
// Use the application autoloader to autoload the classes
// Autoload the dependencies found in composer
$loader = new \Phalcon\Loader();
$loader->registerDirs(
array(
ROOT_PATH
)
);
$config = include APP_DIR . '/config/config.php';
$loader->registerNamespaces(array(
'MyApp\Models' => $config->application->modelsDir,
'MyApp\Controllers' => $config->application->controllersDir,
'MyApp\Forms' => $config->application->formsDir,
'MyApp\Classes' => $config->application->classesDir,
'MyApp' => $config->application->libraryDir
));
$loader->register();
I also created UnitTestCase.php:
<?php
use Phalcon\Di;
use Phalcon\DI\FactoryDefault;
use Phalcon\Test\UnitTestCase as PhalconTestCase;
use Phalcon\Mvc\View;
use Phalcon\Crypt;
use Phalcon\Mvc\Dispatcher;
use \Phalcon\Mvc\Dispatcher as PhDispatcher;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Files as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Logger;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Logger\Adapter\File as LoggerFile;
use MyApp\Auth\Auth;
use MyApp\AuthPublic\AuthPublic;
use MyApp\Acl\Acl;
use MyApp\CacheData\CacheData;
use MyApp\Mail\Mail;
use MyApp\PHPExcel\PHPExcel;
abstract class UnitTestCase extends PhalconTestCase
{
/**
* #var \Voice\Cache
*/
protected $_cache;
/**
* #var \Phalcon\Config
*/
protected $_config;
/**
* #var bool
*/
private $_loaded = false;
public function setUp(Phalcon\DiInterface $di = NULL, Phalcon\Config $config = NULL)
{
// Load any additional services that might be required during testing
$di = new FactoryDefault();
$config = include APP_DIR . '/config/config.php';
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->set('url', function () use ($config) {
$url = new UrlResolver();
$url->setBaseUri($config->application->baseUri);
return $url;
}, true);
/**
* Setting up the view component
*/
$di->set('view', function () use ($config) {
$view = new View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines(array(
'.volt' => function ($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions(array(
'compiledPath' => $config->application->cacheDir . 'volt/',
'compiledSeparator' => '_'
));
return $volt;
}
));
return $view;
}, true);
/**
* Database connection is created based in the parameters defined in the configuration file
*/
$di->set('db', function () use ($config) {
$eventsManager = new EventsManager();
// Debug sql logging //
$is_debug_sql_logging = true;
if ( $is_debug_sql_logging )
{
$logger = new LoggerFile( $config->application->logsDir ."debug_sql.log" );
$logger->log( "\n------\n" );
// Listen all the database events //
$eventsManager->attach( 'db', function( $event, $connection ) use ($logger) {
if ( $event->getType() == 'beforeQuery' ) {
$log_message = $connection->getRealSQLStatement()."\n".print_r( $connection->getSQLVariables(), true );
$logger->log( $log_message, Logger::DEBUG );
}
if ($event->getType() == 'afterQuery') {
//...//
}
});
}
// Database connection //
$dbAdapter = new DbAdapter(array(
'host' => 'localhost',
'username' => 'root',
'password' => 'root',
'dbname' => 'database'
));
//Assign the eventsManager to the db adapter instance
$dbAdapter->setEventsManager( $eventsManager );
return $dbAdapter;
});
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set('modelsMetadata', function () use ($config) {
return new MetaDataAdapter(array(
'metaDataDir' => $config->application->cacheDir . 'metaData/'
));
});
$di->set('modelsManager', function() {
return new \Phalcon\Mvc\Model\Manager();
});
/**
* Start the session the first time some component request the session service
*/
$di->set('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
/**
* Cache of models
*/
$di->set('cache', function () {
$cacheData = new CacheData();
return $cacheData;
});
/**
* Crypt service
*/
$di->set('crypt', function () use ($config) {
$crypt = new Crypt();
$crypt->setKey($config->application->cryptSalt);
return $crypt;
});
/**
* Set a 404 redirect AND use a default namespace
*/
$di->set('dispatcher', function() use ($di) {
$evManager = $di->getShared('eventsManager');
$evManager->attach(
"dispatch:beforeException",
function($event, $dispatcher, $exception)
{
switch ($exception->getCode()) {
case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'show404',
)
);
return false;
}
}
);
$dispatcher = new PhDispatcher();
$dispatcher->setEventsManager($evManager);
/* Dispatcher use a default namespace */
$dispatcher->setDefaultNamespace('MyApp\Controllers');
return $dispatcher;
},
true
);
/**
* Loading routes from the routes.php file
*/
$di->set('router', function () {
return require __DIR__ . '/routes.php';
});
/**
* Flash service with custom CSS classes
*/
$di->set('flash', function () {
return new Flash(array(
'error' => 'notification notification--error',
'success' => 'notification notification--success',
'notice' => 'notification notification--neutral',
'general' => 'notification notification--general',
'warning' => 'notification notification--warning'
));
});
/**
* Authentication component
*/
$di->set('auth', function () {
return new Auth();
});
/**
* Self test authentication component
*/
$di->set('authPublic', function () {
return new AuthPublic();
});
/**
* Mail service uses AmazonSES
*/
$di->set('mail', function () {
return new Mail();
});
/**
* Access Control List
*/
$di->set('acl', function () {
return new Acl();
});
/**
* PHPExcel
*/
$di->set('phpexcel', function () {
return new PHPExcel();
});
parent::setUp($di, $config);
$this->_loaded = true;
}
/**
* Check if the test case is setup properly
*
* #throws \PHPUnit_Framework_IncompleteTestError;
*/
public function __destruct()
{
if (!$this->_loaded) {
throw new \PHPUnit_Framework_IncompleteTestError('Please run parent::setUp().');
}
}
}
And also phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="TestHelper.php"
backupGlobals="false"
backupStaticAttributes="false"
verbose="true"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true">
<testsuite name="Phalcon - Testsuite">
<directory>./</directory>
</testsuite>
</phpunit>
All this together, should make me able to run some unittests. However, when I go to the tests folder in terminal and run ../vendor/bin/phpunit it throws an error. The error is Phalcon\Di\Exception: Service 'modelsManager' wasn't found in the dependency injection container. I have been struggling for some hours with this and I hope someone will be able to help me. What am I doing wrong here?
Add DI::setDefault($di); before parent::setUp($di, $config); in UnitTestCase.php
This way you can access DI components globally, not only in local scope.
My setUp() function in UnitTestCase.php looks like this:
public function setUp()
{
parent::setUp();
$di = new FactoryDefault();
// load all services.
include APP_PATH . "/config/services.php";
DI::setDefault($di);
$this->setDi($di);
$this->_loaded = true;
}
This way I have access to DI via $this->di (eg: $this->di->get('config') and all other related libraries which need DI can get it globally.
Related
I tried to get slim with PHP-DI and Autowiring working, without success. Maybe I have a wrong understanding of autowiring.
I setup a new project and created the following Index.php:
require __DIR__ . '/../vendor/autoload.php';
use userservice\core\services\UserServiceInterface;
use userservice\infrastructure\services\UserService;
use userservice\webservice\controller\UsersController;
use DI\Container;
$app = \DI\Bridge\Slim\Bridge::create();
$container = $app->getContainer();
$container->set(UserServiceInterface::class, UserService::class);
$container->set(UsersController::class, UsersController::class);
$app->get('/user', [UsersController::class, 'get']);
$app->run();
The UsersController
namespace userservice\webservice\controller;
use userservice\core\services\UserServiceInterface;
class UsersController{
/**
*
* #var UserServiceInterface
*/
private $userService;
public function __construct(UserServiceInterface $userService) {
$this->userService = $userService;
}
public function get(\Psr\Http\Message\ResponseInterface $response, \Psr\Http\Message\RequestInterface $request){
//$user = $this->userService->get();
$response->getBody()->write("Test");
return $response;
}
}
In the example above I get the following error-message:
Non-static method userservice\webservice\controller\UsersController::get() should not be called statically in
I found a working solution how I can use PHP-DI autowiring with mapping to interfaces:
require __DIR__ . '/../vendor/autoload.php';
use userservice\core\services\UserServiceInterface;
use userservice\infrastructure\services\UserService;
use userservice\webservice\controller\UsersController;
use userservice\core\repositories\UserRepositoryInterface;
use userservice\infrastructure\repositories\UserRepository;
/**
* Mapping of classes to interfaces
*/
$definitions = [
//REPOSITORIES
UserRepositoryInterface::class => DI\get(UserRepository::class),
//SERVICES
UserServiceInterface::class => DI\get(UserService::class),
];
$builder = new DI\ContainerBuilder();
$builder->addDefinitions($definitions);
$container = $builder->build();
$app = \DI\Bridge\Slim\Bridge::create($container);
$app->get('/user', [UsersController::class, 'get']);
$app->run();
I'm New in Phalcon framework. I'm testing my first multi module phalcon project with : Phalcon-4.0.3, i have install psr and i'm following example from phalcon documentation. everything is normal without volt engine but my backend module or controller not responding and i didnt get any error & the problem is i cant redirect to beckend module or controller if any expert please solve my issue!!
[index.php]
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Application;
$di = new FactoryDefault();
$di->set('router',function () {
$router = new Router(false);
$router->setDefaultModule('frontend');
$router->add('/backend',
[
'module' => 'backend',
'controller' => 'index',
'action' => 'index',
]
);
return $router;
}
);
$application = new Application($di);
$application->registerModules(
[
'frontend' => [
'className' => 'Multiple\Frontend\Module',//\Multiple\Frontend\Module::class,
'path' => '../apps/frontend/Module.php',
],
'backend' => [
'className' => 'Multiple\Backend\Module',//\Multiple\Backend\Module::class,
'path' => '../apps/backend/Module.php',
],
]
);
try{
$response = $application->handle($_SERVER["REQUEST_URI"]);
$response->send();
}catch (\Throwable $e) {
echo $e->getMessage();
}
[Backend Module]
namespace Multiple\Backend;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;
use Phalcon\Di\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
class Module implements ModuleDefinitionInterface
{
public function registerAutoloaders(DiInterface $di = null)
{
$loader = new Loader();
$loader->registerClasses([
'Multiple\Backend\Module' =>'../apps/backend/Module.php',
]);
$loader->registerNamespaces(
[
'Multiple\Backend\Controllers' => '../apps/backend/controllers/',
'Multiple\Backend\Models' => '../apps/backend/models/',
]
);
$loader->register();
}
public function registerServices(DiInterface $di)
{
$di->set('dispatcher',function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace('Multiple\Backend\Controllers');
return $dispatcher;
}
);
$di->set('view',function () {
$view = new View();
$view->setViewsDir('../apps/backend/views/');
return $view;
}
);
}
}
[Frontend Module]
namespace Multiple\Frontend;
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Volt;
use Phalcon\Di\DiInterface;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\ModuleDefinitionInterface;
class Module implements ModuleDefinitionInterface
{
/**
* Register a specific autoloader for the module
*/
public function registerAutoloaders(DiInterface $di = null)
{
$loader = new Loader();
$loader->registerClasses([
'Multiple\Frontend\Module' =>'../apps/frontend/Module.php',
]);
$loader->registerNamespaces([
'Multiple\Frontend\Controllers' => '../apps/frontend/controllers/',
'Multiple\Frontend\Models' => '../apps/frontend/models/',
]);
$loader->register();
}
/**
* Register specific services for the module
*/
public function registerServices(DiInterface $di)
{
// Registering a dispatcher
$di->set('dispatcher',function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace('Multiple\Frontend\Controllers');
return $dispatcher;
}
);
// Registering the view component
$di->set('view',function () {
$view = new View();
$view->setViewsDir('../apps/frontend/views/');
return $view;
}
);
}
}
I create a new project with Phalcon framework.
For begin, my environment is :
Phalcon 3.2.12
Windows 10
Xampp / PHP 7.2
At this time, I have created one login page in the index. When I launch my application, I have this message :
Fatal error: Uncaught Phalcon\Mvc\Dispatcher\Exception: Dispatcher has
detected a cyclic routing causing stability problems in
\public\index.php:32
Line 32 :
echo $application->handle()->getContent();
There is my dispatcher in services.php :
$di->setShared('dispatcher', function () use ($di) {
$evManager = $di->getShared('eventsManager');
$evManager->attach("dispatch:beforeException", function ($event, $dispatcher, $exception) {
switch ($exception->getCode()) {
case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(array(
'controller' => 'index',
'action' => 'show404'
));
return false;
}
});
$dispatcher = new PhDispatcher();
$dispatcher->setEventsManager($evManager);
return $dispatcher;
});
There is my IndexController :
class IndexController extends ControllerBase
{
public function indexAction()
{
$this->view->setLayout('login');
}
public function show404Action()
{
$this->view->setLayout('login');
$this->response->setStatusCode(404, "Not Found");
$this->view->pick('index/404');
}
}
There is my ControllerBase :
public function beforeExecuteRoute($dispatcher)
{
$isValid = true;
// check auth
if ($dispatcher->getControllerName() !== 'index') {
$isValid = false;
$this->view->disable();
$this->response->setStatusCode(401, 'Vous devez vous identifier pour accéder à votre environnement.');
if (!$this->request->isAjax()) {
$this->response->redirect('index');
}
}
return $isValid;
}
index.php
define('APP_PATH', realpath('..'));
/**
* Define APPLICATION_ENV (DEV,STAGING,PREPROD,PROD)
*
* #var APPLICATION_ENV string
*/
defined('APPLICATION_ENV') || define('APPLICATION_ENV', (isset($_SERVER['APPLICATION_ENV']) ? $_SERVER['APPLICATION_ENV'] : 'PROD'));
/**
* Read the configuration
*/
$config = include APP_PATH . "/app/config/" . strtolower(APPLICATION_ENV) . ".config.php";
/**
* Read auto-loader
*/
include APP_PATH . "/app/config/loader.php";
/**
* Read services
*/
include APP_PATH . "/app/config/services.php";
/**
* Handle the request
*/
$application = new \Phalcon\Mvc\Application($di);
echo $application->handle()->getContent();
If I put a var_dump at the begin of method beforeExecuteRoute, I don't see the result of var_dump.
Have you an idea?
Thanks
probably you forward to something that can't be found. Try to rename show404 to showNotFound, you can inspect the $dispatcher->getControllerName() and getActionName() during the afterExecuteRoute event to see why your handler or action can never be found
public function showNotFoundAction()
{
$this->view->setLayout('login');
$this->response->setStatusCode(404, "Not Found");
$this->view->pick('index/404');
}
And
$dispatcher->forward(array(
'controller' => 'index',
'action' => 'showNotFound'
));
I'm using Guzzle to make tests on the API i'm working on in Symfony2.
I've been watching the knpUniversity series on Rest, and i have trouble updating the part where i should be able to use the app_test.php instead of app.php.
In the series, they use Guzzle v5, but in v6 there are major changes with PSR7 use
In the tutorial, to permit the use of another uri ending with other than app.php, they use :
use GuzzleHttp\Event\BeforeEvent;
...
class ApiTestCase extends KernelTestCase
{
...
public static function setUpBeforeClass()
{
$baseUrl = getenv('TEST_BASE_URL');
self::$staticClient = new Client([
'base_url' => $baseUrl,
'defaults' => [
'exceptions' => false
]
]);
...
// guaranteeing that /app_test.php is prefixed to all URLs
self::$staticClient->getEmitter()
->on('before', function(BeforeEvent $event) {
$path = $event->getRequest()->getPath();
if (strpos($path, '/api') === 0) {
$event->getRequest()->setPath('/app_test.php'.$path);
}
});
self::bootKernel();
}
But with Guzzle6, there is no setter for the request :
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class ApiTestCase extends KernelTestCase
{
private static $staticClient;
protected $client;
public static function setUpBeforeClass()
{
//defined in phpunit.xml
$baseUri = getenv('TEST_BASE_URI');
//Create a handler stack that has all of the default middlewares attached
$handler = HandlerStack::create();
// guaranteeing that /app_test.php is prefixed to all URLs
$handler->push(Middleware::mapRequest(function (RequestInterface $request) {
$path = $request->getUri()->getPath();
if (strpos($path, '/api') === 0) {
$request->getUri()->setPath('/app_test.php'.$path); // <-- this is not allowed
}
// Notice that we have to return a request object
return $request->withHeader('X-Foo', 'Bar');
}));
// Inject the handler into the client
self::$staticClient = new Client([
'base_uri' => $baseUri.'/app_test.php',
'handler' => $handler,
'defaults' => [
'http_errors' => false
]
]);
//Allows to use service container
self::bootKernel();
}
So how can i change the uri, to use the app_test.php instead of app.php ?
Thanks
===========================
EDIT :
Actually, they give a solution in one of the post of the comment
$handler->push(Middleware::mapRequest(function(RequestInterface $request) {
$path = $request->getUri()->getPath();
if (strpos($path, '/app_test.php') !== 0) {
$path = '/app_test.php' . $path;
}
$uri = $request->getUri()->withPath($path);
return $request->withUri($uri);
}));
Thanks #Cerad
Symfony 2 ERROR: Cannot validate values of type "string" automatically. Please provide a constraint.
I do not understand what constraint and where i have to provide?
I am following example from book "Extending Symfony 2", chapter 4. I try to make custom annotation "ValidateUser" and use it on the Entity User property $phone. I also have "ValidUserListenerCustom" registered as a service, which redirects response of controller action join4Action. This action is annotated with said custom annotation "#ValidateUser("join_event")". This action should add User to the Event only if User has mobile number in his profile.
C:\Bitnami\wampstack-5.5.30-0\sym_prog\star\src\Yoda\UserBundle\Entity\User.php
/**
* #ORM\Column(type="string", length=255, name="phone")
* #Assert\NotBlank(groups={"join_event"})
*/
protected $phone;
C:\Bitnami\wampstack-5.5.30-0\sym_prog\star\src\Yoda\UserBundle\Security\ValidUserListenerCustom.php
<?php
namespace Yoda\UserBundle\Security;
use Doctrine\Common\Annotations\Reader;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class ValidUserListenerCustom
{
private $reader;
private $annotation_name = 'Yoda\UserBundle\Security\Annotation\ValidateUser';
private $router;
private $session;
private $sc;
private $container;
public function __construct(Reader $reader, Router $rou, Session $session, SecurityContext $sc, Container $cont)
{
/** #var AnnotationReader $reader */
$this->reader = $reader;
$this->router = $rou;
$this->session = $session;
$this->sc = $sc; //security.context
$this->container = $cont; //container
}
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
$class_name = get_class($event->getController()[0]);
$method_name = $event->getController()[1];
dump($class_name); // "Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController"
dump($method_name);
$method = new \ReflectionMethod($class_name, $method_name);
dump('method'); dump($method);
// Read the annotation
$annotation = $this->reader->getMethodAnnotation($method, $this->annotation_name);
dump($annotation);//null
if (!is_null($annotation)) {
// Retrieve the validation group from the annotation, and try to
// validate the user
$validation_group = $annotation->getValidationGroup();
dump($validation_group);
$user = $this->container->get('security.token_storage')->getToken()->getUser();
dump($user);
$validator = $this->container->get('validator');
dump($validator);
$errors = $validator->validate($user);
dump($errors);
//original: $errors = $this->validator->validate($user, $validation_group);
if (count($errors)) {
$event->setController(function(){
$this->session->getFlashBag()->add('warning', 'You must fill in your phone number before joining a meetup.');
return new RedirectResponse($this->router->generate(
'user_edit',
array ('id' => '1') ) );
});
}
}
}
}
C:\Bitnami\wampstack-5.5.30-0\sym_prog\star\src\Yoda\UserBundle\Security\Annotation\ValidateUser.php
<?php
namespace Yoda\UserBundle\Security\Annotation;
// Extending Symfony 2
// annotation itself ...\src\Yoda\UserBundle\Security\Annotation\ValidateUSer.php
// used in class ...src\Yoda\UserBundle\Entity\User.php
// readed/analysed by ...src\Yoda\UserBundle\Security\Annotation\AnnotationServices\AnnotationDriver::loadMetadataForClass
/**
* #Annotation
*/
class ValidateUser
{
private $validation_group;
public function __construct(array $parameters)
{
$this->validation_group = $parameters['value'];
}
public function getValidationGroup()
{
return $this->validation_group;
}
}
C:\Bitnami\wampstack-5.5.30-0\sym_prog\star\src\Yoda\UserBundle\Resources\config\services.yml
yoda.user.security.valid_user_custom:
class: Yoda\UserBundle\Security\ValidUserListenerCustom
arguments: [#annotation_reader, #router, #session, #security.context, #service_container]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
Usage of custom annotation "ValidateUser" to check if user, who tries to join the event, has mobile number on his profile.
url: http://127.0.0.1:8000/events/5/join4
C:\Bitnami\wampstack-5.5.30-0\sym_prog\star\src\Yoda\UserBundle\Controller\DefaultController.php
<?php ...
class DefaultController extends Controller
{ ...
/**
* #Route("/events/{event_id}/join4")
* #Template()
* #ValidateUser("join_event")
*/
public function join4Action($event_id) {
//Chapter 4
$reader = $this->get('annotation_reader');
$method = new \ReflectionMethod(get_class($this), 'join4Action');
$annotation_name = 'Yoda\UserBundle\Security\Annotation\ValidateUser';
$annotation = $reader->getMethodAnnotations($method);
//Chapter 1
$em = $this->getDoctrine()->getManager();
$meetup = $em->getRepository('EventBundle:Event')->find($event_id);
$form = $this->createForm(new JoinEventType(), $meetup, array(
'action' => '',
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Join'));
$form->handleRequest($this->get('request'));
//Do not know how to make it to work, chec later
//$user = $this->get('security.context')->getToken()->getUser();
$user = $em->getRepository('UserBundle:User')->find('1');
if ($form->isValid()) {
$meetup->addAttendee($user);
$this->get('event_dispatcher')->dispatch(MeetupEvents::MEETUP_JOIN, new MeetupEvent($user, $meetup));
$em->flush();
}
$form = $form->createView();
return compact('meetup', 'user', 'form');
}