CommentsController   B
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 248
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 9
Bugs 6 Features 1
Metric Value
wmc 40
c 9
b 6
f 1
lcom 1
cbo 9
dl 0
loc 248
rs 8.2608

12 Methods

Rating   Name   Duplication   Size   Complexity  
A gEm() 0 4 1
C manageAction() 0 36 7
B ajaxInfo() 0 29 3
B renderResponse() 0 16 8
A postInfo() 0 10 1
A save() 0 7 1
A commentInfo() 0 11 3
B userInfo() 0 18 6
A messageFlash() 0 11 3
A error() 0 8 2
A getErrorsAsArray() 0 12 4
A returnAjaxErrors() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like CommentsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CommentsController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Mykees\CommentBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Response;
8
9
class CommentsController extends Controller
10
{
11
	private function gEm()
12
	{
13
		return $this->getDoctrine()->getManager();
14
	}
15
16
	/**
17
	 * Manage comment process
18
	 * @param Request $request
19
	 * @return \Symfony\Component\HttpFoundation\RedirectResponse
20
	 * @internal param $bundle
21
	 * @internal param $ref
22
	 * @internal param $ref_id
23
	 */
24
	public function manageAction(Request $request)
25
	{
26
		$params = [
27
			'manager'=>$this->get('mykees.comment.manager'),
28
			'session'=>$request->getSession(),
29
			'ref'    => $request->request->get('model') ? $request->request->get('model') : $request->request->get('mykees_comment')['model'],
30
			'ref_id' => $request->request->get('modelId') ? $request->request->get('modelId') : $request->request->get('mykees_comment')['modelId']
31
		];
32
33
		$comment_class_name = $this->container->getParameter('mykees_comment.comment.class');
34
		$comment_class = new $comment_class_name();
35
		$form = $this->createForm($this->get('mykees.comment.form'),$comment_class);
36
37
		if('POST' == $request->getMethod()) {
38
39
			if ($form->handleRequest($request)->isValid()) {
40
41
				if($request->isXmlHttpRequest()) {
42
					return $this->ajaxInfo($params,$request,$comment_class);
43
				}
44
45
				$this->postInfo($params, $request, $comment_class, $params['session']);
46
47
			}else{
48
49
				if($request->isXmlHttpRequest()) {
50
					return $this->returnAjaxErrors($form);
51
				}else{
52
					$this->error($request, $params['session']);
53
				}
54
			}
55
56
		}
57
58
		return $this->redirect($request->headers->get('referer') . '#comments_area');
59
	}
60
61
	/**
62
	 * @param $params
63
	 * @param $request
64
	 * @param $comment_class
65
	 * @return Response
66
	 */
67
	private function ajaxInfo($params,$request,$comment_class)
68
	{
69
70
		$comment = $this->postInfo($params, $request, $comment_class, $params['session']);
71
		$comment_depth = $this->container->getParameter('comment.depth');
72
73
		// Si la profondeur du commentaire parent est inférieure ou égale à la profondeur définis
74
		if($request->request->get('depth') < $comment_depth && $comment_depth >= 1)
75
		{
76
			$comment->setDepthReached($request->request->get('depth') + 1);//On incremente la profondeur max
77
			$comment->setDepth($comment->getId()); //la profondeur de réponse est égale a l'id
78
			$max_depth = false;
79
		}else{
80
			$comment->setDepthReached($request->request->get('depth'));//On à atteint la profondeur max
81
			$comment->setDepth($comment->getParentId());//la profondeur de réponse est éagle au commentaire parent
82
			$max_depth = true;
83
		}
84
85
		$template = $this->renderResponse($comment,$request,$max_depth);
86
		$json = json_encode([
87
			'template'=>$template,
88
			"parent_id"=>$comment->getParentId(),
89
			'comment_id'=>$comment->getId(),
90
			'max_depth'=>$max_depth,
91
			'success_message'=>$this->get('session')->getFlashBag()->get('comment_success')
92
		]);
93
94
		return new Response($json);
95
	}
96
97
	/**
98
	 * Return a template
99
	 * @param $comment
100
	 * @param $request
101
	 * @param $max_depth
102
	 * @return string
103
	 */
104
	private function renderResponse($comment,$request,$max_depth)
105
	{
106
		if($comment->getParentId() > 0)
107
		{
108
			if( ($request->request->get('response_type') === "true" && $max_depth === true) ||
109
				($request->request->get('response_type') === "false" && $max_depth === true) ||
110
				($request->request->get('response_type') === "true" && $max_depth === false)
111
			){
112
				return $this->renderView('MykeesCommentBundle:Comments:unwrap_replies.html.twig',['comment'=>$comment,'recent_reply'=>true]);
113
			}else{
114
				return $this->renderView('MykeesCommentBundle:Comments:replies.html.twig',['comment'=>$comment,'recent_reply'=>true]);
115
			}
116
		}else{
117
			return $this->renderView('MykeesCommentBundle:Comments:comment.html.twig',['comment'=>$comment,'recent_reply'=>true]);
118
		}
119
	}
120
121
122
	/**
123
	 * Init/save comment and user info
124
	 * @param $request
125
	 * @param $comment
126
	 * @param $params
127
	 * @param $session
128
	 * @return
129
	 */
130
	private function postInfo($params, $request, $comment, $session)
131
	{
132
		$this->userInfo($request, $comment);
133
		$this->commentInfo($params,$comment,$request,$params['ref_id']);
134
135
		$this->save($comment);
136
		$this->messageFlash($session);
137
138
		return $comment;
139
	}
140
141
	/**
142
	 * Save comment entity
143
	 * @param $comment
144
	 */
145
	private function save($comment)
146
	{
147
		$this->gEm()->persist($comment);
148
		$this->gEm()->flush();
149
150
		return $comment;
151
	}
152
153
	/**
154
	 * Init comment info
155
	 * @param $params
156
	 * @param $comment
157
	 * @param $request
158
	 * @param $ref_id
159
	 * @return mixed
160
	 */
161
	private function commentInfo($params,$comment,$request,$ref_id)
162
	{
163
		$comment->setIp($request->getClientIp());
164
		$comment->setModel($params['ref']);
165
		$comment->setModelId($ref_id);
166
		//Spam ?
167
		$akismet = $this->container->hasParameter('akismet') ? $this->container->getParameter('akismet') : null;
168
		$params['manager']->isSpam($comment,$request,$akismet) ? $comment->setSpam(1) : $comment->setSpam(0);
169
170
		return $comment;
171
	}
172
173
	/**
174
	 * Init user info
175
	 * @param $request
176
	 * @param $comment
177
	 * @return boo|\Symfony\Component\HttpFoundation\RedirectResponse
178
	 */
179
	private function userInfo($request, $comment)
180
	{
181
		$is_join = method_exists($comment,'getUser') ? true : false;
182
183
		if($this->getUser() !== null)
184
		{
185
			if($this->getUser()->getUsername() != $comment->getUsername() || $this->getUser()->getEmail() != $comment->getEmail())
186
			{
187
				return $this->redirect($request->headers->get('referer') . '#comments_area');
188
			}
189
			if($is_join)
190
			{
191
				$comment->setUser($this->getUser());
192
			}
193
		}
194
195
		return true;
196
	}
197
198
	/**
199
	 * Init message flash
200
	 * @param $session
201
	 * @return bool
202
	 */
203
	private function messageFlash($session)
204
	{
205
		$html = $session->has('success_message') ? $session->get('success_message') : "<strong>Merci!</strong> Votre message à bien été posté.";
206
		if($this->get('session')->getFlashBag()->has('comment_success'))
207
		{
208
			$this->get('session')->getFlashBag()->set('comment_success','');
209
		}
210
		$this->get('session')->getFlashBag()->add('comment_success',$html);
211
212
		return true;
213
	}
214
215
	/**
216
	 * @param $request
217
	 * @param $session
218
	 */
219
	private function error($request, $session)
220
	{
221
		$requestData = $request->request->get('mykees_comment');
222
		if(!empty($requestData))
223
		{
224
			$session->set('form_comment_data',$request->request->get('mykees_comment'));
225
		}
226
	}
227
228
	/**
229
	 * Get errors form for ajax
230
	 * @param $form
231
	 * @return array
232
	 */
233
	protected function getErrorsAsArray($form)
234
	{
235
		$errors = array();
236
		foreach ($form->getErrors() as $error)
237
			$errors[] = $error->getMessage();
238
239
		foreach ($form->all() as $key => $child) {
240
			if ($err = $this->getErrorsAsArray($child))
241
				$errors[$key] = $err;
242
		}
243
		return $errors;
244
	}
245
246
	/**
247
	 * Error message for Ajax
248
	 * @param $form
249
	 * @return Response
250
	 */
251
	private function returnAjaxErrors($form)
252
	{
253
		$json = json_encode(['error'=>'error','error_fields'=>$this->getErrorsAsArray($form)]);
254
		return new Response($json);
255
	}
256
}
257