Skip to content

Core\Http::methodName

Returns the name of an HTTP method as text. Core\Http::methodName takes a case of Core\Http\Method and returns its name in capital letters, the way it is written in a request. Core\Http\Method::Get gives GET, and Core\Http\Method::Delete gives DELETE.

Use it when you need the method as a string. Two common cases are the Allow header of a 405 Method Not Allowed response and a log line. Core\Router::methodsFor and Core\Request::method() return Core\Http\Method cases, so you pass their result to this method.

The method never throws an error. Each of the eight cases has a name.

The examples print the name of every method, build an Allow header, and write the method of the current request into a log line.

Parameters

  • $methodCore\Http\MethodThe method, as a case of Core\Http\Method.

Return value

Returns string. The name in capital letters: GET, HEAD, OPTIONS, TRACE, POST, PUT, PATCH or DELETE.

Examples

The name of each method

<?nvs
// Prints the name of every HTTP method that `Core\Http\Method` has.
// `Core\Reflect\EnumInfo` lists the cases of an enum by name.
Core\Reflect\EnumInfo $info = Core\Reflect\EnumInfo::of(Core\Http\Method::class) as Core\Reflect\EnumInfo;
foreach ($info->cases() as string $case) {
// `valueOf` gives the number of the case. `as Core\Http\Method` converts the number to the case.
Core\Http\Method $method = ($info->valueOf($case) as int) as Core\Http\Method;
// The first line prints `Get is GET`.
echo $case, ' is ', Core\Http::methodName($method), "\n";
}
Output
Get is GET
Head is HEAD
Options is OPTIONS
Trace is TRACE
Post is POST
Put is PUT
Patch is PATCH
Delete is DELETE

An allow header

<?nvs
// Builds the `Allow` header that a `405 Method Not Allowed` response needs.
class Invoices
{
#[Core\Route(path: '/invoices', method: Core\Http\Method::Get)]
#[Core\Access(allow: Core\Audience::Public)]
public function list(): string
{
return 'all invoices';
}
#[Core\Route(path: '/invoices', method: Core\Http\Method::Post)]
#[Core\Access(allow: Core\Audience::Public)]
public function create(): string
{
return 'a new invoice';
}
}
class Allow
{
// Returns the methods of `$path` as one line of text, separated by commas.
public static function header(string $path): string
{
array<string> $names = [];
foreach (Core\Router::methodsFor($path) as Core\Http\Method $method) {
$names[] = Core\Http::methodName($method);
}
return Core\Str::join($names, ', ');
}
}
// This prints `Allow: GET, POST`.
echo 'Allow: ', Allow::header('/invoices'), "\n";
Output
Allow: GET, POST

The method in a log line

<?nvs
// Writes the method of the current request into a log line.
// `Core\Request::method()` returns a `Core\Http\Method` case.
// `Core\Http::methodName` converts it to text. The request below uses `PUT`.
string $line = 'request method: ' . Core\Http::methodName(Core\Request::method());
// This prints `request method: PUT`.
echo $line, "\n";
Output
request method: PUT