diff --git a/CHANGELOG.md b/CHANGELOG.md index 628c7cf29..9aecfa50d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ 1. [](#new) * Added a `CompiledJsonFile` object to better handle Json files. * Added Base32 encode/decode class + * Added a new `User::find()` method 1. [](#improved) * Added `getTaxonomyItemKeys` to the Taxonomy object [#1124](https://github.com/getgrav/grav/issues/1124) * Added a `redirect_me` Twig function [#1124](https://github.com/getgrav/grav/issues/1124) diff --git a/system/src/Grav/Common/User/User.php b/system/src/Grav/Common/User/User.php index 340797011..fcc8f6c43 100644 --- a/system/src/Grav/Common/User/User.php +++ b/system/src/Grav/Common/User/User.php @@ -54,6 +54,42 @@ class User extends Data return $user; } + /** + * Find a user by username, email, etc + * + * @param $query the query to search for + * @param array $fields the fields to search + * @return User + */ + public static function find($query, $fields = ['username', 'email']) + { + $account_dir = Grav::instance()['locator']->findResource('account://'); + $files = array_diff(scandir($account_dir), ['.', '..']); + + // Try with username first, you never know! + if (in_array('username', $fields)) { + $user = User::load($query); + unset($fields[array_search('username', $fields)]); + } else { + $user = User::load(''); + } + + // If not found, try the fields + if (!$user->exists()) { + foreach ($files as $file) { + if (Utils::endsWith($file, YAML_EXT)) { + $find_user = User::load(trim(pathinfo($file, PATHINFO_FILENAME))); + foreach ($fields as $field) { + if ($find_user[$field] == $query) { + return $find_user; + } + } + } + } + } + return $user; + } + /** * Remove user account. *