Create factory for MWHttpRequest
[lhc/web/wiklou.git] / includes / http / HttpRequestFactory.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20 namespace MediaWiki\Http;
21
22 use CurlHttpRequest;
23 use DomainException;
24 use Http;
25 use MediaWiki\Logger\LoggerFactory;
26 use MWHttpRequest;
27 use PhpHttpRequest;
28 use Profiler;
29
30 /**
31 * Factory creating MWHttpRequest objects.
32 */
33 class HttpRequestFactory {
34
35 /**
36 * Generate a new MWHttpRequest object
37 * @param string $url Url to use
38 * @param array $options (optional) extra params to pass (see Http::request())
39 * @param string $caller The method making this request, for profiling
40 * @throws DomainException
41 * @return MWHttpRequest
42 * @see MWHttpRequest::__construct
43 */
44 public function create( $url, array $options = [], $caller = __METHOD__ ) {
45 if ( !Http::$httpEngine ) {
46 Http::$httpEngine = function_exists( 'curl_init' ) ? 'curl' : 'php';
47 } elseif ( Http::$httpEngine == 'curl' && !function_exists( 'curl_init' ) ) {
48 throw new DomainException( __METHOD__ . ': curl (http://php.net/curl) is not installed, but' .
49 ' Http::$httpEngine is set to "curl"' );
50 }
51
52 if ( !isset( $options['logger'] ) ) {
53 $options['logger'] = LoggerFactory::getInstance( 'http' );
54 }
55
56 switch ( Http::$httpEngine ) {
57 case 'curl':
58 return new CurlHttpRequest( $url, $options, $caller, Profiler::instance() );
59 case 'php':
60 if ( !wfIniGetBool( 'allow_url_fopen' ) ) {
61 throw new DomainException( __METHOD__ . ': allow_url_fopen ' .
62 'needs to be enabled for pure PHP http requests to ' .
63 'work. If possible, curl should be used instead. See ' .
64 'http://php.net/curl.'
65 );
66 }
67 return new PhpHttpRequest( $url, $options, $caller, Profiler::instance() );
68 default:
69 throw new DomainException( __METHOD__ . ': The setting of Http::$httpEngine is not valid.' );
70 }
71 }
72
73 /**
74 * Simple function to test if we can make any sort of requests at all, using
75 * cURL or fopen()
76 * @return bool
77 */
78 public function canMakeRequests() {
79 return function_exists( 'curl_init' ) || wfIniGetBool( 'allow_url_fopen' );
80 }
81
82 }