Skip to content

Commit

Permalink
スラッグが設定されている記事にNOでアクセスした場合はリダイレクト fix #3946
Browse files Browse the repository at this point in the history
  • Loading branch information
seto1 authored Jan 23, 2025
1 parent db42022 commit b867cb1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
7 changes: 7 additions & 0 deletions plugins/bc-blog/src/Service/Front/BlogFrontService.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Cake\Datasource\EntityInterface;
use Cake\Datasource\Paging\PaginatedResultSet;
use Cake\Http\Exception\NotFoundException;
use Cake\Http\Exception\RedirectException;
use Cake\Http\ServerRequest;
use BaserCore\Annotation\UnitTest;
use BaserCore\Annotation\NoTodo;
Expand Down Expand Up @@ -372,6 +373,12 @@ public function getViewVarsForSingle(ServerRequest $request, EntityInterface $bl
$post->blog_content_id,
$post->id
] : '';

// スラッグが設定されている記事にNOでアクセスした場合はリダイレクト
if ($post->name && $post->name !== $no) {
$postUrl = $this->BlogPostsService->getUrl($post->blog_content->content, $post, true);
throw new RedirectException($postUrl);
}
}

// ナビゲーションを設定
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,15 @@ public function test_getViewVarsForSingle()
'title' => 'blog post title',
'status' => true
])->persist();
BlogPostFactory::make([
'id' => 2,
'blog_content_id' => 1,
'no' => 2,
'name' => 'slug-test',
'title' => 'blog post title2',
'blog_category_id' => BlogPostFactory::get(1)->get('blog_category_id'),
'status' => true
])->persist();
BlogCategoryFactory::make([
'id' => BlogPostFactory::get(1)->get('blog_category_id'),
'blog_content_id' => 1,
Expand Down Expand Up @@ -348,13 +357,38 @@ public function test_getViewVarsForSingle()
$this->assertEquals($rs['crumbs'], $crumbsExpected);


//$noが存在しない場合、
$this->expectException('Cake\Http\Exception\NotFoundException');
$this->BlogFrontService->getViewVarsForSingle(
$this->getRequest(),
// $noが存在しない場合
try {
$this->BlogFrontService->getViewVarsForSingle(
$this->getRequest(),
$BlogContentsService->get(1),
['blog', 'test']
);
$this->fail();
} catch (\Exception $e) {
$this->assertSame('Cake\Http\Exception\NotFoundException', get_class($e));
}

// スラッグが設定されている記事にスラッグでアクセス
$result = $this->BlogFrontService->getViewVarsForSingle(
$request->withParam('pass', ['slug-test']),
$BlogContentsService->get(1),
['blog', 'test']
);
$this->assertEquals($result['post']->title, 'blog post title2');

// スラッグが設定されている記事にNOでアクセス
try {
$this->BlogFrontService->getViewVarsForSingle(
$request->withParam('pass', ['2']),
$BlogContentsService->get(1),
['blog', 'test']
);
$this->fail();
} catch (\Exception $e) {
$this->assertEquals('https://localhost/archives/slug-test', $e->getMessage());
$this->assertSame('Cake\Http\Exception\RedirectException', get_class($e));
}
}

/**
Expand Down

0 comments on commit b867cb1

Please sign in to comment.