Completed
Pull Request — master (#1)
by Jacob
03:28
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)
161
	{
162
		$this->css_array[] = $file;
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
      return "/css/{$stylesheet}.css";
174
    }, $this->css_array);
175
    $js_array = array_map(function ($script) {
176
      if (substr($script, 0, 4) == 'http') {
177
        return $script;
178
      }
179
      return "/js/{$script}.min.js";
180
    }, $this->js_array);
181
		
182
		$this->set_head('css_link_array', $css_array);
183
		$this->set_head('js_link_array', $js_array);
184
	}
185
186
	protected function set_body_view($view)
187
	{
188
		$this->body_view_array[] = $view;
189
	}
190
191
	protected function eject()
192
	{
193
		if(get_class($this) !== 'Error404Controller')
194
			Loader::loadNew('controller', '/Error404Controller')->activate();
195
	}
196
197
	protected function unavailable()
198
	{
199
		if(get_class($this) !== 'Error503Controller')
200
			Loader::loadNew('controller', '/Error503Controller')->activate();
201
	}
202
203
	protected function redirect($uri, $method = 301)
204
	{
205
		switch($method)
206
		{
207 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...
208
				if(get_class($this) !== 'Error301Controller')
209
					Loader::loadNew('controller', '/Error301Controller', array($uri))->activate();
210
				break;
211 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...
212
				if(get_class($this) !== 'Error303Controller')
213
					Loader::loadNew('controller', '/Error303Controller', array($uri))->activate();
214
				break;
215
		}
216
	}
217
218
	final protected function get_parsed_date($date)
219
	{
220
		$parsed_date = new stdclass();
221
		
222
		$parsed_date->stamp = date('c', strtotime($date));
223
		$parsed_date->friendly = date('F j, Y', strtotime($date));
224
		$parsed_date->elapsed = Content::instance('ElapsedTime', $date)->activate();
225
		
226
		return $parsed_date;
227
	}
228
229
	private $comment_errors;
230
	protected function handle_comment_submit($site_id, $path, $redirect_url, $page_title)
231
	{
232
		if(Request::hasPost() && Request::getPost('submit') == 'Submit Comment')
233
		{
234
			$parameters = array($site_id, $path, $redirect_url, $page_title);
235
			$this->comment_errors = Loader::loadNew('module', 'form/CommentSubmitModule', $parameters)->activate();
236
		}
237
		
238
		return;
239
	}
240
241
	protected function get_comment_array($site, $path)
242
	{
243
		Loader::load('collector', 'comment/CommentCollector');
244
		
245
		$commenter = $this->get_commenter();
246
		
247
		$comment_array = array();
248
		$comment_result = CommentCollector::getCommentsForURL($site, $path, $commenter->id);
249
		
250
		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...
251
		{
252
			$comment_object = new stdclass();
253
			$comment_object->id = $comment->id;
254
			$comment_object->body = $comment->body_format;
255
			$comment_object->date = date("M j, 'y", strtotime($comment->date));
256
			$comment_object->name = $comment->name;
257
			$comment_object->url = $comment->url;
258
			$comment_object->trusted = $comment->trusted;
259
			
260
			if($comment->reply == 0 && Request::getPost('type') == $comment->id)
261
				$comment_object->errors = $this->comment_errors;
262
			else
263
				$comment_object->errors = array();
264
			
265
			if($comment->reply == 0)
266
			{
267
				$comment_object->replies = array();
268
				$comment_array[$comment->id] = $comment_object;
269
			}
270
			else
271
				$comment_array[$comment->reply]->replies[$comment->id] = $comment_object;
272
		}
273
		
274
		$comment_count = CommentCollector::getCommentCountForURL($site, $path);
275
		
276
		return array(
277
			'comments' => $comment_array,
278
			'commenter' => $commenter,
279
			'errors' => $this->comment_errors,
280
			'comment_count' => $comment_count);
281
	}
282
283
	private function get_commenter()
284
	{
285
		Loader::load('collector', 'comment/CommentCollector');
286
		Loader::load('utility', 'Cookie');
287
		
288
		$commenter = new stdclass();
289
		
290
		$commenter->id = 0;
291
		$commenter->name = '';
292
		$commenter->email = '';
293
		$commenter->website = '';
294
		
295
		$commenter_cookie = Cookie::instance('Commenter');
296
		if(!$commenter_cookie->exists())
297
			return $commenter;
298
		
299
		$commenter_cookie_value = $commenter_cookie->getValue();
300
		$commenter_cookie_value = json_decode($commenter_cookie_value);
301
		
302
		if($commenter_cookie_value === NULL)
303
			return $commenter;
304
		
305
		if(!isset($commenter_cookie_value->name) || !isset($commenter_cookie_value->email))
306
			return $commenter;
307
		
308
		$commenter_object = CommentCollector::getCommenterByFields($commenter_cookie_value->name, $commenter_cookie_value->email, (isset($commenter_cookie_value->website) ? $commenter_cookie_value->website : ''));
309
		
310
		if($commenter_object === NULL)
311
			return $commenter;
312
		
313
		$commenter->id = $commenter_object->id;
314
		$commenter->name = $commenter_object->name;
315
		$commenter->email = $commenter_object->email;
316
		$commenter->website = $commenter_object->url;
317
		
318
		return $commenter;
319
	}
320
321
}
322