Ei kuvausta

Common.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. if (is_file(__DIR__ . '/../autoload.php')) {
  3. require_once __DIR__ . '/../autoload.php';
  4. }
  5. if (is_file(__DIR__ . '/../vendor/autoload.php')) {
  6. require_once __DIR__ . '/../vendor/autoload.php';
  7. }
  8. require_once __DIR__ . '/Config.php';
  9. use OSS\OssClient;
  10. use OSS\Core\OssException;
  11. /**
  12. * Class Common
  13. *
  14. * 示例程序【Samples/*.php】 的Common类,用于获取OssClient实例和其他公用方法
  15. */
  16. class Common
  17. {
  18. const endpoint = Config::OSS_ENDPOINT;
  19. const accessKeyId = Config::OSS_ACCESS_ID;
  20. const accessKeySecret = Config::OSS_ACCESS_KEY;
  21. const bucket = Config::OSS_TEST_BUCKET;
  22. /**
  23. * 根据Config配置,得到一个OssClient实例
  24. *
  25. * @return OssClient 一个OssClient实例
  26. */
  27. public static function getOssClient()
  28. {
  29. try {
  30. $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
  31. } catch (OssException $e) {
  32. printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
  33. printf($e->getMessage() . "\n");
  34. return null;
  35. }
  36. return $ossClient;
  37. }
  38. public static function getBucketName()
  39. {
  40. return self::bucket;
  41. }
  42. /**
  43. * 工具方法,创建一个存储空间,如果发生异常直接exit
  44. */
  45. public static function createBucket()
  46. {
  47. $ossClient = self::getOssClient();
  48. if (is_null($ossClient)) exit(1);
  49. $bucket = self::getBucketName();
  50. $acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ;
  51. try {
  52. $ossClient->createBucket($bucket, $acl);
  53. } catch (OssException $e) {
  54. $message = $e->getMessage();
  55. if (\OSS\Core\OssUtil::startsWith($message, 'http status: 403')) {
  56. echo "Please Check your AccessKeyId and AccessKeySecret" . "\n";
  57. exit(0);
  58. } elseif (strpos($message, "BucketAlreadyExists") !== false) {
  59. echo "Bucket already exists. Please check whether the bucket belongs to you, or it was visited with correct endpoint. " . "\n";
  60. exit(0);
  61. }
  62. printf(__FUNCTION__ . ": FAILED\n");
  63. printf($e->getMessage() . "\n");
  64. return;
  65. }
  66. print(__FUNCTION__ . ": OK" . "\n");
  67. }
  68. public static function println($message)
  69. {
  70. if (!empty($message)) {
  71. echo strval($message) . "\n";
  72. }
  73. }
  74. }
  75. Common::createBucket();