Licenses.php 2.6 KB

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