Licenses.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. <?php
  2. /**
  3. * @package Grav\Common\GPM
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\GPM;
  9. use Grav\Common\File\CompiledYamlFile;
  10. use Grav\Common\Grav;
  11. /**
  12. * Class Licenses
  13. *
  14. * @package Grav\Common\GPM
  15. */
  16. class Licenses
  17. {
  18. /**
  19. * Regex to validate the format of a License
  20. *
  21. * @var string
  22. */
  23. protected static $regex = '^(?:[A-F0-9]{8}-){3}(?:[A-F0-9]{8}){1}$';
  24. protected static $file;
  25. /**
  26. * Returns the license for a Premium package
  27. *
  28. * @param string $slug
  29. * @param string $license
  30. *
  31. * @return bool
  32. */
  33. public static function set($slug, $license)
  34. {
  35. $licenses = self::getLicenseFile();
  36. $data = (array)$licenses->content();
  37. $slug = strtolower($slug);
  38. if ($license && !self::validate($license)) {
  39. return false;
  40. }
  41. if (!\is_string($license)) {
  42. if (isset($data['licenses'][$slug])) {
  43. unset($data['licenses'][$slug]);
  44. } else {
  45. return false;
  46. }
  47. } else {
  48. $data['licenses'][$slug] = $license;
  49. }
  50. $licenses->save($data);
  51. $licenses->free();
  52. return true;
  53. }
  54. /**
  55. * Returns the license for a Premium package
  56. *
  57. * @param string $slug
  58. *
  59. * @return array|string
  60. */
  61. public static function get($slug = null)
  62. {
  63. $licenses = self::getLicenseFile();
  64. $data = (array)$licenses->content();
  65. $licenses->free();
  66. $slug = strtolower($slug);
  67. if (!$slug) {
  68. return $data['licenses'] ?? [];
  69. }
  70. return $data['licenses'][$slug] ?? '';
  71. }
  72. /**
  73. * Validates the License format
  74. *
  75. * @param string $license
  76. *
  77. * @return bool
  78. */
  79. public static function validate($license = null)
  80. {
  81. if (!is_string($license)) {
  82. return false;
  83. }
  84. return preg_match('#' . self::$regex. '#', $license);
  85. }
  86. /**
  87. * Get the License File object
  88. *
  89. * @return \RocketTheme\Toolbox\File\FileInterface
  90. */
  91. public static function getLicenseFile()
  92. {
  93. if (!isset(self::$file)) {
  94. $path = Grav::instance()['locator']->findResource('user-data://') . '/licenses.yaml';
  95. if (!file_exists($path)) {
  96. touch($path);
  97. }
  98. self::$file = CompiledYamlFile::instance($path);
  99. }
  100. return self::$file;
  101. }
  102. }