Routing is not work in Symfony 3.2 - php

I use example from docs.
This is
routing.yml:
app:
resource: '#AppBundle/Controller/'
type: annotation
blog_list:
path: /blog/{page}
defaults: { _controller: AppBundle:Blog:list , page: 1}
requirements:
page: '\d+'
And this controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class BlogController extends Controller
{
/**
* #Route("/blog/{page}", name="blog_list", requirements={"page": "\d+"})
*/
public function listAction($page = 1)
{
$number = mt_rand(0, 100);
return $this->render('lucky/number.html.twig',['number'=>$number]);
}
}
I see errors:
The routing file "/var/www/pars/app/config/routing.yml" contains unsupported keys for "app": "blog_list". Expected one of: "resource", "type", "prefix", "path", "host", "schemes", "methods", "defaults", "requirements", "options", "condition" in /var/www/pars/app/config/routing.yml (which is being imported from "/var/www/pars/app/config/routing_dev.yml").
WHY?

Seems only an indentation problem: the new route should be at the low level:
app:
resource: '#AppBundle/Controller/'
type: annotation
blog_list:
path: /blog/{page}
defaults: { _controller: AppBundle:Blog:list , page: 1}
requirements:
page: '\d+'
Hope this help

Related

Catch-all route in Symfony 3

I have a catch-all fallback route in Symfony2 that I couldn't get to work in Symfony3. I tried this exact syntax (a verbatim copy of my Symfony2 route) and that didn't work.
fallback:
path: /{req}
defaults: { _controller: MyBundle:Default:catchAll }
requirements:
req: ".+"
How can I get this working in Symfony3? (It's literally the only thing holding me back from using Symfony3 and keeping me at v2.8)
This should help you:
route1:
path: /{req}
defaults: { _controller: 'AppBundle:Default:index' }
requirements:
req: ".+"
Where, my controller is called "DefaultController", and I have a function called "indexAction()".
Here is my code for the DefaultController:
class DefaultController extends Controller
{
/**
* #Route("/", name="homepage")
*/
public function indexAction(Request $request)
...
I actually did try what you said in my environment, and it didn't work until I had the right controller settings specified.
EDIT:
For this to work, it was necessary to add the parameter Request $request (with the type hint) to the action's method signature.
I found the current accepted answer almost useful for Symfony 4, so I'm going to add my solution:
This is what I did to get it working in Symfony 4:
Open /src/Controller/DefaultController.php, make sure there is a function called index(){}
It's not required to add the Request $request as first param as some comment suggest.
This is the method that will handle all urls caught by the routes.yaml
Open /config/routes.yaml, add this:
yourRouteNameHere:
path: /{req}
defaults: { _controller: 'App\Controller\DefaultController::index' }
requirements: # the controller --^ the method --^
req: ".*"` # not ".+"
You can also override Exception controller.
# app/config/config.yml
twig:
exception_controller: app.exception_controller:showAction
# app/config/services.yml
services:
app.exception_controller:
class: AppBundle\Controller\ExceptionController
arguments: ['#twig', '%kernel.debug%']
namespace AppBundle\Controller;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class ExceptionController
{
protected $twig;
protected $debug;
public function __construct(\Twig_Environment $twig, $debug)
{
$this->twig = $twig;
$this->debug = $debug;
}
public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null)
{
// some action
return new Response($this->twig->render('error/template.html.twig', [
'status_code' => $exception->getStatusCode()
]
));
}
}

Error configuring a particular provider for my web application

[Symfony\Component\Debug\Exception\ContextErrorException]
Catchable Fatal Error: Argument 2 passed to Symfony\Component\Security\Core\Authentication\Provider\SimpleAuthenticationProvider::__construct() must implement interface Symfony\Component\Security\Core\User\UserProviderInterface, instance of Delivve\WebBundle\Service\WebKeyUsersService given, called in /home/delivve-webservice/app/cache/de_/ap_DevDebugProjectContainer.php on line 4611 and defined
What happens is that I have an api that works, but now I need to make the web service log face or google account, but this error of the above, follow this tutorial to make
http://nyrodev.info/fr/posts/286/Connexions-OAuth-Multiple-avec-Symfony-2-3
And apena in OAuthMembersService.php file includes the useSymfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface; because symfony complained of is not having such imports.
I'm really doubt
I implemented the following classes:
<?php
namespace Delivve\WebBundle\Security;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUser as BaseOAuthUser;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
class WebKeyUserProvider extends BaseOAuthUser {
protected $data;
public function __construct(UserResponseInterface $response) {
parent::__construct($response->getUsername());
$this->data = array(
'provider'=>$response->getResourceOwner()->getName(),
'providerId'=>$response->getUsername()
);
$vars = array(
'nickname',
'realname',
'email',
'profilePicture',
'accessToken',
'refreshToken',
'tokenSecret',
'expiresIn',
);
foreach($vars as $v) {
$fct = 'get'.ucfirst($v);
$this->data[$v] = $response->$fct();
}
}
public function getData() {
return $this->data;
}
/**
* {#inheritDoc}
*/
public function getRoles() {
return array('ROLE_OAUTH_USER');
}
}
<?php
namespace Delivve\WebBundle\Service;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\UserProviderFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Delivve\WebBundle\Security\WebKeyUserProvider;
class WebKeyUsersService implements UserProviderFactoryInterface, OAuthAwareUserProviderInterface {
public function loadUserByUsername($username) {
throw new Exception('loadByUsername not implemented');
}
public function supportsClass($class) {
return $class === "Delivve\\WebBundle\\Security\\WebKeyUserProvider";
}
public function refreshUser(\Symfony\Component\Security\Core\User\UserInterface $user) {
if (!$this->supportsClass(get_class($user))) {
throw new UnsupportedUserException(sprintf('Unsupported user class "%s"', get_class($user)));
}
return $user;
}
public function loadUserByOAuthUserResponse(UserResponseInterface $response) {
return new OAuthUser($response);
}
public function create(ContainerBuilder $container, $id, $config)
{
// TODO: Implement create() method.
}
public function getKey()
{
// TODO: Implement getKey() method.
}
public function addConfiguration(NodeDefinition $builder)
{
// TODO: Implement addConfiguration() method.
}
}
And these are my configurations:
routingSecurityOAuth.yml
hwi_oauth_login:
resource: "#HWIOAuthBundle/Resources/config/routing/login.xml"
prefix: /login
hwi_oauth_redirect:
resource: "#HWIOAuthBundle/Resources/config/routing/redirect.xml"
prefix: /connect
facebook_login:
pattern: /login/check-facebook
google_login:
pattern: /login/check-google
web_target:
pattern: /target
defaults: { _controller: DelivveWebBundle:Security:oauthTarget }
service
services:
web_key_user_provider:
class: Delivve\WebBundle\Service\WebKeyUsersService
security
security:
providers:
web_key_user_provider:
id: web_key_user_provider
firewalls:
web_key:
pattern: ^/web/*
anonymous: ~
provider: web_key_user_provider
oauth:
resource_owners:
facebook: "/web/login/check-facebook"
google: "/web/login/check-google"
# linkedin: "/web/login/check-linkedin"
login_path: /web/login
failure_path: /web/login
check_path: /web/login_check
default_target_path: /web/target
oauth_user_provider:
service: web_key_user_provider
default:
anonymous: ~
access_control:
- { path: ˆ/web/target, roles: ROLE_OAUTH_USER }
- { path: ˆ/web/, roles: IS_AUTHENTICATED_ANONYMOUSLY }
routing
web_key_register:
pattern: /webRegister
defaults: { _controller: DelivveWebBundle:Security:webRegister }
web_key:
resource: "#DelivveWebBundle/Resources/config/routingSecurityOAuth.yml"
prefix: /web/
config
hwi_oauth:
firewall_name: web_key
resource_owners:
facebook:
type: facebook
client_id: %facebook_client_id%
client_secret: %facebook_client_secret%
scope: email
infos_url: "https://graph.facebook.com/me?fields=username,name,email,picture.type(large)"
paths:
email: email
profilepicture: picture.data.url
options:
display: popup
google:
type: google
client_id: %google_client_id%
client_secret: %google_client_secret%
scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"
paths:
email: email
profilepicture: picture

Accessing route path in event listener

ROUTE:
user_lock:
path: /user/lock/{id}
defaults: { _controller: SiteMainBundle:Frontend\Default:userLock }
methods: [GET]
As you know, router above will create a URL like htt://mysite.com/app_dev.php/user/lock/66 so I need to get only /user/lock/66 part of it in event listener below. How can I do it?
I tried $request->getBaseUrl() and $request->getBasePath() didn't give me what I wanted.
YAML
services:
kernel.listener.kernel_controller:
class: Site\MainBundle\EventListener\Controller\KernelController
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
CLASS
<?php
namespace Site\MainBundle\EventListener\Controller;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class KernelController
{
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
$this->writeLog('ROUTE', $request->attributes->get('_route'));
$this->writeLog('CONTROLLER', $request->attributes->get('_controller'));
$this->writeLog('ROUTE PARAMETERS', $request->attributes->get('_route_params'));
$this->writeLog('ROUTE PATH', ??????????????????????????????);
}
}
I think, you are looking for
$request->server->get('PATH_INFO');

Symfony 2.5 "You have requested a non-existent service "siteTest.b"

When run workspace/app_dev.php, no problem. But when I try to run workspace/app.php I get:
"You have requested a non-existent service "siteTest.b"
I dont have the first clue what am I doing wrong.
app/config/config.yml :
imports:
- { resource: parameters.yml }
- { resource: security.yml }
framework:
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
handler_id: ~
fragments: ~
http_method_override: true
src/Site/TestBundle/Resources/config/services.yml:
parameters:
siteTest.aa: Site\TestBundle\Controller\a
services:
siteTest.b:
class: %siteTest.aa%
src/Site/TestBundle/DependencyInjection/SiteTestExtension.php :
namespace Site\TestBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
class SiteTestExtension extends Extension
{
/**
* {#inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('services.yml');
}
}
src/Site/TestBundle/Controller/a.php :
namespace Site\TestBundle\Controller;
class a {
public function printTest() {
var_dump('Test');
exit;
}
}
src/Site/TestBundle/Controller/DefaultController.php:
namespace Site\TestBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class DefaultController extends Controller
{
public function indexAction()
{
$aaa = $this->get('siteTest.b');
exit();
}
}
you might also need to add the code below inside
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: '#TestBundle/Resources/config/services.yml' }
alternatively you can use the cookbook configurations http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class
run command php app/console cache:clear --env=prod to clear your prod cache

SonataAdminBundle cannot import resource

I have follow error when try to enter in admin dashboard:
Cannot import resource "/var/www/autoportal/app/config/." from
"/var/www/autoportal/app/config/routing.yml". (The autoloader expected
class "App\AdminBundle\Admin\AutoAdmin" to be defined in file
"/var/www/autoportal/src/App/AdminBundle/Admin/AutoAdmin.php". The
file was found but the class was not in it, the class name or
namespace probably has a typo.)
My admin class:
namespace App\AdminBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class AutoAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name')
->add('enabled', null, array('required' => false))
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('name')
->add('posts')
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('slug')
->add('enabled')
;
}
}
Service configure:
services:
app_admin.auto:
class: App\AdminBundle\Admin\AutoAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: posts, label: "Auto" }
arguments:
- ~
- 'App\AutoPortalBundle\Entity\Auto'
- 'SonataAdminBundle:CRUD'
calls:
- [ setTranslationDomain, [AppAdminBundle]]
routing file:
app_auto_portal_controller:
resource: "#AppAutoPortalBundle/Controller"
type: annotation
app_auto_portal:
resource: "#AppAutoPortalBundle/Resources/config/routing.yml"
prefix: /
login:
pattern: /login
defaults: { _controller: AppAutoPortalBundle:Security:login }
login_check:
pattern: /login_check
admin:
resource: '#SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
prefix: /admin
_sonata_admin:
resource: .
type: sonata_admin
prefix: /admin

Categories