投稿日: 
ちょっと前に、【PHP】URLを渡すとヘッダー情報を見てステータスを返すやつ書いた | Shimabox Blogを書いたのですがせっかくなのでクラスにしてみました。
ソースはこちら
インストール
$ composer require shimabox/url-status
使い方
<?php
require_once 'vendor/autoload.php';
$ret = \SMB\UrlStatus::get('https://google.com/webhp?gl=us&hl=en&gws_rd=cr');
$ret->targetUrl(); // => 'https://google.com/webhp?gl=us&hl=en&gws_rd=cr'
$ret->reachedUrl(); // => 'https://www.google.com/webhp?gl=us&hl=en&gws_rd=cr'
$ret->isValidUrl(); // => true
$ret->redirectedUrls(); // => ['https://www.google.com/webhp?gl=us&hl=en&gws_rd=cr']
$ret->redirectedCode(); // => [301]
$ret->code(); // => 200
$ret->is200(); // => true
// for the POST method
$data = http_build_query(['foo' => 'bar', 'hoge' => 'piyo']);
$header = [
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: ' . strlen($data)
];
$options = [
'http' => [
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $data
]
];
$ret = \SMB\UrlStatus::get('http://localhost/post.php', $options);
関数版との違い
- インターフェイス( 第一引数にURL, 第二引数にstream_context作成用の値 )は変わっていません
stdClassを返していたのを自身\SMB\UrlStatusを返すように変更- 返されたプロパティを変更出来ないように
- isxxx()をマジックメソッドで用意
- is{数値3桁}()
/\Ais(\d{3})\z/- is200()とか、is503()とか
こんな感じです。雨が続いて憂鬱です。