Overview

Packages

  • php-surveymonkey
    • exception

Classes

  • SurveyMonkey

Exceptions

  • SurveyMonkey_Exception
  • Overview
  • Package
  • Class
  1: <?php
  2: /**
  3:  * Class for SurveyMonkey API v2
  4:  * @package php-surveymonkey
  5:  */
  6: class SurveyMonkey{
  7:   /**
  8:    * @var string API key
  9:    * @access protected
 10:    */
 11:   protected $_apiKey;
 12: 
 13:   /**
 14:    * @var string API access token
 15:    * @access protected
 16:    */
 17:   protected $_accessToken;
 18: 
 19:   /**
 20:    * @var string API protocol
 21:    * @access protected
 22:    */
 23:   protected $_protocol;
 24: 
 25:   /**
 26:    * @var string API hostname
 27:    * @access protected
 28:    */
 29:   protected $_hostname;
 30: 
 31:   /**
 32:    * @var string API version
 33:    * @access protected
 34:    */
 35:   protected $_version;
 36: 
 37:   /**
 38:    * @var resource $conn The client connection instance to use.
 39:    * @access private
 40:    */
 41:   private $conn = null;
 42: 
 43:   /**
 44:    * @var array (optional) cURL connection options
 45:    * @access protected
 46:    */
 47:   protected $_connectionOptions;
 48: 
 49:   /**
 50:    * @const SurveyMonkey Status code:  Success
 51:    */
 52:   const SM_STATUS_SUCCESS = 0;
 53: 
 54:   public static function successfulHttpResponse($code){
 55:     if ($code >= 200 and $code < 300){
 56:       return true;
 57:     }
 58:     return false;
 59:   }
 60:   /**
 61:    * SurveyMonkey API Status code definitions
 62:    */
 63:   public static $SM_STATUS_CODES = array(
 64:     0 => "Success",
 65:     1 => "Not Authenticated",
 66:     2 => "Invalid User Credentials",
 67:     3 => "Invalid Request",
 68:     4 => "Unknown User",
 69:     5 => "System Error",
 70:     6 => "Plan Limit Exceeded"
 71:   );
 72: 
 73:   /**
 74:    * Explain Survey Monkey status code
 75:    * @param integer $code Status code
 76:    * @return string Definition
 77:    */
 78:   public static function explainStatusCode($code){
 79:     return self::$SM_STATUS_CODES[$code];
 80:   }
 81: 
 82:   /**
 83:    * The SurveyMonkey Constructor.
 84:    *
 85:    * This method is used to create a new SurveyMonkey object with a connection to a
 86:    * specific api key and access token
 87:    *
 88:    * @param string $apiKey A valid api key
 89:    * @param string $accessToken A valid access token
 90:    * @param array $options (optional) An array of options
 91:    * @param array $connectionOptions (optional) cURL connection options
 92:    * @throws SurveyMonkey_Exception If an error occurs creating the instance.
 93:    * @return SurveyMonkey A unique SurveyMonkey instance.
 94:    */
 95:   public function __construct($apiKey, $accessToken, $options = array(), $connectionOptions = array()){
 96: 
 97:     if (empty($apiKey))     throw new SurveyMonkey_Exception('Missing apiKey');
 98:     if (empty($accessToken))  throw new SurveyMonkey_Exception('Missing accessToken');
 99:     $this->_apiKey = $apiKey;
100:     $this->_accessToken = $accessToken;
101: 
102:     $this->_protocol =  (!empty($options['protocol']))? $options['protocol']  : 'https';
103:     $this->_hostname =  (!empty($options['hostname']))? $options['hostname']  : 'api.surveymonkey.net';
104:     $this->_version =   (!empty($options['version']))?  $options['version']   : 'v2';
105: 
106:     $this->_connectionOptions = $connectionOptions;
107:   }
108: 
109:   /**
110:    * Build the request URI
111:    * @param string $endpoint API endpoint to call in the form: resource/method
112:    * @return string Constructed URI
113:    */
114:   protected function buildUri($endpoint){
115:     return $this->_protocol . '://' . $this->_hostname . '/' . $this->_version . '/' . $endpoint . '?api_key=' . $this->_apiKey;
116:   }
117: 
118:   /**
119:    * Get the connection
120:    * @return boolean
121:    */
122:   protected function getConnection(){
123:     $this->conn = curl_init();
124:     return is_resource($this->conn);
125:   }
126: 
127:   /**
128:    * Close the connection
129:    */
130:   protected function closeConnection(){
131:         curl_close($this->conn);
132:   }
133: 
134:   /**
135:    * Run the
136:    * @param string $method API method to run
137:    * @param array $params Parameters array
138:    * @return array Results
139:    */
140:   protected function run($endpoint, $params = array()){
141:     if (!is_resource($this->conn)) {
142:         if (!$this->getConnection()) return $this->failure('Can not initialize connection');
143:     }
144: 
145:     $request_url = $this->buildUri($endpoint);
146:     curl_setopt($this->conn, CURLOPT_URL, $request_url);  // URL to post to
147:     curl_setopt($this->conn, CURLOPT_RETURNTRANSFER, 1 );   // return into a variable
148:     $headers = array('Content-type: application/json', 'Authorization: Bearer ' . $this->_accessToken);
149:     curl_setopt($this->conn, CURLOPT_HTTPHEADER, $headers ); // custom headers
150:     curl_setopt($this->conn, CURLOPT_HEADER, false );     // return into a variable
151:     curl_setopt($this->conn, CURLOPT_POST, true);     // POST
152:     $postBody = (!empty($params))? json_encode($params) : "{}";
153:     curl_setopt($this->conn, CURLOPT_POSTFIELDS,  $postBody);
154:     curl_setopt_array($this->conn, $this->_connectionOptions);  // (optional) additional options
155: 
156:     $result = curl_exec( $this->conn );
157:     if ($result === false) return $this->failure('Curl Error: ' . curl_error($this->conn));
158:     $responseCode = curl_getinfo($this->conn, CURLINFO_HTTP_CODE);
159:     if (!self::successfulHttpResponse($responseCode)){
160:       return $this->failure('Error ['.$responseCode.']: ' . $result);
161:     }
162: 
163:     $this->closeConnection();
164: 
165:     $parsedResult = json_decode($result,true);
166:     $jsonErr = json_last_error();
167:     if ($parsedResult === null  &&  $jsonErr !== JSON_ERROR_NONE) return $this->failure("Error [$jsonErr] parsing result JSON");
168: 
169:     $status = $parsedResult['status'];
170:     if ($status != self::SM_STATUS_SUCCESS) return $this->failure("API Error: Status [$status:" . self::explainStatusCode($status) . '].  Message [' . $parsedResult["errmsg"] . ']');
171:     else return $this->success($parsedResult["data"]);
172:   }
173: 
174: 
175: 
176:   /**
177:    * Return an error
178:    * @param string $msg Error message
179:    * @return array Result
180:    */
181:   protected function failure($msg){
182:     return array(
183:       'success' => false,
184:       'message' => $msg
185:     );
186:   }
187: 
188:     /**
189:      * Return a success with data
190:      * @param string $data Payload
191:      * @return array Result
192:      */
193:   protected function success($data){
194:     return array(
195:       'success' => true,
196:       'data' => $data
197:     );
198:   }
199: 
200: 
201:   /***************************
202:    * SurveyMonkey API methods
203:    ***************************/
204: 
205:   //survey methods
206: 
207:   /**
208:    * Retrieves a paged list of surveys in a user's account.
209:    * @see https://developer.surveymonkey.com/mashery/get_survey_list
210:    * @param array $params optional request array
211:    * @return array Result
212:    */
213:   public function getSurveyList($params = array()){
214:     return $this->run('surveys/get_survey_list', $params);
215:   }
216: 
217:   /**
218:    * Retrieve a given survey's metadata.
219:    * @see https://developer.surveymonkey.com/mashery/get_survey_details
220:    * @param string $surveyId Survey ID
221:    * @return array Results
222:    */
223:   public function getSurveyDetails($surveyId){
224:     $params = array('survey_id'=>$surveyId);
225:     return $this->run('surveys/get_survey_details', $params);
226:   }
227: 
228:   /**
229:    * Retrieves a paged list of collectors for a survey in a user's account.
230:    * @see https://developer.surveymonkey.com/mashery/get_collector_list
231:    * @param string $surveyId Survey ID
232:    * @param array $params optional request array
233:    * @return array Results
234:    */
235:   public function getCollectorList($surveyId, $params = array()){
236:     $params['survey_id'] = $surveyId;
237:     return $this->run('surveys/get_collector_list', $params);
238:   }
239: 
240:   /**
241:    * Retrieves a paged list of respondents for a given survey and optionally collector
242:    * @see https://developer.surveymonkey.com/mashery/get_respondent_list
243:    * @param string $surveyId Survey ID
244:    * @param array $params optional request array
245:    * @return array Results
246:    */
247:   public function getRespondentList($surveyId, $params = array()){
248:     $params['survey_id'] = $surveyId;
249:     return $this->run('surveys/get_respondent_list', $params);
250:   }
251: 
252:   /**
253:    * Takes a list of respondent ids and returns the responses that correlate to them.
254:    * @see https://developer.surveymonkey.com/mashery/get_responses
255:    * @param string $surveyId Survey ID
256:    * @param array $respondentIds Array of respondents IDs to retrieve
257:    * @param integer $chunkSize optional number of respondants to fetch in each chunk. We split it to multiple requests to conform with SurveyMonkey's API limits.  If successful, the returned array is a joined array of all chunks.
258:    * @return array Results
259:    */
260:   public function getResponses($surveyId, $respondentIds, $chunkSize = 100){
261:     // Split requests to multiple chunks, if larger then $chunkSize
262:     if (count($respondentIds) > $chunkSize){
263:       $data = array();
264:       foreach (array_chunk($respondentIds, $chunkSize) as $r){
265:         $result = $this->getResponses($surveyId, $r, $chunkSize);
266:         if (!$result["success"]) return $result;
267:         $data = array_merge($data, $result["data"]);
268:       }
269:       return $this->success($data);
270:     }
271: 
272:     $params = array(
273:       'survey_id' => $surveyId,
274:       'respondent_ids' => $respondentIds
275:     );
276:     return $this->run('surveys/get_responses', $params);
277:   }
278: 
279:   /**
280:    * Returns how many respondents have started and/or completed the survey for the given collector
281:    * @see https://developer.surveymonkey.com/mashery/get_response_counts
282:    * @param string $collectorId Collector ID
283:    * @return array Results
284:    */
285:   public function getResponseCounts($collectorId){
286:     $params = array('collector_id' => $collectorId);
287:     return $this->run('surveys/get_response_counts', $params);
288:   }
289: 
290:   //user methods
291: 
292:   /**
293:    * Returns basic information about the logged-in user
294:    * @see https://developer.surveymonkey.com/mashery/get_user_details
295:    * @return array Results
296:    */
297:   public function getUserDetails(){
298:     return $this->run('user/get_user_details');
299:   }
300: 
301:   //template methods
302: 
303:   /**
304:    * Retrieves a paged list of templates provided by survey monkey.
305:    * @see https://developer.surveymonkey.com/mashery/get_template_list
306:    * @param array $params optional request array
307:    * @return array Results
308:    */
309:   public function getTemplateList($params = array()){
310:     return $this->run('templates/get_template_list', $params);
311:   }
312: 
313:   //collector methods
314: 
315:   /**
316:    * Retrieves a paged list of templates provided by survey monkey.
317:    * @see https://developer.surveymonkey.com/mashery/create_collector
318:    * @param string $surveyId Survey ID
319:    * @param string $collectorName optional Collector Name - defaults to 'New Link'
320:    * @param string $collectorType required Collector Type - only 'weblink' currently supported
321:    * @param array $params optional request array
322:    * @return array Results
323:    */
324:   public function createCollector($surveyId, $collectorName = null, $collectorType = 'weblink'){
325:     $params = array(
326:       'survey_id'=>$surveyId,
327:       'collector'=>array(
328:         'type'=>$collectorType,
329:         'name'=>$collectorName
330:       )
331:     );
332:     return $this->run('collectors/create_collector', $params);
333:   }
334: 
335:   //batch methods
336: 
337:   /**
338:    * Create a survey, email collector and email message based on a template or existing survey.
339:    * @see https://developer.surveymonkey.com/mashery/create_flow
340:    * @param string $surveyTitle Survey Title
341:    * @param array $params optional request array
342:    * @return array Results
343:    */
344:   public function createFlow($surveyTitle, $params = array()){
345:     if (isset($params['survey'])){
346:       $params['survey']['survey_title'] = $surveyTitle;
347:     }
348:     else{
349:       $params['survey'] = array('survey_title'=>$surveyTitle);
350:     }
351:     return $this->run('batch/create_flow', $params);
352:   }
353: 
354:   /**
355:    * Create an email collector and email message attaching them to an existing survey.
356:    * @see https://developer.surveymonkey.com/mashery/send_flow
357:    * @param string $surveyId Survey ID
358:    * @param array $params optional request array
359:    * @return array Results
360:    */
361:   public function sendFlow($surveyId, $params = array()){
362:     $params['survey_id'] = $surveyId;
363:     return $this->run('batch/send_flow', $params);
364:   }
365: }
366: 
367: /**
368:  * A basic class for SurveyMonkey Exceptions.
369:  * @package php-surveymonkey
370:  * @subpackage exception
371:  */
372: class SurveyMonkey_Exception extends Exception {}
API documentation generated by ApiGen