FacebookBatchRequest.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. <?php
  2. /**
  3. * Copyright 2017 Facebook, Inc.
  4. *
  5. * You are hereby granted a non-exclusive, worldwide, royalty-free license to
  6. * use, copy, modify, and distribute this software in source code or binary
  7. * form for use in connection with the web services and APIs provided by
  8. * Facebook.
  9. *
  10. * As with any software that integrates with the Facebook platform, your use
  11. * of this software is subject to the Facebook Developer Principles and
  12. * Policies [http://developers.facebook.com/policy/]. This copyright notice
  13. * shall be included in all copies or substantial portions of the software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  21. * DEALINGS IN THE SOFTWARE.
  22. *
  23. */
  24. namespace Facebook;
  25. use ArrayIterator;
  26. use IteratorAggregate;
  27. use ArrayAccess;
  28. use Facebook\Authentication\AccessToken;
  29. use Facebook\Exceptions\FacebookSDKException;
  30. /**
  31. * Class BatchRequest
  32. *
  33. * @package Facebook
  34. */
  35. class FacebookBatchRequest extends FacebookRequest implements IteratorAggregate, ArrayAccess
  36. {
  37. /**
  38. * @var array An array of FacebookRequest entities to send.
  39. */
  40. protected $requests = [];
  41. /**
  42. * @var array An array of files to upload.
  43. */
  44. protected $attachedFiles;
  45. /**
  46. * Creates a new Request entity.
  47. *
  48. * @param FacebookApp|null $app
  49. * @param array $requests
  50. * @param AccessToken|string|null $accessToken
  51. * @param string|null $graphVersion
  52. */
  53. public function __construct(FacebookApp $app = null, array $requests = [], $accessToken = null, $graphVersion = null)
  54. {
  55. parent::__construct($app, $accessToken, 'POST', '', [], null, $graphVersion);
  56. $this->add($requests);
  57. }
  58. /**
  59. * Adds a new request to the array.
  60. *
  61. * @param FacebookRequest|array $request
  62. * @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'.
  63. * If a string is given, it is the value of the 'name' option.
  64. *
  65. * @return FacebookBatchRequest
  66. *
  67. * @throws \InvalidArgumentException
  68. */
  69. public function add($request, $options = null)
  70. {
  71. if (is_array($request)) {
  72. foreach ($request as $key => $req) {
  73. $this->add($req, $key);
  74. }
  75. return $this;
  76. }
  77. if (!$request instanceof FacebookRequest) {
  78. throw new \InvalidArgumentException('Argument for add() must be of type array or FacebookRequest.');
  79. }
  80. if (null === $options) {
  81. $options = [];
  82. } elseif (!is_array($options)) {
  83. $options = ['name' => $options];
  84. }
  85. $this->addFallbackDefaults($request);
  86. // File uploads
  87. $attachedFiles = $this->extractFileAttachments($request);
  88. $name = isset($options['name']) ? $options['name'] : null;
  89. unset($options['name']);
  90. $requestToAdd = [
  91. 'name' => $name,
  92. 'request' => $request,
  93. 'options' => $options,
  94. 'attached_files' => $attachedFiles,
  95. ];
  96. $this->requests[] = $requestToAdd;
  97. return $this;
  98. }
  99. /**
  100. * Ensures that the FacebookApp and access token fall back when missing.
  101. *
  102. * @param FacebookRequest $request
  103. *
  104. * @throws FacebookSDKException
  105. */
  106. public function addFallbackDefaults(FacebookRequest $request)
  107. {
  108. if (!$request->getApp()) {
  109. $app = $this->getApp();
  110. if (!$app) {
  111. throw new FacebookSDKException('Missing FacebookApp on FacebookRequest and no fallback detected on FacebookBatchRequest.');
  112. }
  113. $request->setApp($app);
  114. }
  115. if (!$request->getAccessToken()) {
  116. $accessToken = $this->getAccessToken();
  117. if (!$accessToken) {
  118. throw new FacebookSDKException('Missing access token on FacebookRequest and no fallback detected on FacebookBatchRequest.');
  119. }
  120. $request->setAccessToken($accessToken);
  121. }
  122. }
  123. /**
  124. * Extracts the files from a request.
  125. *
  126. * @param FacebookRequest $request
  127. *
  128. * @return string|null
  129. *
  130. * @throws FacebookSDKException
  131. */
  132. public function extractFileAttachments(FacebookRequest $request)
  133. {
  134. if (!$request->containsFileUploads()) {
  135. return null;
  136. }
  137. $files = $request->getFiles();
  138. $fileNames = [];
  139. foreach ($files as $file) {
  140. $fileName = uniqid();
  141. $this->addFile($fileName, $file);
  142. $fileNames[] = $fileName;
  143. }
  144. $request->resetFiles();
  145. // @TODO Does Graph support multiple uploads on one endpoint?
  146. return implode(',', $fileNames);
  147. }
  148. /**
  149. * Return the FacebookRequest entities.
  150. *
  151. * @return array
  152. */
  153. public function getRequests()
  154. {
  155. return $this->requests;
  156. }
  157. /**
  158. * Prepares the requests to be sent as a batch request.
  159. */
  160. public function prepareRequestsForBatch()
  161. {
  162. $this->validateBatchRequestCount();
  163. $params = [
  164. 'batch' => $this->convertRequestsToJson(),
  165. 'include_headers' => true,
  166. ];
  167. $this->setParams($params);
  168. }
  169. /**
  170. * Converts the requests into a JSON(P) string.
  171. *
  172. * @return string
  173. */
  174. public function convertRequestsToJson()
  175. {
  176. $requests = [];
  177. foreach ($this->requests as $request) {
  178. $options = [];
  179. if (null !== $request['name']) {
  180. $options['name'] = $request['name'];
  181. }
  182. $options += $request['options'];
  183. $requests[] = $this->requestEntityToBatchArray($request['request'], $options, $request['attached_files']);
  184. }
  185. return json_encode($requests);
  186. }
  187. /**
  188. * Validate the request count before sending them as a batch.
  189. *
  190. * @throws FacebookSDKException
  191. */
  192. public function validateBatchRequestCount()
  193. {
  194. $batchCount = count($this->requests);
  195. if ($batchCount === 0) {
  196. throw new FacebookSDKException('There are no batch requests to send.');
  197. } elseif ($batchCount > 50) {
  198. // Per: https://developers.facebook.com/docs/graph-api/making-multiple-requests#limits
  199. throw new FacebookSDKException('You cannot send more than 50 batch requests at a time.');
  200. }
  201. }
  202. /**
  203. * Converts a Request entity into an array that is batch-friendly.
  204. *
  205. * @param FacebookRequest $request The request entity to convert.
  206. * @param string|null|array $options Array of batch request options e.g. 'name', 'omit_response_on_success'.
  207. * If a string is given, it is the value of the 'name' option.
  208. * @param string|null $attachedFiles Names of files associated with the request.
  209. *
  210. * @return array
  211. */
  212. public function requestEntityToBatchArray(FacebookRequest $request, $options = null, $attachedFiles = null)
  213. {
  214. if (null === $options) {
  215. $options = [];
  216. } elseif (!is_array($options)) {
  217. $options = ['name' => $options];
  218. }
  219. $compiledHeaders = [];
  220. $headers = $request->getHeaders();
  221. foreach ($headers as $name => $value) {
  222. $compiledHeaders[] = $name . ': ' . $value;
  223. }
  224. $batch = [
  225. 'headers' => $compiledHeaders,
  226. 'method' => $request->getMethod(),
  227. 'relative_url' => $request->getUrl(),
  228. ];
  229. // Since file uploads are moved to the root request of a batch request,
  230. // the child requests will always be URL-encoded.
  231. $body = $request->getUrlEncodedBody()->getBody();
  232. if ($body) {
  233. $batch['body'] = $body;
  234. }
  235. $batch += $options;
  236. if (null !== $attachedFiles) {
  237. $batch['attached_files'] = $attachedFiles;
  238. }
  239. return $batch;
  240. }
  241. /**
  242. * Get an iterator for the items.
  243. *
  244. * @return ArrayIterator
  245. */
  246. public function getIterator()
  247. {
  248. return new ArrayIterator($this->requests);
  249. }
  250. /**
  251. * @inheritdoc
  252. */
  253. public function offsetSet($offset, $value)
  254. {
  255. $this->add($value, $offset);
  256. }
  257. /**
  258. * @inheritdoc
  259. */
  260. public function offsetExists($offset)
  261. {
  262. return isset($this->requests[$offset]);
  263. }
  264. /**
  265. * @inheritdoc
  266. */
  267. public function offsetUnset($offset)
  268. {
  269. unset($this->requests[$offset]);
  270. }
  271. /**
  272. * @inheritdoc
  273. */
  274. public function offsetGet($offset)
  275. {
  276. return isset($this->requests[$offset]) ? $this->requests[$offset] : null;
  277. }
  278. }