RestApi.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * @author Albert Kozlowski <vojant@gmail.com>
  4. * @license MIT License
  5. * @link https://github.com/vojant/Twitter-php
  6. */
  7. namespace TwitterPhp;
  8. use \TwitterPhp\Connection\Application;
  9. use \TwitterPhp\Connection\User;
  10. require_once 'connection/ConnectionAbstract.php';
  11. require_once 'connection/Application.php';
  12. require_once 'connection/User.php';
  13. /**
  14. * Class TwitterRestApiException
  15. */
  16. class RestApiException extends \Exception {};
  17. /**
  18. * Class RestApi
  19. * @package TwitterPhp
  20. */
  21. class RestApi
  22. {
  23. /**
  24. * @var string
  25. */
  26. private $_consumerKey;
  27. /**
  28. * @var string
  29. */
  30. private $_consumerSecret;
  31. /**
  32. * @var string
  33. */
  34. private $_accessToken;
  35. /**
  36. * @var string
  37. */
  38. private $_accessTokenSecret;
  39. /**
  40. * @param string $consumerKey
  41. * @param string $consumerSecret
  42. * @param null|string $accessToken
  43. * @param null|string $accessTokenSecret
  44. * @throws TwitterRestApiException
  45. */
  46. public function __construct($consumerKey,$consumerSecret,$accessToken = null,$accessTokenSecret = null)
  47. {
  48. if (!function_exists('curl_init')) {
  49. throw new TwitterRestApiException('You must have the cURL extension enabled to use this library');
  50. }
  51. $this->_consumerKey = $consumerKey;
  52. $this->_consumerSecret = $consumerSecret;
  53. $this->_accessToken = $accessToken;
  54. $this->_accessTokenSecret = $accessTokenSecret;
  55. }
  56. /**
  57. * Connect to Twitter API as application.
  58. * @link https://dev.twitter.com/docs/auth/application-only-auth
  59. *
  60. * @return \TwitterPhp\Connection\Application
  61. */
  62. public function connectAsApplication()
  63. {
  64. return new Application($this->_consumerKey,$this->_consumerSecret);
  65. }
  66. /**
  67. * Connect to Twitter API as user.
  68. * @link https://dev.twitter.com/docs/auth/oauth/single-user-with-examples
  69. *
  70. * @return \TwitterPhp\Connection\User
  71. * @throws TwitterRestApiException
  72. */
  73. public function connectAsUser()
  74. {
  75. if (!$this->_accessToken || !$this->_accessTokenSecret) {
  76. throw new TwitterRestApiException('Missing ACCESS_TOKEN OR ACCESS_TOKEN_SECRET');
  77. }
  78. return new User($this->_consumerKey,$this->_consumerSecret,$this->_accessToken,$this->_accessTokenSecret);
  79. }
  80. }