How can I access database inside zend framework 2 plugin - doctrine-orm

I need to access database inside zend framework2 plugin. I have to create ACL using database and for this purpose I need to access database inside plugin.
Here is my module.config.php
return array(
// added for Acl ###################################
'controller_plugins' => array(
'invokables' => array(
'MyAclPlugin' => 'MyAcl\Controller\Plugin\MyAclPlugin',
)
),
// end: added for Acl ###################################
);
Here is my module.php
namespace MyAcl;
use Zend\ModuleManager\ModuleManager; // added for module specific layouts. ericp
// added for Acl ###################################
use Zend\Mvc\MvcEvent,
Zend\ModuleManager\Feature\AutoloaderProviderInterface,
Zend\ModuleManager\Feature\ConfigProviderInterface;
// end: added for Acl ###################################
//class Module
class Module {
public function getConfig() {
return include __DIR__ . '/config/module.config.php';
}
// added for Acl ###################################
public function onBootstrap(MvcEvent $e) {
$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach('route', array($this, 'loadConfiguration'), 2);
//you can attach other function need here...
}
public function loadConfiguration(MvcEvent $e) {
$application = $e->getApplication();
$sm = $application->getServiceManager();
$sharedManager = $application->getEventManager()->getSharedManager();
$router = $sm->get('router');
$request = $sm->get('request');
$matchedRoute = $router->match($request);
if (null !== $matchedRoute) {
$sharedManager->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) use ($sm) {
$sm->get('ControllerPluginManager')->get('MyAclPlugin')
->doAuthorization($e); //pass to the plugin...
}, 2
);
}
}
// end: added for Acl ###################################
/*
* // added init() func for module specific layouts. ericp
* http://blog.evan.pro/module-specific-layouts-in-zend-framework-2
*/
public function init(ModuleManager $moduleManager) {
$sharedEvents = $moduleManager->getEventManager()->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
// This event will only be fired when an ActionController under the MyModule namespace is dispatched.
$controller = $e->getTarget();
//$controller->layout('layout/zfcommons'); // points to module/Album/view/layout/album.phtml
}, 100);
}
public function getAutoloaderConfig() {
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
And my plugin MyAclPlugin.php
I need to access some table (role, resource) from plugin, so that I can configure this resource allocation using a UI. Is there anyway I can access database from plugin. Please let me know the process.
namespace MyAcl\Controller\Plugin;
use Zend\Mvc\Controller\Plugin\AbstractPlugin,
Zend\Session\Container as SessionContainer,
Zend\Permissions\Acl\Acl,
Zend\Permissions\Acl\Role\GenericRole as Role,
Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Zend\View\Model\JsonModel;
use DataSource\Model\AgentModel;
use DataSource\Model\OfficeModel;
use DataSource\Model\UserModel;
class MyAclPlugin extends AbstractPlugin{
protected $constants;
protected $userModel;
protected $agentModel;
protected $user;
protected $sesscontainer;
private function getSessContainer() {
if (!$this->sesscontainer) {
$this->sesscontainer = new SessionContainer('zftutorial');
}
return $this->sesscontainer;
}
public function doAuthorization($e) {
$acl = new Acl();
$acl->deny();
//$this->createService();
############################# ROLES ####################################
$acl->addRole(new Role('anonymous'));
$acl->addRole(new Role('crm'), 'anonymous');
$acl->addRole(new Role('agent'), 'crm');
$acl->addRole(new Role('admin'), 'agent');
$acl->addRole(new Role('superAdmin'), 'admin');
############################ End ROLES #################################
########################### RESOURCES #################################
//------------------------- Front End Resources ------------------------
$acl->addResource('application');
//------------------------- Admin Template Resources -------------------
$acl->addResource('admin');
$acl->addResource('ta-authentication');
$acl->addResource('ta-home');
$acl->addResource('ta-lead');
$acl->addResource('ta-listing');
$acl->addResource('ta-website');
$acl->addResource('ta-craigslist');
$acl->addResource('ta-configuration');
$acl->addResource('ta-single-property-website');
$acl->addResource('ta-open-house-schedule');
$acl->addResource('ta-social-media');
$acl->addResource('ta-office');
$acl->addResource('ta-agent');
$acl->addResource('ta-blog');
//------------------------- Rest API Resources -------------------------
//
// everything sould be protected except login
//only anonymous user privileges
//only crm user privileges + anonymous user privileges
$acl->addResource('admin-rest-lead');
$acl->addResource('admin-rest-lead-event');
$acl->addResource('admin-rest-lead-task');
$acl->addResource('admin-rest-lead-document');
$acl->addResource('admin-rest-lead-group');
$acl->addResource('admin-rest-notification');
########################### Resources ##################################
########################### Intagent PERMISSIONS #######################
// $acl->allow('role', 'resource', 'controller:action');
//--------------------frontend permission-------------------------------
//--------------------template permission-------------------------------
$acl->allow('anonymous', 'application');
$acl->allow('anonymous', 'admin', 'index:index');
$acl->allow('anonymous', 'admin', 'authentication:login');
$acl->allow('crm', 'admin', 'lead:index');
$acl->allow('crm', 'admin', 'lead:form');
$acl->allow('crm', 'admin', 'lead:group');
$acl->allow('crm', 'admin', 'lead:event');
$acl->allow('crm', 'admin', 'lead:task');
$acl->allow('crm', 'admin', 'lead:task-category');
$acl->allow('crm', 'admin', 'lead:document');
$acl->allow('crm', 'admin', 'configuration:help');
$acl->allow('crm', 'admin', 'configuration:notification');
//---------------------admin resources permission-----------------------
//only crm user privileges + anonymous user privileges
$acl->allow('crm', 'admin-rest-lead');
$acl->allow('crm', 'admin-rest-lead-event');
$acl->allow('crm', 'admin-rest-lead-task');
$acl->allow('crm', 'admin-rest-lead-document');
$acl->allow('crm', 'admin-rest-lead-group');
$acl->allow('crm', 'admin-rest-notification');
//only agent user privileges
$acl->allow('agent', 'admin-rest-authentication');
$acl->allow('agent', 'admin-rest-help');
$acl->allow('agent', 'admin-rest-utility');
$acl->allow('agent', 'admin-rest-blog');
//only admin user privileges
$acl->allow('admin', 'admin-rest-configuration');
$acl->allow('admin', 'admin-rest-configuration-email');
$acl->allow('admin', 'admin-rest-configuration-general');
$acl->allow('admin', 'admin-rest-configuration-social-media');
$acl->allow('admin', 'admin-rest-configuration-user');
$acl->allow('admin', 'admin-rest-website');
$acl->allow('admin', 'admin-rest-template');
$acl->allow('admin', 'admin-rest-email-type');
$acl->allow('admin', 'admin-rest-listing');
$acl->allow('admin', 'admin-rest-user');
$acl->allow('admin', 'admin-rest-single-property-website');
$acl->allow('admin', 'admin-rest-open-house-schedule');
$acl->allow('admin', 'admin-rest-office');
$acl->allow('admin', 'admin-rest-agent');
//only super admin privileges
$acl->allow('superAdmin', 'admin-rest-country');
$acl->allow('superAdmin', 'admin-rest-state');
$acl->allow('superAdmin', 'admin-rest-currency');
$acl->allow('superAdmin', 'admin-rest-timezone');
$acl->allow('superAdmin', 'admin-rest-role');
$acl->allow('superAdmin', 'admin-rest-resource');
####################### End Intagent PERMISSIONS #######################
$controller = $e->getTarget();
$controllerClass = get_class($controller);
$moduleName = strtolower(substr($controllerClass, 0, strpos($controllerClass, '\\')));
$role = (!$this->getSessContainer()->role ) ? 'anonymous' : $this->getSessContainer()->role;
//echo $this->user->getId();
//$role = (!$this->user->getRole() && !$this->user->getRole()->getName()) ? 'crm' : $this->user->getRole()->getName();
$role = "crm";
$routeMatch = $e->getRouteMatch();
$actionName = strtolower($routeMatch->getParam('action', 'not-found')); // get the action name
$controllerName = $routeMatch->getParam('controller', 'not-found'); // get the controller name
$controllerName = explode('\\', $controllerName);
$controllerName = strtolower(array_pop($controllerName));
#################### Check Access ########################
if (!$acl->isAllowed($role, $moduleName, $controllerName . ':' . $actionName)) {
$router = $e->getRouter();
//make a logout operation
echo "Access Problem Role:{$role} is not allowed to Module:{$moduleName} Controller:{$controllerName} Action:{$actionName} " ;
// $url = $router->assemble(array(), array('name' => 'Login/auth')); // assemble a login route
// $url = $router->assemble(array(), array('name' => 'authentication', 'action'=>'login'));
//
// $response = $e->getResponse();
// $response->setStatusCode(302);
// // redirect to login page or other page.
// $response->getHeaders()->addHeaderLine('Location', $url);
//
$e->stopPropagation();
}
}
}
Please let me know how can I do that.

In your "MyAclPlugin" create a method like:
public function setServiceLocator($sl)
{
$this->sl = $sl;
}
Then in your MyAcl module.php create a method:
public function getServiceConfig()
{
return array(
'factories' => array(
'myAclPlugin' => function($sm)
{
$plugin = new Controller\Plugin\MyAclPlugin();
$plugin->setServicelocator($sm);
return $plugin;
},
),
);
}
Then in your MyAclPlugin you could probably do something like:
$dbAdapter = $this->sl->get('Zend\Db\Adapter\Adapter');
Hope this helps

In reference to the previous answer from Peter you could implement the ServiceLocatorAwareInterface in your Plugin, so you can use $this->getServiceocator() in it.
This method should return a class like ControllerPluginManager. From this you must be able to call getService(Manager|Locator) (i'm not sure right now) to get the top-level ServiceManager that knows everything about all ServiceManagers. There you should be able to call get('Zend\Db\Adapter\Adapter').
But some ZF2 maintainer are sure that this technique is bad practise (see Github issue)

Related

Create an admin menu in Opencart 4

In Opencart4 I am creating a new module. Installed the module and working fine from accessing Admin-> extensions -> modules -> module name -> (then edit).
Now I would like to add a new menu item under the "Catalogue" menu in the admin part.
I have done the following
In module's controller I added
$this->load->model('setting/event');
$this->model_setting_event->deleteEventByCode('MY_EVENT');
$this->model_setting_event->addEvent('MY_EVENT', "",'admin/view/common/column_left/before', 'extension/testimonials/module/testimonials/ADDTOADMINMENU');
ADDTOADMINMENU function in the module's controller looks like
public function ADDTOADMINMENU(&$route, &$data){
/**
* Check if current logged in user has permission to access that link
* Replace "extension/module/MY_EXTENSION" with your target path
* This check can very well be ignored/deleted...
**/
echo "Here";
exit;
if ($this->user->hasPermission('access', 'extension/testimonials/module/testimonials')) {
$my_menu_entry = array(
'id' => 'menu-MY_EXTENSION',
'icon' => 'fa-check',
'name' => 'My menu entry',
'href' => $this->url->link('extension/testimonials/module/testimonials', 'user_token=' . $this->session->data['user_token'], true),
'children' => array()
);
$target_menu_id = 'menu-catalog';
$target_submenu_href = $this->url->link('catalog/product', 'user_token=' . $this->session->data['user_token'], true);
$new_menu = array();
foreach( $data['menus'] as &$menu ) {
if( $menu['id'] == $target_menu_id ) {
$new_submenu = array();
foreach( $menu['children'] as $submenu ) {
if( $submenu['href'] == $target_submenu_href ) {
$new_submenu[] = $my_menu_entry;
$new_submenu[] = $submenu;
} else {
$new_submenu[] = $submenu;
}
}
$menu['children'] = $new_submenu;
$new_menu[] = $menu;
} else {
$new_menu[] = $menu;
}
}
$data['menus'] = $new_menu;
}
}
But not even entering in this function. Is the correct way I am following ?
Please guide.
try this:
$this->model_setting_event->addEvent('MY_EVENT', "",'admin/view/common/column_left/before', 'extension/testimonials/module/testimonials/ADDTOADMINMENU');
replace with:
$this->model_setting_event->addEvent('MY_EVENT', "",'admin/view/common/column_left/before', 'extension/testimonials/module/testimonials|ADDTOADMINMENU');
I have not checked, but OC have changed they framework a bit.
Solution :
Replace
$this->model_setting_event->addEvent('MY_EVENT', "",'admin/view/common/column_left/before', 'extension/testimonials/module/testimonials/ADDTOADMINMENU');
With
$dataEvent = [
'code' => 'MY_EVENT',
'description' => '',
'trigger' => 'admin/view/common/column_left/before',
'action' => 'extension/testimonials/module/testimonials|ADDTOADMINMENU',
'status' => true,
'sort_order' => 0,
];
if (version_compare(VERSION, '4.0.1.0', '>=')) {
$this->model_setting_event->addEvent($dataEvent);
} elseif (version_compare(VERSION, '4.0.0.0', '>=')) {
$this->model_setting_event->addEvent($dataEvent['code'], $dataEvent['description'], $dataEvent['trigger'], $dataEvent['action'], $dataEvent['status'], $dataEvent['sort_order']);
}else {
/* compatibility Opencart 3 */
$dataEvent['trigger']=str_replace("|","/",$dataEvent['trigger']);
$this->model_setting_event->addEvent($dataEvent['code'], $dataEvent['trigger'], $dataEvent['action'], $dataEvent['status'], $dataEvent['sort_order']);
}
Now you can use your code to update also Admin menu on Opencart 3

CognitoIdentityClient - 404 not found in iam/security-credentials

I want to register an AWS Cognito Identity using getOpenIdTokenForDeveloperIdentity.
Below are my codes written in CodeIgniter framework:
Awscognitoauth.php
<?php
// <MYPROJECT>/application/controllers/Awscognitoauth.php
defined('BASEPATH') or exit('No direct script access allowed');
class Awscognitoauth extends CI_Controller {
function getOpenId($userId) {
$this->load->library('awsauth');
return $this->awsauth->identity($userId);
}
}
Awsauth.php
<?php
// <MY PROJECT>/application/libraries/Awsauth.php
defined('BASEPATH') or exit('No direct script access allowed');
require_once APPPATH . "third_party/aws/aws-autoloader.php";
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
class Awsauth {
public function identity($userId) {
$region = '<my region>';
$key = '<my key>';
$secret = '<my secret>';
$version = 'latest';
$client = CognitoIdentityClient::factory(array('region' => $region, 'key' => $key, 'secret' => $secret, 'version' => $version));
$poolId = '<my pool Id>'; // formatted: "<region>:<UUID>"
$domain = '<my reversed company domain>'; // com.<company...>...
return $client->GetOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $poolId, 'Logins' => array($domain => $userId))); // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html
}
}
In safari, I call the controller Awscognitoauth and get the following error:
I double-checked my user's role here:
It is AdministratorAccess
Access key does match with the key in my code
What could cause this 404 Not Found response? I thought that my user has AdministratorAccess and I can access any resource. Do I miss something?
oh shoot!
I just found out that the $key and $secret must be wrapped in credentials.
So, the final code for Awsauth.php is:
<?php
// <MY PROJECT>/iot.kooltechs.com/application/libraries
defined('BASEPATH') or exit('No direct script access allowed');
require_once APPPATH . "third_party/aws/aws-autoloader.php";
use Aws\CognitoIdentity\CognitoIdentityClient;
use Aws\Sts\StsClient;
class Awsauth {
public function identity($userId) {
$region = '<my region>';
$key = '<my key>';
$secret = '<my secret>';
$version = 'latest';
$config = [
'version' => $version,
'region' => $region,
'credentials' => [
'key' => $key,
'secret' => $secret
]
];
$client = CognitoIdentityClient::factory($config);
$poolId = '<my pool Id>'; // formatted: "<region>:<UUID>"
$domain = '<my reversed company domain>'; // com.<company...>...
return $client->GetOpenIdTokenForDeveloperIdentity(array('IdentityPoolId' => $poolId, 'Logins' => array($domain => $userId)));
}
}
Regards,

facebook graph API does not return event

I am trying to use graph API call to return events of a user who logged in to my app. However , $event is null all the time although I have created bunch of events myself, could anyone help?
Here is my code from login to the event api call:
require_once('AppInfo.php');
// Enforce https on production
if (substr(AppInfo::getUrl(), 0, 8) != 'https://' && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
// This provides access to helper functions defined in 'utils.php'
require_once('utils.php');
require_once('sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
'sharedSession' => true,
'trustForwarded' => true,
));
$user_id = $facebook->getUser();
if ($user_id) {
try {
// Fetch the viewer's basic information
$basic = $facebook->api('/me');
} catch (FacebookApiException $e) {
// If the call fails we check if we still have a user. The user will be
// cleared if the error is because of an invalid accesstoken
if (!$facebook->getUser()) {
header('Location: '. AppInfo::getUrl($_SERVER['REQUEST_URI']));
exit();
}
}
// This fetches some things that you like . 'limit=*" only returns * values.
// To see the format of the data you are retrieving, use the "Graph API
// Explorer" which is at https://developers.facebook.com/tools/explorer/
$likes = idx($facebook->api('/me/likes?limit=4'), 'data', array());
// This fetches 4 of your friends.
$friends = idx($facebook->api('/me/friends?limit=4'), 'data', array());
// And this returns 16 of your photos.
$photos = idx($facebook->api('/me/photos?limit=16'), 'data', array());
// Fetch the event information
// $events = idx($facebook->api('/me/events?limit=5'), 'data', array());
$events = $facebook->api('/me/events','GET');
print("11111");
if($events == null) print("empty");
I see no login code in your example, are you sure the user is logged in? See PHP SDK "Usage": https://github.com/facebook/facebook-php-sdk
Anyway, i just tried this in one of my projects, i get the user events with the same call but i need the permission "user_events":
$facebook->getLoginUrl(array('scope' => 'user_events'));

Silex and Doctrine ORM

I am trying to use Silex together with Doctrine ORM (not just DBAL) but I am unable to get the configuration correct.
composer.json
{
"require": {
"silex/silex": "1.0.*#dev",
"symfony/monolog-bridge": "~2.1",
"symfony/twig-bridge": "~2.1",
"symfony/form": "~2.1",
"symfony/yaml": "2.2.*",
"symfony/form": "2.2.*",
"symfony/translation": "~2.1",
"symfony/config": "2.2.*",
"dflydev/doctrine-orm-service-provider": "1.0.*#dev"
},
"autoload": {
"psr-0": {
"Entities": "src/"
}
}
}
bootstrap.php located in my project root folder
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
require_once __DIR__ ."/vendor/autoload.php";
$isDevMode = true;
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src/Entities"), $isDevMode);
$params = array(
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/development.sqlite',
);
$entityManager = EntityManager::create($params, $config);
cli-config.php also located inside the root folder
require_once "bootstrap.php";
$helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($entityManager->getConnection()),
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($entityManager)
));
Customer.php entity located inside src/Entities
/**
* #Entity #Table(name="customers")
**/
class Customer {
/** #Id #Column(type="integer") #GeneratedValue **/
protected $id;
/** #Column(type="string") **/
protected $name;
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
}
public function getId() {
return $this->id;
}
}
I am able to run commands like php vendor/bin/doctrine orm:schema-tool:create and have it generate a table called customs just as it should. But how do I load that entity inside my Silex application
Here is my index.php
require_once __DIR__.'/../vendor/autoload.php';
$app = new Silex\Application();
use Symfony\Component\Yaml\Yaml;
$app['config'] = function () {
$config = Yaml::parse(__DIR__ .'/../config.yml');
return $config;
};
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'dns.options' => $app['config']['database']['development']
));
$app->register(new Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider, array(
'orm.em.options' => array(
'mappings' => array(
array(
'type' => 'annotation',
'path' => __DIR__ .'/src/Entities',
)
)
),
));
$app->get('/', function () use ($app) {
$customer = $app['orm.em']->getRepository('Customer');
return '<pre>'. $customer->getName() .'</pre>';
});
The result when loading the localhost inside my browser
Warning: class_parents() [function.class-parents]: Class Customer does not exist and could not be loaded in /Users/me/Documents/project/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/RuntimeReflectionService.php on line 40
UPDATE
I am not sure this is the correct way to solve this issue, but by using the following approach the problem got solved and I can now use my entities in Silex
$app['em'] = function ($app) {
$config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src/Entities"), true);
$params = array(
'driver' => 'pdo_sqlite',
'path' => __DIR__ . '/../development.sqlite',
);
$entityManager = EntityManager::create($params, $config);
return $entityManager;
};
I used the dependency approach because that way I can use $app['config'] to store DB information and other environment specific configurations.
$customer = new \Entities\Customer();
$customer->setName('Multi Corp '. uniqid());
$app['em']->persist($customer);
$app['em']->flush();
I presume your doctrine Entity mappings reside under "/src/Entities" in the namespace \Entities. With your autoloader directive they should be accessible as \Entities\MyMappingCls.
Your problem seems to be that you don't give the fq-name of the mapping class when getting the repository. You need to give a string that can be resolved by the autoloader. Please try:
$app['orm.em']->getRepository('Entities\Customer');
You can also try to run orm:generate-proxies as they are only generated on the fly in debug mode (not so sure this is relevant).
hth

Symfony2 - Tests with FOSUserBundle

i would write a test for Symfony2 with FOSUserBundle.
At the moment i tried some ways and no one works.
I need a function like "createAuthClient".
Here is my basic class.
I post it because you could understand my problem better.
<?php
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;
class WebTestMain extends WebTestCase
{
protected static $container;
static protected function createClient(array $options = array(), array $server = array())
{
$client = parent::createClient($options, $server);
self::$container = self::$kernel->getContainer();
return $client;
}
static function createAuthClient(array $options = array(), array $server = array())
{
// see lines below with my tries
}
}
First try:
if(static::$kernel === null)
{
static::$kernel = static::createKernel($options);
static::$kernel->boot();
}
if(static::$container === null)
{
self::$container = self::$kernel->getContainer();
}
$parameters = self::$container->getParameter('test');
$server = array_merge(array('HTTP_HOST' => $parameters['host'], 'HTTP_USER_AGENT' => $parameters['useragent']), $server);
$client = self::createClient($options, $server);
$userProvider = self::$container->get('fos_user.user_manager');
$user = $userProvider->findUserBy(array('id' => 1));
$client->getCookieJar()->set(new Cookie('MOCKSESSID', true));
$session = self::$kernel->getContainer()->get('session');
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$client->getContainer()->get('security.context')->setToken($token);
$session->set('_security_main', serialize($token));
return $client;
Then i searched and searched...
My second try.
if(static::$kernel === null)
{
static::$kernel = static::createKernel($options);
static::$kernel->boot();
}
if(static::$container === null)
{
self::$container = self::$kernel->getContainer();
}
$parameters = self::$container->getParameter('test');
$server = array_merge(
array(
'HTTP_HOST' => $parameters['host'],
'HTTP_USER_AGENT' => $parameters['useragent'],
'PHP_AUTH_USER' => 'admin',
'PHP_AUTH_PW' => 'admin'
),
$server
);
$client = static::createClient(array(), array());
$client->followRedirects();
return $client;
And here is my last try before i post this question...
$client = self::createClient($options, $server);
$parameters = self::$container->getParameter('test');
$server = array_merge(
array(
'HTTP_HOST' => $parameters['host'],
'HTTP_USER_AGENT' => $parameters['useragent']
),
$server
);
$client->setServerParameters($server);
$usermanager = self::$container->get('fos_user.user_manager');
$testuser = $usermanager->createUser();
$testuser->setUsername('test');
$testuser->setEmail('test#mail.org');
$testuser->setPlainPassword('test');
$usermanager->updateUser($testuser);
return $client;
Thank you in Advance.
The best way I have found to test with an authenticated user is to just visit your login page and submit the form with user name and password you have loaded from a fixture. This may seem slow and cumbersome but will test what the user will actually do. You can even create your own method to make using it quick and easy.
public function doLogin($username, $password) {
$crawler = $this->client->request('GET', '/login');
$form = $crawler->selectButton('_submit')->form(array(
'_username' => $username,
'_password' => $password,
));
$this->client->submit($form);
$this->assertTrue($this->client->getResponse()->isRedirect());
$crawler = $this->client->followRedirect();
}
Create an AbstractControllerTest and create an authorized client on setUp() as follow:
<?php
// ...
use Symfony\Component\BrowserKit\Cookie;
abstract class AbstractControllerTest extends WebTestCase
{
/**
* #var Client
*/
protected $client = null;
public function setUp()
{
$this->client = $this->createAuthorizedClient();
}
/**
* #return Client
*/
protected function createAuthorizedClient()
{
$client = static::createClient();
$container = $client->getContainer();
$session = $container->get('session');
/** #var $userManager \FOS\UserBundle\Doctrine\UserManager */
$userManager = $container->get('fos_user.user_manager');
/** #var $loginManager \FOS\UserBundle\Security\LoginManager */
$loginManager = $container->get('fos_user.security.login_manager');
$firewallName = $container->getParameter('fos_user.firewall_name');
$user = $userManager->findUserBy(array('username' => 'REPLACE_WITH_YOUR_TEST_USERNAME'));
$loginManager->loginUser($firewallName, $user);
// save the login token into the session and put it in a cookie
$container->get('session')->set('_security_' . $firewallName,
serialize($container->get('security.context')->getToken()));
$container->get('session')->save();
$client->getCookieJar()->set(new Cookie($session->getName(), $session->getId()));
return $client;
}
}
NOTE: Please, replace the username with your test username.
Then, extends the AbstractControllerTest and use the global $client to make requests as follow:
class ControllerTest extends AbstractControllerTest
{
public function testIndexAction()
{
$crawler = $this->client->request('GET', '/admin/');
$this->assertEquals(
Response::HTTP_OK,
$this->client->getResponse()->getStatusCode()
);
}
}
This method tested and works fine