Licenses.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. <?php
  2. /**
  3. * @package Grav.Common.GPM
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 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 $slug
  29. * @param $license
  30. *
  31. * @return boolean
  32. */
  33. public static function set($slug, $license)
  34. {
  35. $licenses = self::getLicenseFile();
  36. $data = $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 $slug
  58. *
  59. * @return string
  60. */
  61. public static function get($slug = null)
  62. {
  63. $licenses = self::getLicenseFile();
  64. $data = $licenses->content();
  65. $licenses->free();
  66. $slug = strtolower($slug);
  67. if (!$slug) {
  68. return isset($data['licenses']) ? $data['licenses'] : [];
  69. }
  70. if (!isset($data['licenses']) || !isset($data['licenses'][$slug])) {
  71. return '';
  72. }
  73. return $data['licenses'][$slug];
  74. }
  75. /**
  76. * Validates the License format
  77. *
  78. * @param $license
  79. *
  80. * @return bool
  81. */
  82. public static function validate($license = null)
  83. {
  84. if (!is_string($license)) {
  85. return false;
  86. }
  87. return preg_match('#' . self::$regex. '#', $license);
  88. }
  89. /**
  90. * Get's the License File object
  91. *
  92. * @return \RocketTheme\Toolbox\File\FileInterface
  93. */
  94. public static function getLicenseFile()
  95. {
  96. if (!isset(self::$file)) {
  97. $path = Grav::instance()['locator']->findResource('user://data') . '/licenses.yaml';
  98. if (!file_exists($path)) {
  99. touch($path);
  100. }
  101. self::$file = CompiledYamlFile::instance($path);
  102. }
  103. return self::$file;
  104. }
  105. }