Laravel Redirect::action() fallback? - php

As the documentation says the function Redirect::action() receives a string which is separated into 2 parts by the symbol #
The controller name
The method name
e.g. Redirect::action('MyController#myFunction')
I've recently tried to give the function an input: Redirect::action('someRouteName') and see what's gonna happen. Surprisingly it didn't return with an error but actually made the link just as if I was using the Redirect::route() function (I had a route named as someRouteName).
Does the function Redirect::action() falls back to Redirect::route() if the value it gets is invalid? Couldn't find any source that says that.

Yes, it does. Some insight on it can be seen in sources.
https://github.com/laravel/framework/blob/master/src/Illuminate/Routing/UrlGenerator.php#L455
/**
* Get the URL to a controller action.
*
* #param string $action
* #param mixed $parameters
* #param bool $absolute
* #return string
*/
public function action($action, $parameters = array(), $absolute = true)
{
return $this->route($action, $parameters, $absolute, $this->routes->getByAction($action));
}

Related

how the Laravel "Storage::download()" method works under the hood?

I can't see this method in facade and in related to this facade class. Can anyone tell me how this "magic" actually works or at least provide some links with explanation?
As per laravel source code that method comes from Symfony component and it creates a streamed download response for a given file.
/**
* Create a streamed download response for a given file.
*
* #param string $path
* #param string|null $name
* #param array|null $headers
* #return \Symfony\Component\HttpFoundation\StreamedResponse
*/
public function download($path, $name = null, array $headers = [])
{
return $this->response($path, $name, $headers, 'attachment');
}
ref:https://github.com/laravel/framework/blob/5398fbbbf81ed842cf0430b278f07eb0f869cf8f/src/Illuminate/Filesystem/FilesystemAdapter.php#L205

method not calling laravel 5.1 to laravel 8.* upgrade

I need some clarification with dynamic controller method
i upgrading the laravel 5.1 to 8.*, all is done, but only one bug,
my url is admin/admin-profile in 5.1 is working fine, but laravel 8 is not working 404 page error is showing.
this url will call method getAdminProfile(){ } but is not calling.
if this functionality is not available in laravel 8, then how can i manage this, if single url i will create route, but my application have more than 100 url like this, so please help me to solve this...
i was check this issues by compare all file both laravel 5.1 and laravel 8
missing one file to capture the like this problem from ControllerInspector from routing folder.
so please help to solve this..
i can't write each method in web.php
Route::controller('admin', 'AdminController');
class AdminController extends BaseController {
public function getIndex()
{
//
}
public function getAdminProfile()
{
//
}
public function anyLogin()
{
//
}
}
Resource Controller
If Resource Controller can handle your need so use that:
Documentation: https://laravel.com/docs/8.x/controllers#resource-controllers
and it's like below:
Routing:
use App\Http\Controllers\PhotoController;
Route::resource('photos', PhotoController::class);
----------------
If Resource Controller is not what you want:
you can get url and transfer url to controller function, for example:
router file getting any url after admin\
Route::prefix('admin')->group(function () {
Route::get('/{my_url?}', [AdminControlle:class, 'handle'])->where('my_url', '(.*)');
});
AdminController
public function handle(){
// get url segments after admin/ - if url is like your_domain.com/admin/...
$segments = array_slice(request()->segments(), 1);
// Translate array of segments to function name - implement by you
$functionName='';
// calling function with knowing its name
$functionName() // or can use call_user_func($functionName);
}
*Note: be aware that this dynamic route handling doesn't provide a solution for dynamic handling of http methods (post, get, patch, ...).
in this example i used GET method.
I just add below code in router.php
/**
* Register an array of controllers with wildcard routing.
*
* #param array $controllers
* #return void
*
* #deprecated since version 5.1.
/
public function controllers(array $controllers)
{
foreach ($controllers as $uri => $controller) {
$this->controller($uri, $controller);
}
}
/*
* Prepend the last group uses onto the use clause.
*
* #param string $uses
* #return string
*/
protected function prependGroupUses($uses)
{
$group = end($this->groupStack);
return isset($group['namespace']) && strpos($uses, '\\') !== 0 ? $group['namespace'].'\\'.$uses : $uses;
}
/**
* Route a controller to a URI with wildcard routing.
*
* #param string $uri
* #param string $controller
* #param array $names
* #return void
*
* #deprecated since version 5.1.
*/
public function controller($uri, $controller, $names = [])
{
$prepended = $controller;
// First, we will check to see if a controller prefix has been registered in
// the route group. If it has, we will need to prefix it before trying to
// reflect into the class instance and pull out the method for routing.
if (! empty($this->groupStack)) {
$prepended = $this->prependGroupUses($controller);
}
$routable = (new ControllerInspector)
->getRoutable($prepended, $uri);
// When a controller is routed using this method, we use Reflection to parse
// out all of the routable methods for the controller, then register each
// route explicitly for the developers, so reverse routing is possible.
// print_r($routable);
foreach ($routable as $method => $routes) {
foreach ($routes as $route) {
$this->registerInspected($route, $controller, $method, $names);
}
}
$this->addFallthroughRoute($controller, $uri);
}
/**
* Register an inspected controller route.
*
* #param array $route
* #param string $controller
* #param string $method
* #param array $names
* #return void
*
* #deprecated since version 5.1.
*/
protected function registerInspected($route, $controller, $method, &$names)
{
$action = ['uses' => $controller.'#'.$method];
// If a given controller method has been named, we will assign the name to the
// controller action array, which provides for a short-cut to method naming
// so you don't have to define an individual route for these controllers.
$action['as'] = Arr::get($names, $method);
$this->{$route['verb']}($route['uri'], $action);
}
/**
* Add a fallthrough route for a controller.
*
* #param string $controller
* #param string $uri
* #return void
*
* #deprecated since version 5.1.
*/
protected function addFallthroughRoute($controller, $uri)
{
$missing = $this->any($uri.'/{_missing}', $controller.'#missingMethod');
$missing->where('_missing', '(.*)');
}
Now is working normally

How to access variables in Helper in CakePHP 3

How can I access the variables which are set to the view in CakePHP 3 in a Helper? I did not find anything in the documentation.
In CakePHP 2.x this used to work:
$this->_View->viewVars['foo'];
Reading the API helps.
655: /**
656: * Returns the contents of the given View variable.
657: *
658: * #param string $var The view var you want the contents of.
659: * #param mixed $default The default/fallback content of $var.
660: * #return mixed The content of the named var if its set, otherwise $default.
661: */
662: public function get($var, $default = null)
663: {
664: if (!isset($this->viewVars[$var])) {
665: return $default;
666: }
667:
668: return $this->viewVars[$var];
669: }

Laravel - unit testing

Hi i am trying to set a a test to test my database calls. I want to pass a variables in url but cant seem to get it to work.
I wanted to do this
public function testDb()
{
$response = $this->call('GET', '/searchAvailability?keyword=test product');
$content = $response->getContent();
$this->assertEquals('[{"name":"test product"}]',$content );
}
But i keep getting "Undefined variable : keyword" when i try. It works in the browser just not when i run phpunit. Anyone got any ideas on why this is not working thanks.
The answer here is you need to specify the parameters differently in your call method:
$this->call('GET', '/searchAvailability', array('keyword' => 'test product'));
Below is the implementation of Illuminate\Foundation\Testing\TestCase::call method:
/**
* Call the given URI and return the Response.
*
* #param string $method
* #param string $uri
* #param array $parameters
* #param array $files
* #param array $server
* #param string $content
* #param bool $changeHistory
* #return \Illuminate\Http\Response
*/
public function call()
{
call_user_func_array(array($this->client, 'request'), func_get_args());
return $this->client->getResponse();
}

PHPDoc: #return void necessary?

Is it really necessary do something like this:
/**
* ...
*
* #return void
*/
I have quite a few methods that don't have a return value, and it seems really redundant to put something like this in the comment. Would it be considered bad form to leave it out?
If it makes it clear for the documentation, then leave it in, but it isn't strictly necessary. It's an entirely subjective decision.
Personally, I would leave it out.
EDIT
I stand corrected. After a little googling, the wikipedia page says:
#return [type description] This tag should not be used for constructors or methods defined with a void return type.
The phpdoc.org website says:
#return datatype description
#return datatype1|datatype2 description
The #return tag is used to document the return value of functions or methods. #returns is an alias for #return to support tag formats of other automatic documentors
The datatype should be a valid PHP type (int, string, bool, etc), a class name for the type of object returned, or simply "mixed". If you want to explicitly show multiple possible return types, list them pipe-delimited without spaces (e.g. "#return int|string"). If a class name is used as the datatype in the #return tag, phpDocumentor will automatically create a link to that class's documentation. In addition, if a function returns multiple possible values, separate them using the | character, and phpDocumentor will parse out any class names in the return value. phpDocumentor will display the optional description unmodified.
Sooo... Based on that, I would say leave out the void. It's non-standard, at least.
According to phpDocumentor, #return void is valid:
http://www.phpdoc.org/docs/latest/guides/types.html#keywords
...
this type is commonly only used when defining the return type of
a method or function. The basic definition is that the element
indicated with this type does not contain a value and the user should
not rely on any retrieved value.
For example:
/**
* #return void
*/
function outputHello()
{
echo 'Hello world';
}
In the example above no return statement is specified and thus is the
return value not determined.
Source: http://www.phpdoc.org/docs/latest/for-users/phpdoc/types.html (archived page).
I have to edit my answer because of something I have learned recently.
Using #return void instead of #return null has a very special meaning, consider the following two examples of PHP code.
<?php
/**
* #return void
*/
function return_never() {
echo "foo";
}
/**
* #return null|string
*/
function return_sometimes() {
if ($this->condition()) {
return "foo";
}
}
In the first example PHP will actually return NULL, since PHP always returns NULL. But the returned value is of no use to the caller since it does not say anything about what the function did. IDEs can use the documented information of #return void to indicate the developer that a return values is used which serves no purpose.
<?php
$foo1 = return_never();
$foo2 = return_sometimes();
The first call is senseless since the variable will always contain NULL, the second one might actually contain something. This is becoming even more interesting if we put the function calls into a conditional.
<?php
if (($foo1 = return_never())) {
// Dead code
var_dump($foo1);
}
if (($foo2 = return_sometimes())) {
var_dump($foo2);
}
As you can see, #return void has its use cases and should be used if applicable.
Also note that it is going to be a part of the upcoming PHP PSR-5 standard.[1]
[1] http://www.php-fig.org/psr/
As of php 7.1, void is a valid return type and can be enforced on a function.
I would always add it on the docblock.
Another benefit of writing it, is to differentiate the void methods from the methods that may return anything but don't have a #return entry on the docblock by negligence.
Here is how I understand and use PhpDocumentor annotations:
<?php
/**
* This method always returns string.
* #return string
*/
public function useCase1()
{
return 'foo';
}
/**
* This method returns 2 data types so list them both using pipeline separator.
* #return string|false
*/
public function useCase2()
{
if ($this->foo === 1) {
return 'foo';
}
return false;
}
/**
* This method performs some operation and does not return anything so no return
* annotation is needed.
*/
public function useCase3()
{
$this->doOperation();
$this->doAnotherOperation();
}
/**
* If condition passes method returns void. If condition does not pass it returns
* nothing so I think that specifying the return annotation with void is in space. :)
* #return void
*/
public function useCase4()
{
if ($this->foo === 1) {
$this->doOperation();
return;
}
$this->doAnotherOperation();
}
Personally, I think the big thing missing from this is that documenting a function returns at all is important. Currently standards dont have any documentation for functions that never return....hence a return void is way of saying yes this function does actually return.
Consider this code block
<?php
/**
* #return void
*/
function return_void() {
echo "foo";
}
/**
* #return null|string
*/
function return_sometimes() {
if ($this->condition()) {
return "foo";
}
}
/**
* This function actually doesnt return at all - it kills the script
**/
function noreturn() {
//do somthing then
die(); //or exit()
}
Clearly the use of #return at least indicates the function does return

Categories