Completed
Push — preprod ( 503287 )
by Ilia
29:11
created

like.php ➔ like_users()   C

Complexity

Conditions 15
Paths 200

Size

Total Lines 57
Code Lines 35

Duplication

Lines 14
Ratio 24.56 %

Importance

Changes 0
Metric Value
cc 15
eloc 35
nc 200
nop 3
dl 14
loc 57
rs 5.9162
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/*
3
 * Exposes API endpoints for Like annotations
4
 */
5
6
elgg_ws_expose_function(
7
	"like.item",
8
	"like_item",
9
	array(
10
		"user" => array('type' => 'string', 'required' => true),
11
		"guid" => array('type' => 'int', 'required' => true),
12
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
13
	),
14
	'Submits a like/unlike on an entity based on user id and entity id',
15
	'POST',
16
	true,
17
	false
18
);
19
20
elgg_ws_expose_function(
21
	"like.count",
22
	"like_count",
23
	array(
24
		"guid" => array('type' => 'int', 'required' => true),
25
		"user" => array('type' => 'string', 'required' => false),
26
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
27
	),
28
	'Retrieves a like count on an entity based on user id and entity id',
29
	'POST',
30
	true,
31
	false
32
);
33
34
elgg_ws_expose_function(
35
	"like.users",
36
	"like_users",
37
	array(
38
		"guid" => array('type' => 'int', 'required' => true),
39
		"user" => array('type' => 'string', 'required' => false),
40
		"lang" => array('type' => 'string', 'required' => false, 'default' => "en")
41
	),
42
	'Retrieves all users who liked an entity based on user id and entity id',
43
	'POST',
44
	true,
45
	false
46
);
47
48
function like_item($user, $guid, $lang)
49
{
50
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
51
	if (!$user_entity) {
52
		return "User was not found. Please try a different GUID, username, or email address";
53
	}
54
	if (!$user_entity instanceof ElggUser) {
55
		return "Invalid user. Please try a different GUID, username, or email address";
56
	}
57
58
	if (!elgg_is_logged_in()) {
59
		login($user_entity);
60
	}
61
62
	$entity = get_entity($guid);
63
	if (!$entity) {
64
		return "Object was not found. Please try a different GUID";
65
	}
66
	if (!$entity instanceof ElggObject) {
67
		return "Invalid object. Please try a different GUID";
68
	}
69
70
	$likes = elgg_get_annotations(array(
71
		'guid' => $guid,
72
		'annotation_owner_guid' => $user_entity->guid,
73
		'annotation_name' => 'likes'
74
	));
75
76
	$liked = false;
77
78
	// check to see if the user has already liked the item
79
	if (!empty($likes)) {
80
		$like = $likes[0];
81
82
		if ($like && $like->canEdit()) {
83
			$like->delete();
84
			$data['message'] = elgg_echo("likes:deleted");
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
85
		}
86
	} else {
87
		$annotation_id = create_annotation($entity->guid, 'likes', "likes", "", $user_entity->guid, $entity->access_id);
88
		$liked = true;
89
90
		// notify if poster wasn't owner
91 View Code Duplication
		if ($entity->owner_guid != $user_entity->guid) {
92
			$owner = $entity->getOwnerEntity();
93
94
			$annotation = elgg_get_annotation_from_id($annotation_id);
0 ignored issues
show
Security Bug introduced by
It seems like $annotation_id defined by create_annotation($entit...id, $entity->access_id) on line 87 can also be of type false; however, elgg_get_annotation_from_id() does only seem to accept integer, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
95
96
			$title_str = $entity->getDisplayName();
97
			if (!$title_str) {
98
				$title_str = elgg_get_excerpt($entity->description);
99
			}
100
101
			$site = elgg_get_site_entity();
102
103
			$subject = elgg_echo(
104
				'likes:notifications:subject',
105
				array(
106
					$user_entity->name,
107
					$title_str
108
				),
109
				$owner->language
110
			);
111
112
			$body = elgg_echo(
113
				'likes:notifications:body',
114
				array(
115
					$owner->name,
116
					$user_entity->name,
117
					$title_str,
118
					$site->name,
119
					$entity->getURL(),
120
					$user_entity->getURL()
121
				),
122
				$owner->language
123
			);
124
125
			notify_user(
126
				$entity->owner_guid,
127
				$user_entity->guid,
128
				$subject,
129
				$body,
130
				array(
131
					'action' => 'create',
132
					'object' => $annotation,
133
				)
134
			);
135
		}
136
137
		$data['message'] = elgg_echo("likes:likes");
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
138
	}
139
140
	$likes = elgg_get_annotations(array(
141
		'guid' => $guid,
142
		'annotation_name' => 'likes'
143
	));
144
	$data['count'] = count($likes);
0 ignored issues
show
Bug introduced by
The variable $data does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
145
146
	$data['liked'] = $liked;
147
148
	return $data;
149
}
150
151
function like_count($guid, $user, $lang)
152
{
153
	$entity = get_entity($guid);
154
	if (!$entity) {
155
		return "Object was not found. Please try a different GUID";
156
	}
157
	if (!$entity instanceof ElggObject) {
158
		return "Invalid object. Please try a different GUID";
159
	}
160
161
	$likes = elgg_get_annotations(array(
162
		'guid' => $guid,
163
		'annotation_name' => 'likes'
164
	));
165
	$data['count'] = count($likes);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
166
167 View Code Duplication
	if ($user) {
168
		$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
169
		if (!$user_entity) {
170
			return "User was not found. Please try a different GUID, username, or email address";
171
		}
172
		if (!$user_entity instanceof ElggUser) {
173
			return "Invalid user. Please try a different GUID, username, or email address";
174
		}
175
176
		if ($user_entity) {
177
			$likes = elgg_get_annotations(array(
178
				'guid' => $guid,
179
				'annotation_owner_guid' => $user_entity->guid,
180
				'annotation_name' => 'likes'
181
			));
182
			$data['liked'] = count($likes) > 0;
183
		}
184
	}
185
186
	return $data;
187
}
188
189
function like_users($guid, $user, $lang)
190
{
191
	$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
192
	if (!$user_entity) {
193
		return "User was not found. Please try a different GUID, username, or email address";
194
	}
195
	if (!$user_entity instanceof ElggUser) {
196
		return "Invalid user. Please try a different GUID, username, or email address";
197
	}
198
199
	if (!elgg_is_logged_in()) {
200
		login($user_entity);
201
	}
202
203
	$entity = get_entity($guid);
204
	if (!$entity) {
205
		return "Object was not found. Please try a different GUID";
206
	}
207
	if (!$entity instanceof ElggObject) {
208
		return "Invalid object. Please try a different GUID";
209
	}
210
211
	$likes = elgg_get_annotations(array(
212
		'guid' => $guid,
213
		'annotation_name' => 'likes'
214
	));
215
	$data = array();
216
217
	foreach ($likes as $key => $like) {
218
		$item = get_user_block($like->owner_guid, $lang);
219
		$item['time_created'] = date("Y-m-d H:i:s", $like->time_created);
220
		$data['users'][] = $item;
221
	}
222
223
	$data['count'] = count($likes);
224
225 View Code Duplication
	if ($user) {
226
		$user_entity = is_numeric($user) ? get_user($user) : (strpos($user, '@') !== false ? get_user_by_email($user)[0] : get_user_by_username($user));
227
		if (!$user_entity) {
228
			return "User was not found. Please try a different GUID, username, or email address";
229
		}
230
		if (!$user_entity instanceof ElggUser) {
231
			return "Invalid user. Please try a different GUID, username, or email address";
232
		}
233
234
		if ($user_entity) {
235
			$likes = elgg_get_annotations(array(
236
				'guid' => $guid,
237
				'annotation_owner_guid' => $user_entity->guid,
238
				'annotation_name' => 'likes'
239
			));
240
			$data['liked'] = count($likes) > 0;
241
		}
242
	}
243
244
	return $data;
245
}
246