Improved names of entity retrieval methods

This commit is contained in:
Marcin Kurczewski 2014-05-08 08:54:08 +02:00
parent e4ee4589a8
commit a14afd8e27
37 changed files with 148 additions and 114 deletions

View file

@ -12,7 +12,7 @@ abstract class AbstractPostJob extends AbstractJob
else else
{ {
$postId = $this->getArgument(self::POST_ID); $postId = $this->getArgument(self::POST_ID);
$this->post = PostModel::findByIdOrName($postId); $this->post = PostModel::getByIdOrName($postId);
} }
} }
} }

View file

@ -12,7 +12,7 @@ abstract class AbstractUserJob extends AbstractJob
else else
{ {
$userName = $this->getArgument(self::USER_NAME); $userName = $this->getArgument(self::USER_NAME);
$this->user = UserModel::findByNameOrEmail($userName); $this->user = UserModel::getByNameOrEmail($userName);
} }
} }
} }

View file

@ -7,7 +7,7 @@ class ActivateUserEmailJob extends AbstractJob
{ {
if (!$this->hasArgument(self::TOKEN)) if (!$this->hasArgument(self::TOKEN))
{ {
$user = UserModel::findByNameOrEmail($this->getArgument(self::USER_NAME)); $user = UserModel::getByNameOrEmail($this->getArgument(self::USER_NAME));
if (empty($user->getUnconfirmedEmail())) if (empty($user->getUnconfirmedEmail()))
{ {
@ -24,7 +24,7 @@ class ActivateUserEmailJob extends AbstractJob
else else
{ {
$tokenText = $this->getArgument(self::TOKEN); $tokenText = $this->getArgument(self::TOKEN);
$token = TokenModel::findByToken($tokenText); $token = TokenModel::getByToken($tokenText);
TokenModel::checkValidity($token); TokenModel::checkValidity($token);
$user = $token->getUser(); $user = $token->getUser();

View file

@ -4,7 +4,7 @@ class AddCommentJob extends AbstractJob
public function execute() public function execute()
{ {
$user = Auth::getCurrentUser(); $user = Auth::getCurrentUser();
$post = PostModel::findById($this->getArgument(self::POST_ID)); $post = PostModel::getById($this->getArgument(self::POST_ID));
$text = $this->getArgument(self::TEXT); $text = $this->getArgument(self::TEXT);
$comment = CommentModel::spawn(); $comment = CommentModel::spawn();

View file

@ -5,7 +5,7 @@ class DeleteCommentJob extends AbstractJob
public function prepare() public function prepare()
{ {
$this->comment = CommentModel::findById($this->getArgument(self::COMMENT_ID)); $this->comment = CommentModel::getById($this->getArgument(self::COMMENT_ID));
} }
public function execute() public function execute()

View file

@ -5,7 +5,7 @@ class EditCommentJob extends AbstractJob
public function prepare() public function prepare()
{ {
$this->comment = CommentModel::findById($this->getArgument(self::COMMENT_ID)); $this->comment = CommentModel::getById($this->getArgument(self::COMMENT_ID));
} }
public function execute() public function execute()

View file

@ -5,7 +5,7 @@ class GetPostContentJob extends AbstractJob
public function prepare() public function prepare()
{ {
$this->post = PostModel::findByName($this->getArgument(self::POST_NAME)); $this->post = PostModel::getByName($this->getArgument(self::POST_NAME));
} }
public function execute() public function execute()

View file

@ -16,7 +16,7 @@ class GetPostThumbJob extends AbstractJob
$path = PostModel::getThumbDefaultPath($name, $width, $height); $path = PostModel::getThumbDefaultPath($name, $width, $height);
if (!file_exists($path)) if (!file_exists($path))
{ {
$post = PostModel::findByIdOrName($name); $post = PostModel::getByIdOrName($name);
if ($post->isHidden()) if ($post->isHidden())
Access::assert(new Privilege(Privilege::ListPosts, 'hidden')); Access::assert(new Privilege(Privilege::ListPosts, 'hidden'));

View file

@ -8,7 +8,7 @@ class PasswordResetJob extends AbstractJob
{ {
if (!$this->hasArgument(self::TOKEN)) if (!$this->hasArgument(self::TOKEN))
{ {
$user = UserModel::findByNameOrEmail($this->getArgument(self::USER_NAME)); $user = UserModel::getByNameOrEmail($this->getArgument(self::USER_NAME));
if (empty($user->getConfirmedEmail())) if (empty($user->getConfirmedEmail()))
throw new SimpleException('This user has no e-mail confirmed; password reset cannot proceed'); throw new SimpleException('This user has no e-mail confirmed; password reset cannot proceed');
@ -20,7 +20,7 @@ class PasswordResetJob extends AbstractJob
else else
{ {
$tokenText = $this->getArgument(self::TOKEN); $tokenText = $this->getArgument(self::TOKEN);
$token = TokenModel::findByToken($tokenText); $token = TokenModel::getByToken($tokenText);
TokenModel::checkValidity($token); TokenModel::checkValidity($token);
$alphabet = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9')); $alphabet = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9'));

View file

@ -8,13 +8,13 @@ class PreviewCommentJob extends AbstractJob
if ($this->hasArgument(self::POST_ID)) if ($this->hasArgument(self::POST_ID))
{ {
$post = PostModel::findById($this->getArgument(self::POST_ID)); $post = PostModel::getById($this->getArgument(self::POST_ID));
$comment = CommentModel::spawn(); $comment = CommentModel::spawn();
$comment->setPost($post); $comment->setPost($post);
} }
else else
{ {
$comment = CommentModel::findById($this->getArgument(self::COMMENT_ID)); $comment = CommentModel::getById($this->getArgument(self::COMMENT_ID));
} }
$comment->setCommenter($user); $comment->setCommenter($user);

View file

@ -11,7 +11,7 @@ class TogglePostTagJob extends AbstractPostJob
if ($enable) if ($enable)
{ {
$tag = TagModel::findByName($tagName, false); $tag = TagModel::tryGetByName($tagName);
if ($tag === null) if ($tag === null)
{ {
$tag = TagModel::spawn(); $tag = TagModel::spawn();

View file

@ -13,7 +13,7 @@ class Auth
$config = getConfig(); $config = getConfig();
$context = getContext(); $context = getContext();
$user = UserModel::findByNameOrEmail($name, false); $user = UserModel::tryGetByNameOrEmail($name);
if ($user === null) if ($user === null)
throw new SimpleException('Invalid username'); throw new SimpleException('Invalid username');

View file

@ -38,7 +38,7 @@ class CommentController
public function editView($id) public function editView($id)
{ {
getContext()->transport->comment = CommentModel::findById($id); getContext()->transport->comment = CommentModel::getById($id);
} }
public function editAction($id) public function editAction($id)

View file

@ -69,7 +69,7 @@ class PostController
{ {
Access::assert(new Privilege( Access::assert(new Privilege(
Privilege::MassTag, Privilege::MassTag,
Access::getIdentity(PostModel::findById($id)->getUploader()))); Access::getIdentity(PostModel::getById($id)->getUploader())));
Api::run( Api::run(
new TogglePostTagJob(), new TogglePostTagJob(),
@ -121,7 +121,7 @@ class PostController
public function editAction($id) public function editAction($id)
{ {
$post = PostModel::findByIdOrName($id); $post = PostModel::getByIdOrName($id);
$editToken = InputHelper::get('edit-token'); $editToken = InputHelper::get('edit-token');
if ($editToken != $post->getEditToken()) if ($editToken != $post->getEditToken())

View file

@ -12,7 +12,7 @@ class StaticPagesController
{ {
$context->featuredPost = $featuredPost; $context->featuredPost = $featuredPost;
$context->featuredPostDate = PropertyModel::get(PropertyModel::FeaturedPostDate); $context->featuredPostDate = PropertyModel::get(PropertyModel::FeaturedPostDate);
$context->featuredPostUser = UserModel::findByNameOrEmail( $context->featuredPostUser = UserModel::getByNameOrEmail(
PropertyModel::get(PropertyModel::FeaturedPostUserName), PropertyModel::get(PropertyModel::FeaturedPostUserName),
false); false);
} }
@ -48,7 +48,7 @@ class StaticPagesController
return PropertyModel::featureNewPost(); return PropertyModel::featureNewPost();
//check if post was deleted //check if post was deleted
$featuredPost = PostModel::findById($featuredPostId, false); $featuredPost = PostModel::tryGetById($featuredPostId);
if (!$featuredPost) if (!$featuredPost)
return PropertyModel::featureNewPost(); return PropertyModel::featureNewPost();

View file

@ -135,7 +135,7 @@ class UserController
Api::run(new DeleteUserJob(), [ Api::run(new DeleteUserJob(), [
DeleteUserJob::USER_NAME => $name]); DeleteUserJob::USER_NAME => $name]);
$user = UserModel::findById(Auth::getCurrentUser()->getId(), false); $user = UserModel::tryGetById(Auth::getCurrentUser()->getId());
if (!$user) if (!$user)
Auth::logOut(); Auth::logOut();

View file

@ -23,8 +23,15 @@ abstract class AbstractCrudModel implements IModel
} }
public static function getById($key)
{
$ret = self::tryGetById($key);
if (!$ret)
throw new SimpleNotFoundException('Invalid %s ID "%s"', static::getTableName(), $key);
return $ret;
}
public static function findById($key, $throw = true) public static function tryGetById($key)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('*'); $stmt->setColumn('*');
@ -32,15 +39,12 @@ abstract class AbstractCrudModel implements IModel
$stmt->setCriterion(new Sql\EqualsFunctor('id', new Sql\Binding($key))); $stmt->setCriterion(new Sql\EqualsFunctor('id', new Sql\Binding($key)));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return static::convertRow($row); ? static::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('Invalid %s ID "%s"', static::getTableName(), $key);
return null;
} }
public static function findByIds(array $ids) public static function getAllByIds(array $ids)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('*'); $stmt->setColumn('*');

View file

@ -56,7 +56,7 @@ final class CommentModel extends AbstractCrudModel
public static function findAllByPostId($key) public static function getAllByPostId($key)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('comment.*'); $stmt->setColumn('comment.*');
@ -76,7 +76,7 @@ final class CommentModel extends AbstractCrudModel
self::preloadOneToMany($comments, self::preloadOneToMany($comments,
function($comment) { return $comment->getCommenterId(); }, function($comment) { return $comment->getCommenterId(); },
function($user) { return $user->getId(); }, function($user) { return $user->getId(); },
function($userIds) { return UserModel::findByIds($userIds); }, function($userIds) { return UserModel::getAllByIds($userIds); },
function($comment, $user) { return $comment->setCache('commenter', $user); }); function($comment, $user) { return $comment->setCache('commenter', $user); });
} }
@ -85,7 +85,7 @@ final class CommentModel extends AbstractCrudModel
self::preloadOneToMany($comments, self::preloadOneToMany($comments,
function($comment) { return $comment->getPostId(); }, function($comment) { return $comment->getPostId(); },
function($post) { return $post->getId(); }, function($post) { return $post->getId(); },
function($postIds) { return PostModel::findByIds($postIds); }, function($postIds) { return PostModel::getAllByIds($postIds); },
function($comment, $post) { $comment->setCache('post', $post); }); function($comment, $post) { $comment->setCache('post', $post); });
} }
} }

View file

@ -45,7 +45,7 @@ final class CommentEntity extends AbstractEntity implements IValidatable
{ {
if ($this->hasCache('post')) if ($this->hasCache('post'))
return $this->getCache('post'); return $this->getCache('post');
$post = PostModel::findById($this->getPostId()); $post = PostModel::getById($this->getPostId());
$this->setCache('post', $post); $this->setCache('post', $post);
return $post; return $post;
} }
@ -77,7 +77,7 @@ final class CommentEntity extends AbstractEntity implements IValidatable
return $this->getCache('commenter'); return $this->getCache('commenter');
if (!$this->commenterId) if (!$this->commenterId)
return null; return null;
$user = UserModel::findById($this->commenterId, false); $user = UserModel::tryGetById($this->commenterId);
$this->setCache('commenter', $user); $this->setCache('commenter', $user);
return $user; return $user;
} }

View file

@ -45,7 +45,7 @@ class PostEntity extends AbstractEntity implements IValidatable
return $this->getCache('uploader'); return $this->getCache('uploader');
if (!$this->uploaderId) if (!$this->uploaderId)
return null; return null;
$uploader = UserModel::findById($this->uploaderId, false); $uploader = UserModel::tryGetById($this->uploaderId);
$this->setCache('uploader', $uploader); $this->setCache('uploader', $uploader);
return $uploader; return $uploader;
} }
@ -65,7 +65,7 @@ class PostEntity extends AbstractEntity implements IValidatable
{ {
if ($this->hasCache('comments')) if ($this->hasCache('comments'))
return $this->getCache('comments'); return $this->getCache('comments');
$comments = CommentModel::findAllByPostId($this->getId()); $comments = CommentModel::getAllByPostId($this->getId());
$this->setCache('comments', $comments); $this->setCache('comments', $comments);
return $comments; return $comments;
} }
@ -139,7 +139,7 @@ class PostEntity extends AbstractEntity implements IValidatable
$config->browsing->maxRelatedPosts); $config->browsing->maxRelatedPosts);
} }
$relatedPosts []= PostModel::findById($relatedId); $relatedPosts []= PostModel::getById($relatedId);
} }
$this->setRelations($relatedPosts); $this->setRelations($relatedPosts);
@ -149,7 +149,7 @@ class PostEntity extends AbstractEntity implements IValidatable
{ {
if ($this->hasCache('tags')) if ($this->hasCache('tags'))
return $this->getCache('tags'); return $this->getCache('tags');
$tags = TagModel::findAllByPostId($this->getId()); $tags = TagModel::getAllByPostId($this->getId());
$this->setCache('tags', $tags); $this->setCache('tags', $tags);
return $tags; return $tags;
} }
@ -400,7 +400,7 @@ class PostEntity extends AbstractEntity implements IValidatable
throw new SimpleException('Invalid file type "%s"', $this->getMimeType()); throw new SimpleException('Invalid file type "%s"', $this->getMimeType());
} }
$duplicatedPost = PostModel::findByHash($this->getFileHash(), false); $duplicatedPost = PostModel::tryGetByHash($this->getFileHash());
if ($duplicatedPost !== null and (!$this->getId() or $this->getId() != $duplicatedPost->getId())) if ($duplicatedPost !== null and (!$this->getId() or $this->getId() != $duplicatedPost->getId()))
{ {
throw new SimpleException( throw new SimpleException(
@ -438,7 +438,7 @@ class PostEntity extends AbstractEntity implements IValidatable
if (file_exists($thumbPath)) if (file_exists($thumbPath))
unlink($thumbPath); unlink($thumbPath);
$duplicatedPost = PostModel::findByHash($youtubeId, false); $duplicatedPost = PostModel::tryGetByHash($youtubeId);
if ($duplicatedPost !== null and (!$this->getId() or $this->getId() != $duplicatedPost->getId())) if ($duplicatedPost !== null and (!$this->getId() or $this->getId() != $duplicatedPost->getId()))
{ {
throw new SimpleException( throw new SimpleException(

View file

@ -43,7 +43,7 @@ class TokenEntity extends AbstractEntity implements IValidatable
public function getUser() public function getUser()
{ {
return UserModel::findById($this->userId); return UserModel::getById($this->userId);
} }
public function getUserId() public function getUserId()

View file

@ -38,7 +38,7 @@ class UserEntity extends AbstractEntity implements IValidatable
$userName = $this->getName(); $userName = $this->getName();
$config = getConfig(); $config = getConfig();
$otherUser = UserModel::findByName($userName, false); $otherUser = UserModel::tryGetByName($userName);
if ($otherUser !== null and $otherUser->getId() != $this->getId()) if ($otherUser !== null and $otherUser->getId() != $this->getId())
{ {
if (!$otherUser->getConfirmedEmail() if (!$otherUser->getConfirmedEmail()

View file

@ -145,7 +145,15 @@ class PostModel extends AbstractCrudModel
public static function findByName($key, $throw = true) public static function getByName($key)
{
$ret = self::tryGetByName($key);
if (!$ret)
throw new SimpleNotFoundException('Invalid post name "%s"', $key);
return $ret;
}
public static function tryGetByName($key, $throw = true)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('*'); $stmt->setColumn('*');
@ -153,24 +161,29 @@ class PostModel extends AbstractCrudModel
$stmt->setCriterion(new Sql\EqualsFunctor('name', new Sql\Binding($key))); $stmt->setCriterion(new Sql\EqualsFunctor('name', new Sql\Binding($key)));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return self::convertRow($row); ? self::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('Invalid post name "%s"', $key);
return null;
} }
public static function findByIdOrName($key, $throw = true) public static function getByIdOrName($key)
{ {
if (is_numeric($key)) if (is_numeric($key))
$post = self::findById($key, $throw); $post = self::getById($key);
else else
$post = self::findByName($key, $throw); $post = self::getByName($key);
return $post; return $post;
} }
public static function findByHash($key, $throw = true) public static function getByHash($key)
{
$ret = self::tryGetByHash($key);
if (!$ret)
throw new SimpleNotFoundException('Invalid post hash "%s"', $hash);
return $ret;
}
public static function tryGetByHash($key)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('*'); $stmt->setColumn('*');
@ -178,12 +191,9 @@ class PostModel extends AbstractCrudModel
$stmt->setCriterion(new Sql\EqualsFunctor('file_hash', new Sql\Binding($key))); $stmt->setCriterion(new Sql\EqualsFunctor('file_hash', new Sql\Binding($key)));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return self::convertRow($row); ? self::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('Invalid post hash "%s"', $hash);
return null;
} }

View file

@ -85,6 +85,6 @@ class PropertyModel implements IModel
self::set(self::FeaturedPostId, $featuredPostId); self::set(self::FeaturedPostId, $featuredPostId);
self::set(self::FeaturedPostDate, time()); self::set(self::FeaturedPostDate, time());
self::set(self::FeaturedPostUserName, null); self::set(self::FeaturedPostUserName, null);
return PostModel::findById($featuredPostId); return PostModel::getById($featuredPostId);
} }
} }

View file

@ -38,7 +38,7 @@ class PostSearchParser extends AbstractSearchParser
foreach ($this->tags as $item) foreach ($this->tags as $item)
{ {
list ($tagName, $neg) = $item; list ($tagName, $neg) = $item;
$tag = TagModel::findByName($tagName); $tag = TagModel::getByName($tagName);
$innerStmt = new Sql\SelectStatement(); $innerStmt = new Sql\SelectStatement();
$innerStmt->setTable('post_tag'); $innerStmt->setTable('post_tag');
$innerStmt->setCriterion((new Sql\ConjunctionFunctor) $innerStmt->setCriterion((new Sql\ConjunctionFunctor)
@ -73,7 +73,7 @@ class PostSearchParser extends AbstractSearchParser
elseif (in_array($key, ['fav', 'favs', 'favd'])) elseif (in_array($key, ['fav', 'favs', 'favd']))
{ {
$user = UserModel::findByNameOrEmail($value); $user = UserModel::getByNameOrEmail($value);
$innerStmt = (new Sql\SelectStatement) $innerStmt = (new Sql\SelectStatement)
->setTable('favoritee') ->setTable('favoritee')
->setCriterion((new Sql\ConjunctionFunctor) ->setCriterion((new Sql\ConjunctionFunctor)
@ -84,7 +84,7 @@ class PostSearchParser extends AbstractSearchParser
elseif (in_array($key, ['comment', 'comments', 'commenter', 'commented'])) elseif (in_array($key, ['comment', 'comments', 'commenter', 'commented']))
{ {
$user = UserModel::findByNameOrEmail($value); $user = UserModel::getByNameOrEmail($value);
$innerStmt = (new Sql\SelectStatement) $innerStmt = (new Sql\SelectStatement)
->setTable('comment') ->setTable('comment')
->setCriterion((new Sql\ConjunctionFunctor) ->setCriterion((new Sql\ConjunctionFunctor)
@ -95,7 +95,7 @@ class PostSearchParser extends AbstractSearchParser
elseif (in_array($key, ['submit', 'upload', 'uploads', 'uploader', 'uploaded'])) elseif (in_array($key, ['submit', 'upload', 'uploads', 'uploader', 'uploaded']))
{ {
$user = UserModel::findByNameOrEmail($value); $user = UserModel::getByNameOrEmail($value);
return new Sql\EqualsFunctor('post.uploader_id', new Sql\Binding($user->getId())); return new Sql\EqualsFunctor('post.uploader_id', new Sql\Binding($user->getId()));
} }

View file

@ -11,7 +11,7 @@ class TagSearchService extends AbstractSearchService
public static function getRelatedTags($parentTagName) public static function getRelatedTags($parentTagName)
{ {
$parentTagEntity = TagModel::findByName($parentTagName, false); $parentTagEntity = TagModel::tryGetByName($parentTagName);
if (empty($parentTagEntity)) if (empty($parentTagEntity))
return []; return [];
$parentTagId = $parentTagEntity->getId(); $parentTagId = $parentTagEntity->getId();

View file

@ -55,8 +55,8 @@ class TagModel extends AbstractCrudModel
{ {
Database::transaction(function() use ($sourceName, $targetName) Database::transaction(function() use ($sourceName, $targetName)
{ {
$sourceTag = TagModel::findByName($sourceName); $sourceTag = TagModel::getByName($sourceName);
$targetTag = TagModel::findByName($targetName, false); $targetTag = TagModel::tryGetByName($targetName);
if ($targetTag and $targetTag->getId() != $sourceTag->getId()) if ($targetTag and $targetTag->getId() != $sourceTag->getId())
throw new SimpleException('Target tag already exists'); throw new SimpleException('Target tag already exists');
@ -71,8 +71,8 @@ class TagModel extends AbstractCrudModel
{ {
Database::transaction(function() use ($sourceName, $targetName) Database::transaction(function() use ($sourceName, $targetName)
{ {
$sourceTag = TagModel::findByName($sourceName); $sourceTag = TagModel::getByName($sourceName);
$targetTag = TagModel::findByName($targetName); $targetTag = TagModel::getByName($targetName);
if ($sourceTag->getId() == $targetTag->getId()) if ($sourceTag->getId() == $targetTag->getId())
throw new SimpleException('Source and target tag are the same'); throw new SimpleException('Source and target tag are the same');
@ -116,7 +116,7 @@ class TagModel extends AbstractCrudModel
} }
public static function findAllByPostId($key) public static function getAllByPostId($key)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('tag.*'); $stmt->setColumn('tag.*');
@ -130,7 +130,15 @@ class TagModel extends AbstractCrudModel
return []; return [];
} }
public static function findByName($key, $throw = true) public static function getByName($key)
{
$ret = self::tryGetByName($key);
if (!$ret)
throw new SimpleNotFoundException('Invalid tag name "%s"', $key);
return $ret;
}
public static function tryGetByName($key)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('tag.*'); $stmt->setColumn('tag.*');
@ -138,12 +146,9 @@ class TagModel extends AbstractCrudModel
$stmt->setCriterion(new Sql\NoCaseFunctor(new Sql\EqualsFunctor('name', new Sql\Binding($key)))); $stmt->setCriterion(new Sql\NoCaseFunctor(new Sql\EqualsFunctor('name', new Sql\Binding($key))));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return self::convertRow($row); ? self::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('Invalid tag name "%s"', $key);
return null;
} }
@ -166,7 +171,7 @@ class TagModel extends AbstractCrudModel
$tags = []; $tags = [];
foreach ($tagNames as $tagName) foreach ($tagNames as $tagName)
{ {
$tag = TagModel::findByName($tagName, false); $tag = TagModel::tryGetByName($tagName);
if (!$tag) if (!$tag)
{ {
$tag = TagModel::spawn(); $tag = TagModel::spawn();

View file

@ -37,7 +37,15 @@ class TokenModel extends AbstractCrudModel
return $token; return $token;
} }
public static function findByToken($key, $throw = true) public static function getByToken($key)
{
$ret = self::tryGetByToken($key);
if (!$ret)
throw new SimpleNotFoundException('No user with such security token');
return $ret;
}
public static function tryGetByToken($key)
{ {
if (empty($key)) if (empty($key))
throw new SimpleNotFoundException('Invalid security token'); throw new SimpleNotFoundException('Invalid security token');
@ -48,12 +56,9 @@ class TokenModel extends AbstractCrudModel
$stmt->setCriterion(new Sql\EqualsFunctor('token', new Sql\Binding($key))); $stmt->setCriterion(new Sql\EqualsFunctor('token', new Sql\Binding($key)));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return self::convertRow($row); ? self::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('No user with such security token');
return null;
} }
public static function checkValidity($token) public static function checkValidity($token)
@ -74,7 +79,7 @@ class TokenModel extends AbstractCrudModel
while (true) while (true)
{ {
$tokenText = md5(mt_rand() . uniqid()); $tokenText = md5(mt_rand() . uniqid());
$token = self::findByToken($tokenText, false); $token = self::tryGetByToken($tokenText);
if (!$token) if (!$token)
return $tokenText; return $tokenText;
} }

View file

@ -101,7 +101,15 @@ class UserModel extends AbstractCrudModel
public static function findByName($key, $throw = true) public static function getByName($key)
{
$ret = self::tryGetByName($key);
if (!$ret)
throw new SimpleNotFoundException('Invalid user name "%s"', $key);
return $ret;
}
public static function tryGetByName($key)
{ {
$stmt = new Sql\SelectStatement(); $stmt = new Sql\SelectStatement();
$stmt->setColumn('*'); $stmt->setColumn('*');
@ -109,15 +117,20 @@ class UserModel extends AbstractCrudModel
$stmt->setCriterion(new Sql\NoCaseFunctor(new Sql\EqualsFunctor('name', new Sql\Binding(trim($key))))); $stmt->setCriterion(new Sql\NoCaseFunctor(new Sql\EqualsFunctor('name', new Sql\Binding(trim($key)))));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return self::convertRow($row); ? self::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('Invalid user name "%s"', $key);
return null;
} }
public static function findByNameOrEmail($key, $throw = true) public static function getByNameOrEmail($key)
{
$ret = self::tryGetByNameOrEmail($key);
if (!$ret)
throw new SimpleNotFoundException('Invalid user name "%s"', $key);
return $ret;
}
public static function tryGetByNameOrEmail($key)
{ {
$key = trim($key); $key = trim($key);
@ -130,12 +143,9 @@ class UserModel extends AbstractCrudModel
->add(new Sql\NoCaseFunctor(new Sql\EqualsFunctor('email_confirmed', new Sql\Binding($key))))); ->add(new Sql\NoCaseFunctor(new Sql\EqualsFunctor('email_confirmed', new Sql\Binding($key)))));
$row = Database::fetchOne($stmt); $row = Database::fetchOne($stmt);
if ($row) return $row
return self::convertRow($row); ? self::convertRow($row)
: null;
if ($throw)
throw new SimpleNotFoundException('Invalid user name "%s"', $key);
return null;
} }

View file

@ -25,7 +25,7 @@ class ActivateUserEmailJobTest extends AbstractTest
$tokens = Mailer::getMailsSent()[0]->tokens; $tokens = Mailer::getMailsSent()[0]->tokens;
$tokenText = $tokens['token']; $tokenText = $tokens['token'];
$token = TokenModel::findByToken($tokenText); $token = TokenModel::getByToken($tokenText);
$this->assert->areEqual($user->getId(), $token->getUser()->getId()); $this->assert->areEqual($user->getId(), $token->getUser()->getId());
$this->assert->isTrue(strpos($tokens['link'], $tokenText) !== false); $this->assert->isTrue(strpos($tokens['link'], $tokenText) !== false);
@ -66,7 +66,7 @@ class ActivateUserEmailJobTest extends AbstractTest
}); });
//reload local entity after changes done by the job //reload local entity after changes done by the job
$user = UserModel::findById($user->getId()); $user = UserModel::getById($user->getId());
$this->assert->areEqual(null, $user->getUnconfirmedEmail()); $this->assert->areEqual(null, $user->getUnconfirmedEmail());
$this->assert->areEqual('godzilla@whitestar.gov', $user->getConfirmedEmail()); $this->assert->areEqual('godzilla@whitestar.gov', $user->getConfirmedEmail());
@ -139,8 +139,8 @@ class ActivateUserEmailJobTest extends AbstractTest
$token2text = $tokens2['token']; $token2text = $tokens2['token'];
$this->assert->areNotEqual($token1text, $token2text); $this->assert->areNotEqual($token1text, $token2text);
$token1 = TokenModel::findByToken($token1text); $token1 = TokenModel::getByToken($token1text);
$token2 = TokenModel::findByToken($token2text); $token2 = TokenModel::getByToken($token2text);
$this->assert->areEqual($user1->getId(), $token1->getUser()->getId()); $this->assert->areEqual($user1->getId(), $token1->getUser()->getId());
$this->assert->areEqual($user2->getId(), $token2->getUser()->getId()); $this->assert->areEqual($user2->getId(), $token2->getUser()->getId());

View file

@ -20,7 +20,7 @@ class AddCommentJobTest extends AbstractTest
$this->assert->isNotNull($comment->getCreationTime()); $this->assert->isNotNull($comment->getCreationTime());
$this->assert->doesNotThrow(function() use ($comment) $this->assert->doesNotThrow(function() use ($comment)
{ {
CommentModel::findById($comment->getId()); CommentModel::getById($comment->getId());
}); });
} }

View file

@ -298,8 +298,8 @@ class AddUserJobTest extends AbstractTest
$token2text = Mailer::getMailsSent()[1]->tokens['token']; $token2text = Mailer::getMailsSent()[1]->tokens['token'];
$this->assert->areNotEqual($token1text, $token2text); $this->assert->areNotEqual($token1text, $token2text);
$token1 = TokenModel::findByToken($token1text); $token1 = TokenModel::getByToken($token1text);
$token2 = TokenModel::findByToken($token2text); $token2 = TokenModel::getByToken($token2text);
$this->assert->areEqual($user1->getId(), $token1->getUser()->getId()); $this->assert->areEqual($user1->getId(), $token1->getUser()->getId());
$this->assert->areEqual($user2->getId(), $token2->getUser()->getId()); $this->assert->areEqual($user2->getId(), $token2->getUser()->getId());

View file

@ -18,7 +18,7 @@ class EditCommentJobTest extends AbstractTest
$this->assert->isNotNull($comment->getCreationTime()); $this->assert->isNotNull($comment->getCreationTime());
$this->assert->doesNotThrow(function() use ($comment) $this->assert->doesNotThrow(function() use ($comment)
{ {
CommentModel::findById($comment->getId()); CommentModel::getById($comment->getId());
}); });
} }

View file

@ -8,7 +8,7 @@ class EditPostContentJobTest extends AbstractTest
$post = $this->uploadFromFile('image.jpg'); $post = $this->uploadFromFile('image.jpg');
$this->assert->doesNotThrow(function() use ($post) $this->assert->doesNotThrow(function() use ($post)
{ {
PostModel::findById($post->getId()); PostModel::getById($post->getId());
}); });
} }
@ -74,7 +74,7 @@ class EditPostContentJobTest extends AbstractTest
$post = $this->uploadFromUrl('image.jpg'); $post = $this->uploadFromUrl('image.jpg');
$this->assert->doesNotThrow(function() use ($post) $this->assert->doesNotThrow(function() use ($post)
{ {
PostModel::findById($post->getId()); PostModel::getById($post->getId());
}); });
} }
@ -99,7 +99,7 @@ class EditPostContentJobTest extends AbstractTest
$this->assert->doesNotThrow(function() use ($post) $this->assert->doesNotThrow(function() use ($post)
{ {
PostModel::findById($post->getId()); PostModel::getById($post->getId());
}); });
} }

View file

@ -13,7 +13,7 @@ class EditPostSourceJobTest extends AbstractTest
$this->assert->areEqual('a', $post->getSource()); $this->assert->areEqual('a', $post->getSource());
$this->assert->doesNotThrow(function() use ($post) $this->assert->doesNotThrow(function() use ($post)
{ {
PostModel::findById($post->getId()); PostModel::getById($post->getId());
}); });
} }

View file

@ -26,7 +26,7 @@ class ListCommentJobTest extends AbstractTest
$post = $ret->entities[0]; $post = $ret->entities[0];
$samePost = $this->assert->doesNotThrow(function() use ($post) $samePost = $this->assert->doesNotThrow(function() use ($post)
{ {
return PostModel::findById($post->getId()); return PostModel::getById($post->getId());
}); });
//posts retrieved via ListCommentsJob should already have cached its comments //posts retrieved via ListCommentsJob should already have cached its comments
$this->assert->areNotEquivalent($post, $samePost); $this->assert->areNotEquivalent($post, $samePost);

View file

@ -17,7 +17,7 @@ class PreviewCommentJobTest extends AbstractTest
$this->assert->isNotNull($comment->getCreationTime()); $this->assert->isNotNull($comment->getCreationTime());
$this->assert->throws(function() use ($comment) $this->assert->throws(function() use ($comment)
{ {
CommentModel::findById($comment->getId()); CommentModel::getById($comment->getId());
}, 'Invalid comment ID'); }, 'Invalid comment ID');
} }