phpCAS  version 1.4.0
CurlMultiRequest.php
Go to the documentation of this file.
1 <?php
2 
44 {
45  private $_requests = array();
46  private $_sent = false;
47 
48  /*********************************************************
49  * Add Requests
50  *********************************************************/
51 
64  public function addRequest (CAS_Request_RequestInterface $request)
65  {
66  if ($this->_sent) {
68  'Request has already been sent cannot '.__METHOD__
69  );
70  }
71  if (!$request instanceof CAS_Request_CurlRequest) {
73  'As a CAS_Request_CurlMultiRequest, I can only work with CAS_Request_CurlRequest objects.'
74  );
75  }
76 
77  $this->_requests[] = $request;
78  }
79 
86  public function getNumRequests()
87  {
88  if ($this->_sent) {
90  'Request has already been sent cannot '.__METHOD__
91  );
92  }
93  return count($this->_requests);
94  }
95 
96  /*********************************************************
97  * 2. Send the Request
98  *********************************************************/
99 
107  public function send ()
108  {
109  if ($this->_sent) {
110  throw new CAS_OutOfSequenceException(
111  'Request has already been sent cannot send again.'
112  );
113  }
114  if (!count($this->_requests)) {
115  throw new CAS_OutOfSequenceException(
116  'At least one request must be added via addRequest() before the multi-request can be sent.'
117  );
118  }
119 
120  $this->_sent = true;
121 
122  // Initialize our handles and configure all requests.
123  $handles = array();
124  $multiHandle = curl_multi_init();
125  foreach ($this->_requests as $i => $request) {
126  $handle = $request->initAndConfigure();
127  curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
128  $handles[$i] = $handle;
129  curl_multi_add_handle($multiHandle, $handle);
130  }
131 
132  // Execute the requests in parallel.
133  do {
134  curl_multi_exec($multiHandle, $running);
135  } while ($running > 0);
136 
137  // Populate all of the responses or errors back into the request objects.
138  foreach ($this->_requests as $i => $request) {
139  $buf = curl_multi_getcontent($handles[$i]);
140  $request->_storeResponseBody($buf);
141  curl_multi_remove_handle($multiHandle, $handles[$i]);
142  curl_close($handles[$i]);
143  }
144 
145  curl_multi_close($multiHandle);
146  }
147 }
addRequest(CAS_Request_RequestInterface $request)