Skip to content

Commit

Permalink
Separate chain calls (#455)
Browse files Browse the repository at this point in the history
  • Loading branch information
sankaest committed Jun 2, 2022
1 parent fc97733 commit e80ceb8
Show file tree
Hide file tree
Showing 30 changed files with 350 additions and 237 deletions.
8 changes: 6 additions & 2 deletions config/routes.php
Expand Up @@ -97,7 +97,9 @@
->middleware(
fn (HttpCache $httpCache, PostRepository $postRepository) =>
$httpCache->withLastModified(function (ServerRequestInterface $request, $params) use ($postRepository) {
return $postRepository->getMaxUpdatedAt()->getTimestamp();
return $postRepository
->getMaxUpdatedAt()
->getTimestamp();
})
)
->action([BlogController::class, 'index'])
Expand All @@ -120,7 +122,9 @@
fn (HttpCache $httpCache, PostRepository $postRepository, CurrentRoute $currentRoute) =>
$httpCache->withEtagSeed(function (ServerRequestInterface $request, $params) use ($postRepository, $currentRoute) {
$post = $postRepository->findBySlug($currentRoute->getArgument('slug'));
return $post->getSlug() . '-' . $post->getUpdatedAt()->getTimestamp();
return $post->getSlug() . '-' . $post
->getUpdatedAt()
->getTimestamp();
})
)
->action([PostController::class, 'index'])
Expand Down
4 changes: 3 additions & 1 deletion config/web/auth.php
Expand Up @@ -21,7 +21,9 @@

return [
IdentityRepositoryInterface::class => static function (ContainerInterface $container): IdentityRepository {
return $container->get(ORMInterface::class)->getRepository(Identity::class);
return $container
->get(ORMInterface::class)
->getRepository(Identity::class);
},

CookieMiddleware::class => static fn (CookieLogin $cookieLogin, LoggerInterface $logger) => new CookieMiddleware(
Expand Down
4 changes: 3 additions & 1 deletion config/web/comment-service.php
Expand Up @@ -13,7 +13,9 @@
/**
* @var CommentRepository $repository
*/
$repository = $container->get(ORMInterface::class)->getRepository(Comment::class);
$repository = $container
->get(ORMInterface::class)
->getRepository(Comment::class);

return new CommentService($repository);
},
Expand Down
4 changes: 3 additions & 1 deletion src/Auth/Controller/AuthController.php
Expand Up @@ -45,7 +45,9 @@ public function login(
if (
$request->getMethod() === Method::POST
&& $loginForm->load(is_array($body) ? $body : [])
&& $validator->validate($loginForm)->isValid()
&& $validator
->validate($loginForm)
->isValid()
) {
$identity = $this->authService->getIdentity();

Expand Down
4 changes: 3 additions & 1 deletion src/Auth/Controller/SignupController.php
Expand Up @@ -42,7 +42,9 @@ public function signup(
if (
$request->getMethod() === Method::POST
&& $signupForm->load(is_array($body) ? $body : [])
&& $validator->validate($signupForm)->isValid()
&& $validator
->validate($signupForm)
->isValid()
) {
return $this->redirectToMain();
}
Expand Down
4 changes: 3 additions & 1 deletion src/Auth/Form/LoginForm.php
Expand Up @@ -58,7 +58,9 @@ private function passwordRules(): array
$result = new Result();

if (!$this->authService->login($this->login, $this->password)) {
$this->getFormErrors()->addError('login', '');
$this
->getFormErrors()
->addError('login', '');
$result->addError($this->translator->translate('validator.invalid.login.password'));
}

Expand Down
4 changes: 3 additions & 1 deletion src/Auth/Form/SignupForm.php
Expand Up @@ -67,7 +67,9 @@ private function passwordVerifyRules(): array
function (): Result {
$result = new Result();
if ($this->password !== $this->passwordVerify) {
$this->getFormErrors()->addError('password', '');
$this
->getFormErrors()
->addError('password', '');
$result->addError($this->translator->translate('validator.password.not.match'));
}

Expand Down
4 changes: 3 additions & 1 deletion src/Blog/Archive/ArchiveController.php
Expand Up @@ -41,7 +41,9 @@ public function monthlyArchive(CurrentRoute $currentRoute, TagRepository $tagRep
'year' => $year,
'month' => $month,
'paginator' => $paginator,
'archive' => $archiveRepo->getFullArchive()->withLimit(12),
'archive' => $archiveRepo
->getFullArchive()
->withLimit(12),
'tags' => $tagRepository->getTagMentions(self::POPULAR_TAGS_COUNT),
];
return $this->viewRenderer->render('monthly-archive', $data);
Expand Down
40 changes: 26 additions & 14 deletions src/Blog/Archive/ArchiveRepository.php
Expand Up @@ -39,19 +39,28 @@ public function select(): Select

public function getMonthlyArchive(int $year, int $month): DataReaderInterface
{
$begin = (new \DateTimeImmutable())->setDate($year, $month, 1)->setTime(0, 0, 0);
$end = $begin->setDate($year, $month + 1, 1)->setTime(0, 0, -1);
$begin = (new \DateTimeImmutable())
->setDate($year, $month, 1)
->setTime(0, 0, 0);
$end = $begin
->setDate($year, $month + 1, 1)
->setTime(0, 0, -1);

$query = $this->select()
->andWhere('published_at', 'between', $begin, $end)
->load(['user', 'tags']);
$query = $this
->select()
->andWhere('published_at', 'between', $begin, $end)
->load(['user', 'tags']);
return $this->prepareDataReader($query);
}

public function getYearlyArchive(int $year): DataReaderInterface
{
$begin = (new \DateTimeImmutable())->setDate($year, 1, 1)->setTime(0, 0, 0);
$end = $begin->setDate($year + 1, 1, 1)->setTime(0, 0, -1);
$begin = (new \DateTimeImmutable())
->setDate($year, 1, 1)
->setTime(0, 0, 0);
$end = $begin
->setDate($year + 1, 1, 1)
->setTime(0, 0, -1);

$query = $this
->select()
Expand Down Expand Up @@ -89,7 +98,9 @@ public function getFullArchive(): DataReaderInterface
private function extractFromDateColumn(string $attr): FragmentInterface
{
$driver = $this->getDriver();
$wrappedField = $driver->getQueryCompiler()->quoteIdentifier($attr);
$wrappedField = $driver
->getQueryCompiler()
->quoteIdentifier($attr);
if ($driver instanceof SQLiteDriver) {
$str = ['year' => '%Y', 'month' => '%m', 'day' => '%d'][$attr];
return new Fragment("strftime('{$str}', post.published_at) {$wrappedField}");
Expand All @@ -99,12 +110,13 @@ private function extractFromDateColumn(string $attr): FragmentInterface

private function getDriver(): DriverInterface
{
return $this->select()
->getBuilder()
->getLoader()
->getSource()
->getDatabase()
->getDriver(DatabaseInterface::READ);
return $this
->select()
->getBuilder()
->getLoader()
->getSource()
->getDatabase()
->getDriver(DatabaseInterface::READ);
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/Blog/BlogController.php
Expand Up @@ -41,7 +41,9 @@ public function index(

$data = [
'paginator' => $paginator,
'archive' => $archiveRepo->getFullArchive()->withLimit(self::ARCHIVE_MONTHS_COUNT),
'archive' => $archiveRepo
->getFullArchive()
->withLimit(self::ARCHIVE_MONTHS_COUNT),
'tags' => $tagRepository->getTagMentions(self::POPULAR_TAGS_COUNT),
'isGuest' => $currentUser->isGuest(),
];
Expand Down
8 changes: 6 additions & 2 deletions src/Blog/Post/PostController.php
Expand Up @@ -56,7 +56,9 @@ public function add(Request $request, ValidatorInterface $validator): Response

if ($request->getMethod() === Method::POST) {
$form = new PostForm();
if ($form->load($parameters['body']) && $validator->validate($form)->isValid()) {
if ($form->load($parameters['body']) && $validator
->validate($form)
->isValid()) {
$this->postService->savePost($this->userService->getUser(), new Post(), $form);
return $this->webService->getRedirectResponse('blog/index');
}
Expand Down Expand Up @@ -93,7 +95,9 @@ public function edit(
if ($request->getMethod() === Method::POST) {
$form = new PostForm();
$body = $request->getParsedBody();
if ($form->load($body) && $validator->validate($form)->isValid()) {
if ($form->load($body) && $validator
->validate($form)
->isValid()) {
$this->postService->savePost($this->userService->getUser(), $post, $form);
return $this->webService->getRedirectResponse('blog/index');
}
Expand Down
12 changes: 9 additions & 3 deletions src/Blog/Post/PostRepository.php
Expand Up @@ -31,7 +31,8 @@ public function __construct(Select $select, EntityWriter $entityWriter)
*/
public function findAllPreloaded(): DataReaderInterface
{
$query = $this->select()
$query = $this
->select()
->load(['user', 'tags']);
return $this->prepareDataReader($query);
}
Expand Down Expand Up @@ -63,12 +64,17 @@ public function fullPostPage(string $slug): ?Post

public function getMaxUpdatedAt(): DateTimeInterface
{
return new DateTimeImmutable($this->select()->max('updated_at') ?? 'now');
return new DateTimeImmutable($this
->select()
->max('updated_at') ?? 'now');
}

public function findBySlug(string $slug): ?Post
{
return $this->select()->where(['slug' => $slug])->fetchOne();
return $this
->select()
->where(['slug' => $slug])
->fetchOne();
}

/**
Expand Down
18 changes: 12 additions & 6 deletions src/Blog/Tag/TagRepository.php
Expand Up @@ -33,9 +33,10 @@ public function getOrCreate(string $label): Tag

public function findByLabel(string $label): ?Tag
{
return $this->select()
->where(['label' => $label])
->fetchOne();
return $this
->select()
->where(['label' => $label])
->fetchOne();
}

/**
Expand Down Expand Up @@ -70,8 +71,11 @@ public function getTagMentions(int $limit = 0): DataReaderInterface
->select()
->buildQuery()
->columns(['t.label', 'count(*) count'])
->innerJoin('post', 'p')->on('p.id', 'postTag.post_id')->onWhere(['p.public' => true])
->innerJoin('tag', 't')->on('t.id', 'postTag.tag_id')
->innerJoin('post', 'p')
->on('p.id', 'postTag.post_id')
->onWhere(['p.public' => true])
->innerJoin('tag', 't')
->on('t.id', 'postTag.tag_id')
->groupBy('t.label, tag_id');

/**
Expand Down Expand Up @@ -132,6 +136,8 @@ public function getTagMentions(int $limit = 0): DataReaderInterface
->columns(['label', 'count(*) count']);

$sort = Sort::only(['count', 'label'])->withOrder(['count' => 'desc']);
return (new EntityReader($case3))->withSort($sort)->withLimit($limit);
return (new EntityReader($case3))
->withSort($sort)
->withLimit($limit);
}
}
14 changes: 10 additions & 4 deletions src/Blog/Widget/PostCard.php
Expand Up @@ -48,19 +48,25 @@ protected function renderHead(): string
$this->urlGenerator->generate('blog/post', ['slug' => $this->post->getSlug()]),
['class' => 'mb-0 h4 text-decoration-none'] // stretched-link
)
->render();
->render();
}

protected function renderBody(): string
{
$return = Html::openTag('div', ['class' => 'card-text mb-auto']);
$return .= $this->post->getPublishedAt() === null
? 'not published'
: $this->post->getPublishedAt()->format('M, d');
: $this->post
->getPublishedAt()
->format('M, d');
$return .= ' by ';
$return .= Html::a(
$this->post->getUser()->getLogin(),
$this->urlGenerator->generate('user/profile', ['login' => $this->post->getUser()->getLogin()])
$this->post
->getUser()
->getLogin(),
$this->urlGenerator->generate('user/profile', ['login' => $this->post
->getUser()
->getLogin()])
)->class('mb-1 text-muted');

$return .= Html::p(
Expand Down
4 changes: 3 additions & 1 deletion src/Command/Fixture/AddCommand.php
Expand Up @@ -97,7 +97,9 @@ private function addUsers(int $count): void
private function addTags(int $count): void
{
/** @var TagRepository $tagRepository */
$tagRepository = $this->promise->getORM()->getRepository(Tag::class);
$tagRepository = $this->promise
->getORM()
->getRepository(Tag::class);
$this->tags = [];
$tagWords = [];
for ($i = 0, $fails = 0; $i < $count; ++$i) {
Expand Down
4 changes: 3 additions & 1 deletion src/Contact/ContactController.php
Expand Up @@ -41,7 +41,9 @@ public function contact(
): ResponseInterface {
$body = $request->getParsedBody();
$form = new ContactForm();
if (($request->getMethod() === Method::POST) && $form->load((array)$body) && $validator->validate($form)->isValid()) {
if (($request->getMethod() === Method::POST) && $form->load((array)$body) && $validator
->validate($form)
->isValid()) {
$this->mailer->send($form, $request);

return $this->responseFactory
Expand Down
13 changes: 7 additions & 6 deletions src/Contact/ContactMailer.php
Expand Up @@ -40,12 +40,13 @@ public function __construct(

public function send(FormModelInterface $form, ServerRequestInterface $request)
{
$message = $this->mailer->compose(
'contact-email',
[
'content' => $form->getAttributeValue('body'),
]
)
$message = $this->mailer
->compose(
'contact-email',
[
'content' => $form->getAttributeValue('body'),
]
)
->withSubject($form->getAttributeValue('subject'))
->withFrom([$form->getAttributeValue('email') => $form->getAttributeValue('name')])
->withSender($this->sender)
Expand Down
4 changes: 3 additions & 1 deletion src/Handler/NotFoundHandler.php
Expand Up @@ -21,6 +21,8 @@ public function __construct(ViewRenderer $viewRenderer)

public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->viewRenderer->render('404')->withStatus(Status::NOT_FOUND);
return $this->viewRenderer
->render('404')
->withStatus(Status::NOT_FOUND);
}
}
6 changes: 4 additions & 2 deletions src/Middleware/LocaleMiddleware.php
Expand Up @@ -74,7 +74,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface

$response = $handler->handle($request);
if ($this->isDefaultLocale($locale, $country) && $request->getMethod() === 'GET') {
$response = $this->responseFactory->createResponse(Status::FOUND)
$response = $this->responseFactory
->createResponse(Status::FOUND)
->withHeader(Header::LOCATION, $newPath);
}
if ($this->enableSaveLocale) {
Expand All @@ -96,7 +97,8 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
$this->urlGenerator->setDefaultArgument($this->queryParameterName, $locale);

if ($request->getMethod() === 'GET') {
return $this->responseFactory->createResponse(Status::FOUND)
return $this->responseFactory
->createResponse(Status::FOUND)
->withHeader(Header::LOCATION, '/' . $locale . $path);
}

Expand Down
12 changes: 9 additions & 3 deletions src/User/Controller/ApiUserController.php
Expand Up @@ -36,12 +36,16 @@ public function __construct(DataResponseFactoryInterface $responseFactory)
*/
public function index(UserRepository $userRepository): ResponseInterface
{
$dataReader = $userRepository->findAll()->withSort(Sort::only(['login'])->withOrderString('login'));
$dataReader = $userRepository
->findAll()
->withSort(Sort::only(['login'])->withOrderString('login'));
$users = $dataReader->read();

$items = [];
foreach ($users as $user) {
$items[] = ['login' => $user->getLogin(), 'created_at' => $user->getCreatedAt()->format('H:i:s d.m.Y')];
$items[] = ['login' => $user->getLogin(), 'created_at' => $user
->getCreatedAt()
->format('H:i:s d.m.Y')];
}

return $this->responseFactory->createResponse($items);
Expand Down Expand Up @@ -71,7 +75,9 @@ public function profile(UserRepository $userRepository, CurrentRoute $currentRou
}

return $this->responseFactory->createResponse(
['login' => $user->getLogin(), 'created_at' => $user->getCreatedAt()->format('H:i:s d.m.Y')]
['login' => $user->getLogin(), 'created_at' => $user
->getCreatedAt()
->format('H:i:s d.m.Y')]
);
}
}

0 comments on commit e80ceb8

Please sign in to comment.