Completed
Pull Request — master (#1)
by Jacob
15:50
created

PageController::expand_post()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 17
rs 9.4286
cc 3
eloc 10
nc 4
nop 2
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('utility', 'Header');
4
5
abstract class PageController
6
{
7
8
	private static $TRACKING_CODE = 'UA-11745070-1';
9
	
10
	protected static $DEPRECATED_BLOGS = array(
11
		10 => 63,
12
		55 => 67,
13
	);
14
15
	private $headers;
16
	private $css_array = array();
17
	private $font_css_array = array();
0 ignored issues
show
Unused Code introduced by
The property $font_css_array is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
18
	private $js_array = array();
19
20
	private $data_array = array();
21
	private $body_view_array = array();
22
23
	protected function set_head_data() {}
24
	protected function set_body_data() {}
25
	protected function set_data() {}
26
27
	public function __construct()
28
	{
29
		$this->set_header_method('sendHTML');
30
		
31
		$this->set_head('google_verification', 'sgAISiuoWfK54KXnOfm2oU4vQdad8eyNCQX7LkZ1OxM');
32
		$this->set_head('bing_verification', 'AF1A4CEA30A7589590E9294C4B512607');
33
		
34
		$this->set_body('domain_container', $this->get_domain_container());
35
		$this->set_body('footer', array(
36
			'link' => Loader::getRootUrl('site'),
37
			'anchor' => 'jacobemerick.com',
38
			'date' => date('Y')));
39
		
40
		Loader::loadInstance('utility', 'Database');
41
		if(Database::isConnected() === false)
42
			$this->unavailable();
43
	}
44
45
	protected function get_domain_container()
46
	{
47
		$domain_container = new stdclass();
48
		
49
		$domain_container->blog = Loader::getRootUrl('blog');
50
		$domain_container->home = Loader::getRootUrl('home');
51
		$domain_container->lifestream = Loader::getRootUrl('lifestream');
52
		$domain_container->map = Loader::getRootUrl('map');
53
		$domain_container->portfolio = Loader::getRootUrl('portfolio');
54
		$domain_container->waterfalls = Loader::getRootUrl('waterfalls');
55
		
56
		return $domain_container;
57
	}
58
59
    protected function get_recent_activity()
60
    {
61
        global $container;
62
        $activityRepository = new Jacobemerick\Web\Domain\Stream\Activity\MysqlActivityRepository($container['db_connection_locator']);
63
        $post_result = $activityRepository->getActivities(5);
64
65
        $post_array = array();
66
        foreach($post_result as $row) {
0 ignored issues
show
Bug introduced by
The expression $post_result 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...
67
            array_push($post_array, $this->expand_post($row));
68
        }
69
70
        return $post_array;
71
    }
72
73
    protected function expand_post($raw_post, $format = 'short')
74
    {
75
        $post = [
76
            'type' => $raw_post['type'],
77
            'title' => ($format == 'short') ? $raw_post['message'] : $raw_post['message_long'],
78
            'date' => $this->get_parsed_date($raw_post['datetime']),
79
        ];
80
81
        if ($format != 'short') {
82
            $post['url'] = Loader::getRootUrl('lifestream') . "{$raw_post['type']}/{$raw_post['id']}/";
83
84
            $metadata = json_decode($raw_post['metadata'], true);
85
            $post = array_merge($post, $metadata);
86
        }
87
88
        return (object) $post;
89
    }
90
91
	public function activate()
92
	{
93
		$this->set_head_data();
94
		$this->set_body_data();
95
		$this->set_data();
96
		
97
		$this->load_assets();
98
		
99
		$headers = $this->headers;
100
		Header::$headers();
101
		Loader::load('view', '/Head', $this->data_array['head']);
102
		foreach($this->body_view_array as $view)
103
		{
104
			if(substr($view, 0, 1) == '/')
105
				Loader::load('view', $view, $this->data_array['body']);
106
			else
107
				Loader::load('view', URLDecode::getSite() . '/' . $view, $this->data_array['body']);
108
		}
109
        
110
        if (URLDecode::getSite() == 'waterfalls') {
111
            Loader::load('view', '/WaterfallFoot');
112
        } else {
113
            Loader::load('view', '/Foot', array('tracking_code' => self::$TRACKING_CODE));
114
        }
115
		
116
		if($view == '/404' || $view == '/503')
0 ignored issues
show
Bug introduced by
The variable $view seems to be defined by a foreach iteration on line 102. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
117
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
118
	}
119
120
	protected function set_header_method($method)
121
	{
122
		$this->headers = $method;
123
	}
124
125
	protected function set_title($value)
126
	{
127
		$this->set_head('title', $value);
128
	}
129
130
	protected function set_author($value)
131
	{
132
		$this->set_head('author', $value);
133
	}
134
135
	protected function set_description($value)
136
	{
137
		$this->set_head('description', $value);
138
	}
139
140
	protected function set_keywords($array)
141
	{
142
		$this->set_head('keywords', implode(', ', $array));
143
	}
144
	
145
	protected function set_canonical($url)
146
	{
147
		$this->set_head('canonical', $url);
148
	}
149
150
	protected function set_head($set, $value)
151
	{
152
		$this->data_array['head'][$set] = $value;
153
	}
154
155
	protected function set_body($set, $value)
156
	{
157
		$this->data_array['body'][$set] = $value;
158
	}
159
160
	protected function add_css($file, $version = 1)
161
	{
162
		$this->css_array[] = [$file, $version];
163
	}
164
165
	protected function add_js($file)
166
	{
167
		$this->js_array[] = $file;
168
	}
169
170
	private function load_assets()
171
	{
172
    $css_array = array_map(function ($stylesheet) {
173
      $path = "/css/{$stylesheet[0]}.css";
174
      if ($stylesheet[1] > 1) {
175
        $path .= "?v={$stylesheet[1]}";
176
      }
177
      return $path;
178
    }, $this->css_array);
179
    $js_array = array_map(function ($script) {
180
      if (substr($script, 0, 4) == 'http') {
181
        return $script;
182
      }
183
      return "/js/{$script}.min.js";
184
    }, $this->js_array);
185
		
186
		$this->set_head('css_link_array', $css_array);
187
		$this->set_head('js_link_array', $js_array);
188
	}
189
190
	protected function set_body_view($view)
191
	{
192
		$this->body_view_array[] = $view;
193
	}
194
195
	protected function eject()
196
	{
197
		if(get_class($this) !== 'Error404Controller')
198
			Loader::loadNew('controller', '/Error404Controller')->activate();
199
	}
200
201
	protected function unavailable()
202
	{
203
		if(get_class($this) !== 'Error503Controller')
204
			Loader::loadNew('controller', '/Error503Controller')->activate();
205
	}
206
207
	protected function redirect($uri, $method = 301)
208
	{
209
		switch($method)
210
		{
211 View Code Duplication
			case 301 :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212
				if(get_class($this) !== 'Error301Controller')
213
					Loader::loadNew('controller', '/Error301Controller', array($uri))->activate();
214
				break;
215 View Code Duplication
			case 303 :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
216
				if(get_class($this) !== 'Error303Controller')
217
					Loader::loadNew('controller', '/Error303Controller', array($uri))->activate();
218
				break;
219
		}
220
	}
221
222
	final protected function get_parsed_date($date)
223
	{
224
		$parsed_date = new stdclass();
225
		
226
		$parsed_date->stamp = date('c', strtotime($date));
227
		$parsed_date->friendly = date('F j, Y', strtotime($date));
228
		$parsed_date->elapsed = Content::instance('ElapsedTime', $date)->activate();
229
		
230
		return $parsed_date;
231
	}
232
233
	private $comment_errors;
234
	protected function handle_comment_submit($site_id, $path, $redirect_url, $page_title)
235
	{
236
		if(Request::hasPost() && Request::getPost('submit') == 'Submit Comment')
237
		{
238
			$parameters = array($site_id, $path, $redirect_url, $page_title);
239
			$this->comment_errors = Loader::loadNew('module', 'form/CommentSubmitModule', $parameters)->activate();
240
		}
241
		
242
		return;
243
	}
244
245
	protected function get_comment_array($site, $path)
246
	{
247
		Loader::load('collector', 'comment/CommentCollector');
248
		
249
		$commenter = $this->get_commenter();
250
		
251
		$comment_array = array();
252
		$comment_result = CommentCollector::getCommentsForURL($site, $path, $commenter->id);
253
		
254
		foreach($comment_result as $comment)
0 ignored issues
show
Bug introduced by
The expression $comment_result 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...
255
		{
256
			$comment_object = new stdclass();
257
			$comment_object->id = $comment->id;
258
			$comment_object->body = $comment->body_format;
259
			$comment_object->date = date("M j, 'y", strtotime($comment->date));
260
			$comment_object->name = $comment->name;
261
			$comment_object->url = $comment->url;
262
			$comment_object->trusted = $comment->trusted;
263
			
264
			if($comment->reply == 0 && Request::getPost('type') == $comment->id)
265
				$comment_object->errors = $this->comment_errors;
266
			else
267
				$comment_object->errors = array();
268
			
269
			if($comment->reply == 0)
270
			{
271
				$comment_object->replies = array();
272
				$comment_array[$comment->id] = $comment_object;
273
			}
274
			else
275
				$comment_array[$comment->reply]->replies[$comment->id] = $comment_object;
276
		}
277
		
278
		$comment_count = CommentCollector::getCommentCountForURL($site, $path);
279
		
280
		return array(
281
			'comments' => $comment_array,
282
			'commenter' => $commenter,
283
			'errors' => $this->comment_errors,
284
			'comment_count' => $comment_count);
285
	}
286
287
	private function get_commenter()
288
	{
289
		Loader::load('collector', 'comment/CommentCollector');
290
		Loader::load('utility', 'Cookie');
291
		
292
		$commenter = new stdclass();
293
		
294
		$commenter->id = 0;
295
		$commenter->name = '';
296
		$commenter->email = '';
297
		$commenter->website = '';
298
		
299
		$commenter_cookie = Cookie::instance('Commenter');
300
		if(!$commenter_cookie->exists())
301
			return $commenter;
302
		
303
		$commenter_cookie_value = $commenter_cookie->getValue();
304
		$commenter_cookie_value = json_decode($commenter_cookie_value);
305
		
306
		if($commenter_cookie_value === NULL)
307
			return $commenter;
308
		
309
		if(!isset($commenter_cookie_value->name) || !isset($commenter_cookie_value->email))
310
			return $commenter;
311
		
312
		$commenter_object = CommentCollector::getCommenterByFields($commenter_cookie_value->name, $commenter_cookie_value->email, (isset($commenter_cookie_value->website) ? $commenter_cookie_value->website : ''));
313
		
314
		if($commenter_object === NULL)
315
			return $commenter;
316
		
317
		$commenter->id = $commenter_object->id;
318
		$commenter->name = $commenter_object->name;
319
		$commenter->email = $commenter_object->email;
320
		$commenter->website = $commenter_object->url;
321
		
322
		return $commenter;
323
	}
324
325
}
326