Skip to content

Instantly share code, notes, and snippets.

@norberttech
Created April 22, 2015 11:50
Show Gist options
  • Select an option

  • Save norberttech/426a9bdaceabbb291a2e to your computer and use it in GitHub Desktop.

Select an option

Save norberttech/426a9bdaceabbb291a2e to your computer and use it in GitHub Desktop.
<?php
class BlogController extends Controller
{
/**
* @Route("/comment/{postSlug}/new", name = "comment_new")
* @Security("is_granted('IS_AUTHENTICATED_FULLY')")
*
* @Method("POST")
* @ParamConverter("post", options={"mapping": {"postSlug": "slug"}})
*/
public function commentAction(Request $request, Post $post)
{
$form = $this->createCommentForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getUser()->comment($post, $form->get('content')->getData());
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('blog_post', array('slug' => $post->getSlug()));
}
return $this->render('blog/comment_form_error.html.twig', array(
'post' => $post,
'form' => $form->createView(),
));
}
}
<?php
class Comment
{
private $author;
private $content;
private $createdAt;
private $lastUpdatedAt;
public function __construct(User $author, Content $content, \DateTime $createdAt)
{
$this->author = $author;
$this->content = $content;
$this->createdAt = $createdAt;
}
public function wasCreatedBy(User $user)
{
return $this->user->isEqualTo($user);
}
public function updateContent(Content $newContent)
{
$this->content = $newContent;
$this->lastUpdatedAt = new \DateTime();
}
}
<?php
class Content
{
private $value;
public function __construct($value)
{
if (empty($value)) {
throw new \InvalidArgumentException("Post comment content can't be empty.");
}
$this->value = $value;
}
public function __toString()
{
return $this->value;
}
}
<?php
class Post
{
public function addComment(Content $content, User $author)
{
$this->comments->add(new Comment($author, $content, new DateTime()));
}
}
<?php
class User
{
public function comment(Post $post, $content)
{
if (!$post->canBeCommented()) {
throw new \RuntimeException("Post can't be commented.");
}
$post->addComment(new Content($content), $this);
}
public function updateComment(Comment $comment, $content)
{
if ($comment->wasCreatedByUser($this)) {
throw new \RuntimeException("You can not update not your comments.");
}
$comment->updateContent(new Content($content));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment