11<?php namespace Lio \Forum \Threads ;
22
3+ use Illuminate \Support \MessageBag ;
4+ use Lio \Accounts \User ;
5+ use Lio \Validators \DoesNotContainPhoneNumbers ;
6+
37/**
48* This class can call the following methods on the listener object:
59*
812*/
913class ThreadCreator
1014{
15+ /**
16+ * @var \Lio\Forum\Threads\ThreadRepository
17+ */
1118 protected $ threads ;
1219
13- public function __construct (ThreadRepository $ threads )
20+ /**
21+ * @var \Lio\Validators\DoesNotContainPhoneNumbers
22+ */
23+ protected $ phoneNumbers ;
24+
25+ /**
26+ * @param \Lio\Forum\Threads\ThreadRepository $threads
27+ * @param \Lio\Validators\DoesNotContainPhoneNumbers $phoneNumbers
28+ */
29+ public function __construct (ThreadRepository $ threads , DoesNotContainPhoneNumbers $ phoneNumbers )
1430 {
1531 $ this ->threads = $ threads ;
32+ $ this ->phoneNumbers = $ phoneNumbers ;
1633 }
1734
1835 // an additional validator is optional and will be run first, an example of a usage for
@@ -41,8 +58,24 @@ private function getNew($data)
4158
4259 private function validateAndSave ($ thread , $ listener , $ data )
4360 {
61+ if ($ this ->containsSpam ($ thread ->subject )) {
62+ $ this ->increaseUserSpamCount ($ thread ->author );
63+
64+ return $ listener ->threadCreationError (
65+ new MessageBag (['subject ' => 'Title contains spam. Your account has been flagged. ' ])
66+ );
67+ }
68+
69+ if ($ this ->containsSpam ($ thread ->body )) {
70+ $ this ->increaseUserSpamCount ($ thread ->author );
71+
72+ return $ listener ->threadCreationError (
73+ new MessageBag (['body ' => 'Body contains spam. Your account has been flagged. ' ])
74+ );
75+ }
76+
4477 // check the model validation
45- if ( ! $ this ->threads ->save ($ thread )) {
78+ if (! $ this ->threads ->save ($ thread )) {
4679 return $ listener ->threadCreationError ($ thread ->getErrors ());
4780 }
4881
@@ -53,4 +86,33 @@ private function validateAndSave($thread, $listener, $data)
5386
5487 return $ listener ->threadCreated ($ thread );
5588 }
89+
90+ /**
91+ * Determines if one or more subject contain spam
92+ *
93+ * @param string|array $subject
94+ * @return bool
95+ */
96+ private function containsSpam ($ subject )
97+ {
98+ // If the validator detects phone numbers, return false.
99+ return ! $ this ->phoneNumbers ->validate ($ subject );
100+ }
101+
102+ /**
103+ * Increases a user's spam count
104+ *
105+ * @param \Lio\Accounts\User $user
106+ */
107+ private function increaseUserSpamCount (User $ user )
108+ {
109+ $ user ->spam_count = $ user ->spam_count + 1 ;
110+
111+ // If the user reaches a spam threshold of 3 or more, automatically ban him
112+ if ($ user ->spam_count >= 3 ) {
113+ $ user ->is_banned = true ;
114+ }
115+
116+ $ user ->save ();
117+ }
56118}
0 commit comments