Completed
Push — master ( b71929...bf05f4 )
by Jacob
10:14
created

get_comments_for_post_from_service()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 33
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
rs 8.8571
cc 2
eloc 26
nc 2
nop 1
1
<?
0 ignored issues
show
Security Best Practice introduced by
It is not recommend to use PHP's short opening tag <?, better use <?php, or <?= in case of outputting.

Short opening tags are disabled in PHP’s default configuration. In such a case, all content of this file is output verbatim to the browser without being parsed, or executed.

As a precaution to avoid these problems better use the long opening tag <?php.

Loading history...
2
3
Loader::load('collector', 'comment/CommentCollector');
4
5
Loader::load('controller', '/PageController');
6
Loader::load('utility', 'Content');
7
8
abstract class DefaultPageController extends PageController
9
{
10
11
	private static $RECENT_COMMENT_COUNT = 10;
12
	private static $MINIMUM_TAG_COUNT = 10;
13
	protected static $LENGTH_OF_TRIMMED_POST = 300;
14
15
	protected static $BLOG_SITE_ID = 2;
16
17
	private static $INTRODUCTION_IMAGE_PATTERN = '<img src="/photo/%s/%s-size-%s.jpg" height="%d" width="%d" alt="%s" />';
18
19
	protected function set_head_data()
20
	{
21
    $this->set_head('rss_link', [
22
      'title' => 'Jacob Emerick Blog Feed',
23
      'url' => '/rss.xml'
24
    ]);
25
    $this->set_head('rss_comment_link', [
26
      'title' => 'Jacob Emerick Blog Comment Feed',
27
      'url' => '/rss-comments.xml'
28
    ]);
29
		
30
		$this->add_css('normalize');
31
		$this->add_css('blog');
32
	}
33
34
	protected function get_introduction()
35
	{
36
		return;
37
	}
38
39
	protected function get_introduction_image($id)
40
	{
41
		Loader::load('collector', 'image/PhotoCollector');
42
		$photo_result = PhotoCollector::getRow($id);
43
		
44
		if($photo_result == null)
45
			return;
46
		
47
		$name = $photo_result->name;
48
		$category = $photo_result->category;
49
		$size = 'medium';
50
		$height = 375;
51
		$width = 500;
52
		$description = $photo_result->description;
53
		
54
		return sprintf(self::$INTRODUCTION_IMAGE_PATTERN, $category, $name, $size, $height, $width, $description);
55
	}
56
57
	protected function set_body_data()
58
	{
59
		$this->set_body('introduction', $this->get_introduction());
60
		$this->set_body('right_side', $this->get_right_side());
61
		$this->set_body('activity_array', $this->get_recent_activity());
62
		
63
		$this->set_body_view('Page');
64
	}
65
66
	final protected function format_post($post, $trim = false)
67
	{
68
		$post_object = new stdclass();
69
		
70
		$post_object->title = $post['title'];
71
		$post_object->path = "/{$post['category']}/{$post['path']}/";
72
		$post_object->category = ucwords(str_replace('-', ' ', $post['category']));
73
		$post_object->category_link = "/{$post['category']}/";
74
		// $post_object->comment_count = $this->get_comments_for_post($post);
75
		$post_object->tags = $this->get_tags_for_post($post);
76
		$post_object->image = Content::instance('FetchFirstPhoto', $post['body'])->activate(false, 'small');
77
		$post_object->body = $this->get_body_for_post($post, $trim);
78
		$post_object->date = $this->get_parsed_date($post['date']);
79
80
		return $post_object;
81
	}
82
83
	final private function get_comments_for_post($post)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
84
	{
85
		$count = CommentCollector::getCommentCountForURL(self::$BLOG_SITE_ID, $post['path']);
86
    $count_from_service = $this->get_comments_for_post_from_service($post);
87
88
    if ($count_from_service !== null && $count_from_service != $count) {
89
        global $container;
90
        $container['console']->log('Mismatch between comment service and legacy db');
91
        $container['console']->log("{$count}, {$count_from_service} in service");
92
    }
93
    return $count;
94
	}
95
96
    final private function get_comments_for_post_from_service($post)
97
    {
98
        global $config;
99
        $configuration = new Jacobemerick\CommentService\Configuration();
100
        $configuration->setUsername($config->comments->user);
101
        $configuration->setPassword($config->comments->password);
102
        $configuration->addDefaultHeader('Content-Type', 'application/json');
103
        $configuration->setHost($config->comments->host);
104
        $configuration->setCurlTimeout($config->comments->timeout);
105
106
        $client = new Jacobemerick\CommentService\ApiClient($configuration);
107
        $api = new Jacobemerick\CommentService\Api\DefaultApi($client);
108
109
        $start = microtime(true);
110
        try {
111
            $comment_response = $api->getComments(
112
                null,
113
                null,
114
                null,
115
                'blog.jacobemerick.com',
116
                "{$post['category']}/{$post['path']}"
117
            );
118
        } catch (Exception $e) {
119
            global $container;
120
            $container['logger']->warning("CommentService | Comment Count | {$e->getMessage()}");
121
            return;
122
        }
123
        $elapsed = microtime(true) - $start;
124
        global $container;
125
        $container['logger']->info("CommentService | Comment Count | {$elapsed}");
126
127
        return count($comment_response);
128
    }
129
130
	final private function get_tags_for_post($post)
131
	{
132
        global $container;
133
        $repository = new Jacobemerick\Web\Domain\Blog\Tag\MysqlTagRepository($container['db_connection_locator']);
134
        $tag_result = $repository->getTagsForPost($post['id']);
135
136
        $tag_array = array();
137
		foreach($tag_result as $tag)
138
		{
139
			$tag_object = new stdclass();
140
			$tag_object->name = $tag['tag'];
141
			$tag_object->link = Content::instance('URLSafe', "/tag/{$tag['tag']}/")->activate();
142
			$tag_array[] = $tag_object;
143
		}
144
		return $tag_array;
145
	}
146
147
	final private function get_body_for_post($post, $trim)
148
	{
149
		$body = $post['body'];
150
		
151
		if($trim)
152
			$body = Content::instance('SmartTrim', $body)->activate(self::$LENGTH_OF_TRIMMED_POST);
153
		
154
		$body = Content::instance('FixPhoto', $body)->activate(false, 'standard');
155
		$body = Content::instance('MarkupCode', $body)->activate();
156
		
157
		return $body;
158
	}
159
160
	final protected function get_right_side()
161
	{
162
		$side_array = array();
163
		$side_array['tags'] = $this->get_tag_cloud();
164
		$side_array['comments'] = $this->get_comments();
165
		return $side_array;
166
	}
167
168
	final private function get_tag_cloud()
169
	{
170
        global $container;
171
        $repository = new Jacobemerick\Web\Domain\Blog\Tag\MysqlTagRepository($container['db_connection_locator']);
172
        $tag_result = $repository->getTagCloud();
173
		
174
		$maximum_tag_count = $this->get_maximum_tag_count($tag_result);
175
		
176
		$cloud_array = array();
177
		foreach($tag_result as $tag)
178
		{
179
			if($tag['count'] < self::$MINIMUM_TAG_COUNT)
180
				continue;
181
			
182
			$tag_object = new stdclass();
183
			$tag_object->name = $tag['tag'];
184
			$tag_object->link = Content::instance('URLSafe', "/tag/{$tag['tag']}/")->activate();
185
			$tag_object->scalar = floor(($tag['count'] - 1) * (9 / ($maximum_tag_count - self::$MINIMUM_TAG_COUNT)));
186
			$cloud_array[] = $tag_object;
187
		}
188
		
189
		return $cloud_array;
190
	}
191
192
	final private function get_maximum_tag_count($tag_result)
193
	{
194
		$maximum = 1;
195
		
196
		foreach($tag_result as $tag)
197
		{
198
			if($tag['count'] > $maximum)
199
				$maximum = $tag['count'];
200
		}
201
		return $maximum;
202
	}
203
204
	final private function get_comments()
205
	{
206
		$comment_array = CommentCollector::getRecentBlogComments(self::$RECENT_COMMENT_COUNT);
207
		
208
		$array = array();
209
		foreach($comment_array as $comment)
0 ignored issues
show
Bug introduced by
The expression $comment_array of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
210
		{
211
			$body = $comment->body;
212
			$body = strip_tags($body);
213
			
214
			$comment_obj = new stdclass();
215
			$comment_obj->description = Content::instance('SmartTrim', $body)->activate(30);
216
			$comment_obj->commenter = $comment->name;
217
			$comment_obj->link = Loader::getRootURL() . "{$comment->category}/{$comment->path}/#comment-{$comment->id}";
218
			$array[] = $comment_obj;
219
		}
220
221
    $comment_service_array = $this->get_comments_from_service();
222
    if ($comment_service_array !== null && $comment_service_array !== $array) {
223
      global $container;
224
      $container['console']->log('Mismatch between comment service and legacy db');
225
      $container['console']->log($comment_service_array[0]);
226
      $container['console']->log($array[0]);
227
    }
228
		return $array;
229
	}
230
231
    final private function get_comments_from_service()
232
    {
233
        global $config;
234
        $configuration = new Jacobemerick\CommentService\Configuration();
235
        $configuration->setUsername($config->comments->user);
236
        $configuration->setPassword($config->comments->password);
237
        $configuration->addDefaultHeader('Content-Type', 'application/json');
238
        $configuration->setHost($config->comments->host);
239
        $configuration->setCurlTimeout($config->comments->timeout);
240
241
        $client = new Jacobemerick\CommentService\ApiClient($configuration);
242
        $api = new Jacobemerick\CommentService\Api\DefaultApi($client);
243
244
        $start = microtime(true);
245
        try {
246
            $comment_response = $api->getComments(
247
                1,
248
                self::$RECENT_COMMENT_COUNT,
249
                '-date',
250
                'blog.jacobemerick.com'
251
            );
252
        } catch (Exception $e) {
253
            global $container;
254
            $container['logger']->warning("CommentService | Sidebar | {$e->getMessage()}");
255
            return;
256
        }
257
 
258
        $elapsed = microtime(true) - $start;
259
        global $container;
260
        $container['logger']->info("CommentService | Sidebar | {$elapsed}");
261
262
        $array = array();
263
        foreach($comment_response as $comment)
264
        {
265
            $body = $comment->getBody();
266
            $body = Content::instance('CleanComment', $body)->activate();
267
            $body = strip_tags($body);
268
269
            $comment_obj = new stdclass();
270
            $comment_obj->description = Content::instance('SmartTrim', $body)->activate(30);
271
            $comment_obj->commenter = $comment->getCommenter()->getName();
272
            $comment_obj->link = "{$comment->getUrl()}/#comment-{$comment->getId()}";
273
            $array[] = $comment_obj;
274
        }
275
        return $array;
276
    }
277
278
}
279