1 <?php
2 /**
3 * @package Joomla.Platform
4 * @subpackage HTTP
5 *
6 * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
7 * @license GNU General Public License version 2 or later; see LICENSE
8 */
9
10 defined('JPATH_PLATFORM') or die;
11
12 use Joomla\Registry\Registry;
13
14 /**
15 * HTTP factory class.
16 *
17 * @since 12.1
18 */
19 class JHttpFactory
20 {
21 /**
22 * method to receive Http instance.
23 *
24 * @param Registry $options Client options object.
25 * @param mixed $adapters Adapter (string) or queue of adapters (array) to use for communication.
26 *
27 * @return JHttp Joomla Http class
28 *
29 * @throws RuntimeException
30 *
31 * @since 12.1
32 */
33 public static function getHttp(Registry $options = null, $adapters = null)
34 {
35 if (empty($options))
36 {
37 $options = new Registry;
38 }
39
40 if (!$driver = self::getAvailableDriver($options, $adapters))
41 {
42 throw new RuntimeException('No transport driver available.');
43 }
44
45 return new JHttp($options, $driver);
46 }
47
48 /**
49 * Finds an available http transport object for communication
50 *
51 * @param Registry $options Option for creating http transport object
52 * @param mixed $default Adapter (string) or queue of adapters (array) to use
53 *
54 * @return JHttpTransport Interface sub-class
55 *
56 * @since 12.1
57 */
58 public static function getAvailableDriver(Registry $options, $default = null)
59 {
60 if (is_null($default))
61 {
62 $availableAdapters = self::getHttpTransports();
63 }
64 else
65 {
66 settype($default, 'array');
67 $availableAdapters = $default;
68 }
69
70 // Check if there is at least one available http transport adapter
71 if (!count($availableAdapters))
72 {
73 return false;
74 }
75
76 foreach ($availableAdapters as $adapter)
77 {
78 $class = 'JHttpTransport' . ucfirst($adapter);
79
80 if (class_exists($class) && $class::isSupported())
81 {
82 return new $class($options);
83 }
84 }
85
86 return false;
87 }
88
89 /**
90 * Get the http transport handlers
91 *
92 * @return array An array of available transport handlers
93 *
94 * @since 12.1
95 */
96 public static function getHttpTransports()
97 {
98 $names = array();
99 $iterator = new DirectoryIterator(__DIR__ . '/transport');
100
101 /* @type $file DirectoryIterator */
102 foreach ($iterator as $file)
103 {
104 $fileName = $file->getFilename();
105
106 // Only load for php files.
107 if ($file->isFile() && $file->getExtension() == 'php')
108 {
109 $names[] = substr($fileName, 0, strrpos($fileName, '.'));
110 }
111 }
112
113 // Keep alphabetical order across all environments
114 sort($names);
115
116 // If curl is available set it to the first position
117 if ($key = array_search('curl', $names))
118 {
119 unset($names[$key]);
120 array_unshift($names, 'curl');
121 }
122
123 return $names;
124 }
125 }
126