Testing laravel routes identify method type - laravel

How can I get about a Laravel route if the request is a get or post?
I try to test my laravel routes with the following
public function testRoutes()
{
$app = app();
$routes = $app->routes->getRoutes();
/**
* Test if mynamespace routes are redirected to login page if is not the login page
*/
echo PHP_EOL;
foreach ($routes as $route) {
if(strpos($route->getName(),'mynamespace::' ) !== false ) {
$url = $route->uri;
//$appURL = env('APP_URL') .'/';
$response = $this->get($url);
if((int)$response->status() !== 200 ){
echo $url . ' (FAILED) did not return 200. The response is ' . $response->status();
$this->assertTrue(false);
} else {
echo $url . ' (success ?)';
$this->assertTrue(true);
}
echo PHP_EOL;
}
}
}
but I would like exclude post requests for the moment

As we can see the Route class has a property $methods.
Your solution would look something like:
if (in_array('POST', $route->methods)) continue;
It may be interesting for you to look into the testing provided by Laravel itself. A simple way of testing response testing and much more!
Laravel testing.

Related

How add multiple actions In URL?

How can I add more than one action to a URL? As I described in the title, I want to add more than one action to a URL. How do I do that?
As a further clarification, I define actions for some parts in an HTML file, and by setting an action, I handle the request in the php file!
Example:
example.com/?order=1&price=high
I appreciate your help.
As i ask and get help from my friend, we can use function like this to solve our problem:
function shapeSpace_add_var($url, $key, $value) {
$url = preg_replace('/(.*)(?|&)'. $key .'=[^&]+?(&)(.*)/i', '$1$2$4', $url .'&');
$url = substr($url, 0, -1);
if (strpos($url, '?') === false) {
return ($url .'?'. $key .'='. $value);
} else {
return ($url .'&'. $key .'='. $value);
}
}
example:
$url = 'http://example.com/whatever/?hello=world';
shapeSpace_add_var($url, 'goodbye', 'nightclub');
Result:
http://example.com/whatever/?hello=world&goodbye=nightclub

how to un-substitute paramters in Lumen route

Say if I defined a route GET /user/{user_id}/post/{post_id}. How do I get the un-substitute route in middleware? i.e. if the request is GET /usr/123/post/456, is there a pre-defined function that can get me /user/{user_id}/post/{post_id}?
I am currently using following snippet
$urlParam = $request->route()[2];
if (isset($urlParam) && count($urlParam)) {
$urlPath = substr(str_replace(
array_map(function($item) { return "/" . $item . "/"; }, array_values($urlParam)),
array_map(function($item) { return "/{" . $item . "}/"; }, array_keys($urlParam)),
"/" . $request->path() . "/"), 1, -1);
}
return $urlPath;
but as you can see this is not bug-free, if both user_id & post_id are the same, above snippet will not generate right result.
In Laravel
If you wan to get the same route URI you can use
$request->route()->uri();
This will return user/{user_id}/post/{post_id}
In Lumen
$segments = $request->segments();
foreach ($request->route()[2] as $parameter => $value) {
$segment_index = array_search($value, $request->segments());
$segments[$segment_index] = "{{$parameter}}";
}
$segments = implode('/', $segments);
dd($segments);
And the result will be user/{user_id}/post/{post_id}

Joomla logout with message

I'm trying to modify the
'Token Interceptor' system plugin
by joomunited.com
The original plugin redirects on encountering an invalid token error using register_shutdown_function.
I'm trying to get it to:
Log the user out if they are logged in
Redirect to the login page with the invalid token message
Code:
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect('/index.php', JText::_('JINVALID_TOKEN'), 'warning');
I can successfully log the user out and redirect to the login page but the error message is not being displayed.
How can I retain the message after logging the user out?
i've also tried:
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
but that didn't work either...
The solution I came up with was a variation of Alonzo Turner's 2nd post here.
The plugin redirects to the login page with a parameter passed in the url. The onAfterInitialise event then looks for this parameter and displays a message if it's found.
class PlgSystemTokeninterceptor extends JPlugin
{
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
$app = JFactory::getApplication();
if (($app->isSite() && $this->params->get('use_frontend')) || ($app->isAdmin() && $this->params->get('use_backend')))
{
register_shutdown_function(array($this,'redirectToLogin'));
}
}
public function redirectToLogin()
{
$content = ob_get_contents();
if($content == JText::_('JINVALID_TOKEN') || $content == 'Invalid Token')
{
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect(JURI::base().'index.php?invalid_token=true');
return false;
}
}
function onAfterInitialise()
{
$app = JFactory::getApplication();
$invalid_token = $app->input->get('invalid_token', 'false');
if ($invalid_token == 'true')
{
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
}
return true;
}
}
When you logout you destroy the session so you are not going to have the message any more.
This will get you a message on redirect.
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
//$app->logout();
$app->redirect($this->redirect);
}
This will not because the session is destroyed
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
$app->logout();
$app->redirect($this->redirect);
}
Not tested but
$app->logout()
echo '<div class="">'. JText::_('whatever you want') . '</div>';
$module = JModuleHelper::getModule('login');
$output = JModuleHelper::renderModule($module);
Something like that

precontroller hooks in codeigniter

I am using pre-controller hook codeigniter in my project
Description:
we are using subdomain concept and three templates(theme). eg: My site is xyz.com. this is having one first template.
some business signup with this xyz site. for eg. abc(business). We create abc.xyz.com. abc chooses 2 template. abc.xyz.com in browser need to show 2nd template. It is not showing 2nd template. it is showing only 1st template.
When we clicked any link on the site more than once , then the template 2 is set for abc.xyz.com link.
I am using codeigniter. loaded session, database in autoload files.
I used precontroller hook to check whether the url is xyz or any subdomain abc.xyz.com
In hook i am setting template if the url is subdomain one.
But template is not showing when abc.xyz.com is in browser. when i refresh the url for some clicks or clicked any of the header link some count , it showing the actual template of the business abc.
Please help me to fix this issue or provide me some solution .
<?php
class Subdomain_check extends CI_Controller{
public function __construct(){
parent::__construct();
$this->CI =& get_instance();
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
}
function checking()
{
$subdomain_arr = explode('.', $_SERVER['HTTP_HOST']); //creates the various parts
if($subdomain_arr[0] == 'www')
{
$subdomain_name = $subdomain_arr[1]; //2ND Part
}
else
{
$subdomain_name = $subdomain_arr[0]; // FIRST Part
}
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");
if( $subdomain_name != 'xyz' )
{
$where = array();
$where['subdomain_name'] = $subdomain_name;
$where['status'] = 1;
$this->db->from('subdomain_map');
$this->db->where($where);
$query = $this->db->get();
if($query->num_rows() < 1)
{
header('Location:http://xyz.com/index.php?/error');
}
else
{
$result = $query->row_array();
$this->CI->session->set_userdata('subdomain_id',$result['subdomain_id']);
$this->CI->session->set_userdata('subdomain_name',$result['subdomain_name']);
$org_id = gat_organisationid_using_subdomainid($result['subdomain_id']);
$this->CI->session->set_userdata('organisation_id', $org_id);
if($org_id)
{
$templ_id = get_templid_using_organisationid($org_id);
$org_logo = get_organisation_logo($org_id);
}
if($templ_id){
if($this->session->userdata('pinlogin'))
$this->CI->session->set_userdata('template_set', 4);
else
$this->CI->session->set_userdata('template_set', $templ_id);
}
if($org_logo)
$this->CI->session->set_userdata('org_logo', $org_logo);
}
}
else
{
$this->CI->session->unset_userdata('subdomain_id');
$this->CI->session->unset_userdata('subdomain_name');
if( $this->CI->session->userdata('user_id') && $this->CI->session->userdata('user_category')<=2 )
{
$this->CI->session->unset_userdata('organisation_id');
$this->CI->session->unset_userdata('org_logo');
}
}
}
}
Here is the basic check you need to support custom themes per subdomain
// Gets the current subdomain
$url = 'http://' . $_SERVER['HTTP_HOST'];
$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
// store $host[0], which will contain subdomain or sitename if no subdomain exists
$subdomain = $host[0];
// check for subdomain
if ($subdomain !== 'localhost' OR $subdomain !== 'mysite')
{
// there is a subdomain, lets check that its valid
// simplified get_where using activerecord
$query = $this->db->get_where('subdomain_map', array('subdomain_name' => $subdomain, 'status' => 1));
// num_rows will return 1 if there was a valid subdomain selected
$valid = $query->num_rows() === 1 ? true : false;
if($valid)
{
// set theme, user_data, etc. for subdomain.
}
else
{
// get user out of here with redirect
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/error');
exit();
}
}
Note that when using subdomains with codeigniter, you should set your config > base_url to the following:
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/poasty/poasty-starterkit/';
this will ensure things like site_url() and other CI helpers still work.
Reading through your code may I suggest utilizing more of Codeigniters built-in functionality, for example your __construct function has a lot of un-necessary code:
Original code
public function __construct(){
parent::__construct();
/**
* CI already exists
* since this controller extends CI_controller, there is already and instance of CI available as $this.
$this->CI =& get_instance();
*/
/**
* duplicate check, CI checks if library is loaded
* and will ignore if loaded already
if (!isset($this->CI->session))
{
$this->CI->load->library('session');
}
*/
$this->CI->load->library('session');
}
Optimized for Codeigniter
public function __construct()
{
parent::__construct();
$this->CI->load->library('session');
}
I suggest reading up on the Codeigniter user_guide to better understand what codeigniter can do. #see http://codeigniter.com/user_guide/
I hope you find this helpful!

Session expiring for twitter oAuth

I am using Abraham Williams' oAuth library to update a status. The application does not have a UI (other than the prompt from Twitter for credentials. Instead, the user enters a URL in the browser.
When the URL is called, I get an error: "Could not post Tweet. Error: Reason: 1".
I inserted some test code, and it seems as if the session is getting lost in between transitions: $_SESSION['tweetmsg'] is set on initial call in index.php, but then when the switch to connect.php happens, it seems as if the session is lost. Any ideas?
Following is the source code:
index.php
<?php
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
session_start();
if (empty($_SESSION['access_token'])) {
$_SESSION['tweetmsg'] = create_tweet_text();
print "<script>self.location='./connect.php');</script>";
}
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['access_token']['oauth_token'],
$_SESSION['access_token']['oauth_token_secret']
);
if (!isset($_SESSION['tweetmsg'])) {
exit('No tweet value in session or from form');
}
$tweetmsg = $_SESSION['tweetmsg'];
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
echo 'Tweet Posted: '.$tweetmsg;
}
else {
echo 'Could not post Tweet. Error: '.$httpCode.' Reason: '.
session_destroy();
}
function create_tweet_text () {
return 'this is a test';
}
connect.php
?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK.'callback.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->getAuthorizeURL($request_token);
print "<script>self.location='$url';</script>";
callback.php
<?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
if (
isset($_REQUEST['oauth_token'])
&& $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
echo 'Session expired';
}
else {
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']
);
$_SESSION['access_token'] = $connection->getAccessToken($_REQUEST['oauth_verifier']);
print "<script>self.location='index.php';</script>";
}
Recently Twitter deactivated a number of http urls for oAuth and replaced them with https equivalents. If you can see the URL string http://twitter.com/oauth/request_token in the includes then it means you need to follow https://dev.twitter.com/discussions/10803 and change all the calls to https...

Resources