SwUserHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace XoopsModules\Smallworld;
4
5
/*
6
 You may not change or alter any portion of this comment or credits of
7
 supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit
9
 authors.
10
11
 This program is distributed in the hope that it will be useful, but
12
 WITHOUT ANY WARRANTY; without even the implied warranty of
13
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
 */
15
16
/**
17
 * Smallworld
18
 *
19
 * @package      \XoopsModules\Smallworld
20
 * @license      GNU GPL (https://www.gnu.org/licenses/gpl-2.0.html/)
21
 * @author       XOOPS Module Development Team
22
 * @copyright    Copyright (c) 2001-2020 {@link https://xoops.org XOOPS Project}
23
 * @link         https://github.com/XoopsModules25x/smallworld
24
 * @since        1.16
25
 */
26
27
use XoopsModules\Smallworld\Constants;
28
29
/**
30
 * Smallworld User Object Handler
31
 *
32
 */
33
class SwUserHandler extends \XoopsPersistableObjectHandler
34
{
35
    /**
36
     * Class constructor
37
     *
38
     * @param \XoopsDatabase $db
0 ignored issues
show
Documentation introduced by
Should the type for parameter $db not be \XoopsDatabase|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
39
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
40
     */
41
    public function __construct(&$db = null)
42
    {
43
        /** {@internal - note use of userid for \XoopsPersistableObjectHandler::identifierName
44
         *  This was done so that {@see \XoopsHandler::getList() will return the userids since it's not the primary key in
45
         *  the dB table but is unique and more useful than returning the `username` column. }}
46
         */
47
        parent::__construct($db, 'smallworld_user', SwUser::class, 'id', 'userid');
48
    }
49
    /**
50
     * Check if user has profile
51
     *
52
     * Returns profile type:
53
     *  Constants::PROFILE_NONE - no profile (XOOPS or SW),
54
     *  || Constants::PROFILE_XOOPS_ONLY - XOOPS user but no SW profile,
55
     *  || Constants::PROFILE_HAS_BOTH - has both
56
     *
57
     * @param int $userId  XOOPS user id
58
     * @return int
59
     */
60
    public function checkIfProfile($userId)
61
    {
62
        $userId = (int)$userId;
63
        $type   = Constants::PROFILE_NONE; // init profile type
64
        if (Constants::DEFAULT_UID < $userId) {
65
            // now check to see if it's a real XOOPS user
66
            $xUser = new \XoopsUser($userId);
67
            if ($xUser instanceof \XoopsUser) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
68
                // valid XOOPS user, see if there's a SW profile for them
69
                $userCount = $this->getCount(new \Criteria('userid', $userId));
70
                // If \XoopsUser but no smallworld profile set to XOOPS only, otherwise they have a SW profile too
71
                $type = (0 == $userCount) ? Constants::PROFILE_XOOPS_ONLY : Constants::PROFILE_HAS_BOTH;
72
            }
73
        }
74
        return $type;
75
    }
76
    /**
77
     * Get SwUser userid
78
     *
79
     * @param int $userId
80
     * @return bool|\XoopsModules\Smallworld\SwUser false if not exists
81
     */
82
    public function getByUserId($userId)
83
    {
84
        $swUser  = false;
85
        $criteria = new \Criteria('userid', (int)$userId);
86
        $criteria->setLimit(1);
87
        $swUserObjArray = $this->getAll($criteria);
88
        if (0 < count($swUserObjArray)) {
89
            $swUser = array_pop($swUserObjArray);
90
        }
91
        return $swUser;
92
    }
93
    /**
94
     * Get SwUser name from userid
95
     *
96
     * @param int $userId
97
     * @return string
98
     */
99
    public function getName($userId)
100
    {
101
        $swUser = $this->getByUserId($userId);
102
        $username = (false !== $swUser) ? $swUser->getVar('username') : '';
103
104
        return $username;
105
    }
106
    /**
107
     * Get SwUser userid from username
108
     *
109
     * @param string $userName
0 ignored issues
show
Documentation introduced by
There is no parameter named $userName. Did you maybe mean $username?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
110
     * @return int   SW userid, 0 if not found
111
     */
112
    public function getByName($username = '')
113
    {
114
        $userId = 0;
115
        if (!empty($username)) {
116
            $criteria = new \Criteria('username', $username);
117
            $criteria->setLimit(1);
118
            $swUserArray = $this->getAll($criteria, ['userid'], false);
119
            if (0 < count($swUserArray)) {
120
                $swUser = array_pop($swUserArray);
121
                $userId = (int)$swUser['userid'];
122
            }
123
        }
124
125
        return $userId;
126
    }
127
    /**
128
     * Does partner/spouse exist as a SwUser
129
     *
130
     * @param string $name
0 ignored issues
show
Bug introduced by
There is no parameter named $name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
131
     * @return bool
132
     */
133
    public function spouseExists($username)
134
    {
135
        $exists = $this->getByName($username);
136
        return (0 < $exists) ? true : false;
137
    }
138
    /**
139
     * Get array of `userid`s
140
     *
141
     * @return array
142
     */
143
    public function allUsers()
144
    {
145
        $r = $this->getList();
146
        return count($r) ? smallworld_array_flatten($r, 0) : [];
147
        /*
148
        $retVal = [];
149
        $sql    = 'SELECT userid FROM ' . $GLOBALS['xoopsDB']->prefix('smallworld_user') . ' ORDER BY userid';
150
        $result = $GLOBALS['xoopsDB']->queryF($sql);
151
        $i      = $GLOBALS['xoopsDB']->getRowsNum($result);
152
        $criteria = new \Criteria('');
153
        $criteria->setSort('userid');
154
        $criteria->order = 'ASC';
155
        $users  = $this->getAll($criteria, ['userid'], false);
156
157
        if (0 !== $i) {
158
            $data = [];
159
            while (false !== ($r = $GLOBALS['xoopsDB']->fetchArray($result))) {
160
                $data[] = $r;
161
            }
162
            $retVal = smallworld_array_flatten($data, 0);
163
        }
164
165
        return $retVal;
166
        //redirect_header(XOOPS_URL . "/modules/smallworld/register.php");
167
         */
168
    }
169
170
    /**
171
     * Get user image based on uid
172
     *
173
     * @param int $uid
0 ignored issues
show
Bug introduced by
There is no parameter named $uid. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
174
     * @return string
175
     */
176
    public function gravatar($userId)
177
    {
178
        $avatar = '';
0 ignored issues
show
Unused Code introduced by
$avatar is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
179
        $swUser = $this->getByUserId($userId);
180
        $image  = (false !== $swUser) ? $swUser->getVar('userimage') : '';
181
        //        $image  = ('' === $image || 'blank.gif' === $image) ? $this->getAvatarLink($userId, $image) : $image;
182
        $image  = (empty($image) || 'blank.gif' === $image) ? $this->getAvatarLink($userId, $image) : $image;
183
        $type   = [
184
            Constants::IMAGE_TYPE_JPG  => 'jpg',
185
            Constants::IMAGE_TYPE_JPEG => 'jpeg',
186
            Constants::IMAGE_TYPE_PNG  => 'png',
187
            Constants::IMAGE_TYPE_GIF  => 'gif'
188
        ];
189
190
        $parts  = explode('.', $image);
191
        $ext    = (is_array($parts) && 0 < count($parts)) ? array_pop($parts) : '';
192
        $avatar = in_array(mb_strtolower($ext), $type) ? $image : '';
193
        return $avatar;
194
    }
195
    /**
196
     * Check image extension and users gender.
197
     *
198
     * If image is legal image extension return avatar, else return default gender based image
199
     * @param int    $userId
200
     * @param string $image
201
     * @return string
202
     */
203
    public function getAvatarLink($userId, $image)
204
    {
205
        $swUser = $this->getByUserId($userId);
206
        $gender = (false !== $swUser) ? $swUser->getVar('gender') : Constants::GENDER_UNKNOWN;
207
        $link   = (preg_match('/avatars/i', $image)) ? XOOPS_UPLOAD_URL . '/' . $image : $image;
208
        $ext    = pathinfo(mb_strtolower($image), PATHINFO_EXTENSION);
209
210 View Code Duplication
        if (!in_array($ext, ['jpg', 'bmp', 'gif', 'png', 'jpeg']) || "" == $image || 'avatars/blank.gif' == $image) {
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...
211
            switch ($gender) {
212
                case Constants::FEMALE:
213
                    $pict = 'ano_woman.png';
214
                    break;
215
                case Constants::MALE:
216
                    $pict = 'ano_man.png';
217
                    break;
218
                case Constants::GENDER_UNKNOWN:
219
                default:
220
                    $pict = 'genderless.png';
221
                    break;
222
            }
223
            $link = Helper::getInstance()->url("assets/images/{$pict}");
224
        }
225
        return $link;
226
    }
227
}
228