utils.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Grav\Plugin\Admin;
  3. use Grav\Common\Grav;
  4. use Grav\Common\User\User;
  5. /**
  6. * Admin utils class
  7. *
  8. * @license MIT
  9. */
  10. class Utils
  11. {
  12. /**
  13. * Matches an email to a user
  14. *
  15. * @param $email
  16. *
  17. * @return User
  18. */
  19. public static function findUserByEmail($email)
  20. {
  21. $account_dir = Grav::instance()['locator']->findResource('account://');
  22. $files = array_diff(scandir($account_dir, SCANDIR_SORT_ASCENDING), ['.', '..']);
  23. foreach ($files as $file) {
  24. if (strpos($file, '.yaml') !== false) {
  25. $user = User::load(trim(substr($file, 0, -5)));
  26. if ($user['email'] === $email) {
  27. return $user;
  28. }
  29. }
  30. }
  31. // If a User with the provided email cannot be found, then load user with that email as the username
  32. return User::load($email);
  33. }
  34. /**
  35. * Generates a slug of the given string
  36. *
  37. * @param string $str
  38. * @return string
  39. */
  40. public static function slug($str)
  41. {
  42. if (function_exists('transliterator_transliterate')) {
  43. $str = transliterator_transliterate('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove;', $str);
  44. } else {
  45. $str = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $str);
  46. }
  47. $str = strtolower($str);
  48. $str = preg_replace('/[-\s]+/', '-', $str);
  49. $str = preg_replace('/[^a-z0-9-]/i', '', $str);
  50. $str = trim($str, '-');
  51. return $str;
  52. }
  53. }