Completed
Push — master ( 693283...8cba26 )
by Craig
06:26
created

ProfileExtension::getUserAvatar()   C

Complexity

Conditions 7
Paths 33

Size

Total Lines 41
Code Lines 25

Duplication

Lines 41
Ratio 100 %

Importance

Changes 0
Metric Value
dl 41
loc 41
c 0
b 0
f 0
cc 7
eloc 25
nc 33
nop 5
rs 6.7272
1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\UsersModule\Twig\Extension;
13
14
use Zikula\Common\Translator\TranslatorInterface;
15
use Zikula\UsersModule\Collector\ProfileModuleCollector;
16
use Zikula\UsersModule\Constant as UsersConstant;
17
use Zikula\UsersModule\Entity\RepositoryInterface\UserRepositoryInterface;
18
19
class ProfileExtension extends \Twig_Extension
20
{
21
    /**
22
     * @var UserRepositoryInterface
23
     */
24
    private $userRepository;
25
26
    /**
27
     * @var ProfileModuleCollector
28
     */
29
    private $profileModuleCollector;
30
31
    /**
32
     * @var TranslatorInterface
33
     */
34
    private $translator;
35
36
    /**
37
     * ProfileExtension constructor.
38
     * @param UserRepositoryInterface $userRepository
39
     * @param ProfileModuleCollector $profileModuleCollector
40
     * @param TranslatorInterface $translator
41
     */
42
    public function __construct(
43
        UserRepositoryInterface $userRepository,
44
        ProfileModuleCollector $profileModuleCollector,
45
        TranslatorInterface $translator
46
    ) {
47
        $this->userRepository = $userRepository;
48
        $this->profileModuleCollector = $profileModuleCollector;
49
        $this->translator = $translator;
50
    }
51
52
    public function getFunctions()
53
    {
54
        return [
55
            new \Twig_SimpleFunction('userAvatar', [$this, 'getUserAvatar'], ['is_safe' => ['html']])
56
        ];
57
    }
58
59
    public function getFilters()
60
    {
61
        return [
62
            new \Twig_SimpleFilter('profileLinkByUserId', [$this, 'profileLinkByUserId'], ['is_safe' => ['html']]),
63
            new \Twig_SimpleFilter('profileLinkByUserName', [$this, 'profileLinkByUserName'], ['is_safe' => ['html']])
64
        ];
65
    }
66
67
    /**
68
     * Displays the avatar of a given user.
69
     *
70
     * @param int|string $uid    The user's id or name
71
     * @param int        $width  Image width (optional)
72
     * @param int        $height Image height (optional)
73
     * @param int        $size   Gravatar size (optional)
74
     * @param string     $rating Gravatar self-rating [g|pg|r|x] see: http://en.gravatar.com/site/implement/images/ (optional)
75
     *
76
     * @return string
77
     */
78 View Code Duplication
    public function getUserAvatar($uid = 0, $width = 0, $height = 0, $size = 0, $rating = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
79
    {
80
        if (!is_numeric($uid)) {
81
            $limit = 1;
82
            $filter = [
83
                'activated' => ['operator' => 'notIn', 'operand' => [
84
                    UsersConstant::ACTIVATED_PENDING_REG,
85
                    UsersConstant::ACTIVATED_PENDING_DELETE
86
                ]],
87
                'uname' => ['operator' => '=', 'operand' => $uid]
88
            ];
89
            $results = $this->userRepository->query($filter, [], $limit);
90
            if (!count($results)) {
91
                return '';
92
            }
93
94
            $uid = $results->getIterator()->getArrayCopy()[0]->getUname();
95
        }
96
        $params = ['uid' => $uid];
97
        if ($width > 0) {
98
            $params['width'] = $width;
99
        }
100
        if ($height > 0) {
101
            $params['height'] = $height;
102
        }
103
        if ($size > 0) {
104
            $params['size'] = $size;
105
        }
106
        if ($rating != '') {
107
            $params['rating'] = $rating;
108
        }
109
110
        // load avatar plugin
111
        // @todo fix this as part of https://github.com/zikula-modules/Profile/issues/80
112
        include_once 'lib/legacy/viewplugins/function.useravatar.php';
113
114
        $view = \Zikula_View::getInstance('ZikulaUsersModule', false);
115
        $result = smarty_function_useravatar($params, $view);
116
117
        return $result;
118
    }
119
120
    /**
121
     * Create a link to a users profile from the UID.
122
     *
123
     * Examples
124
     *
125
     *   Simple version, shows the username
126
     *   {{ uid|profileLinkByUserId() }}
127
     *   Simple version, shows username, using class="classname"
128
     *   {{ uid|profileLinkByUserId(class='classname') }}
129
     *   Using profile.gif instead of username, no class
130
     *   {{ uid|profileLinkByUserId(image='images/profile.gif') }}
131
     *
132
     * @param integer $userId    The users uid
133
     * @param string  $class     The class name for the link (optional)
134
     * @param string  $image     Path to the image to show instead of the username (optional)
135
     * @param integer $maxLength If set then user names are truncated to x chars
136
     * @return string The output
137
     */
138 View Code Duplication
    public function profileLinkByUserId($userId, $class = '', $image = '', $maxLength = 0, $title = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
139
    {
140
        if (empty($userId) || (int)$userId < 1) {
141
            return $userId;
142
        }
143
144
        return $this->determineProfileLink((int)$userId, null, $class, $image, $maxLength, $title);
145
    }
146
147
    /**
148
     * Create a link to a users profile from the username.
149
     *
150
     * Examples
151
     *
152
     *   Simple version, shows the username
153
     *   {{ username|profileLinkByUserName() }}
154
     *   Simple version, shows username, using class="classname"
155
     *   {{ username|profileLinkByUserName(class='classname') }}
156
     *   Using profile.gif instead of username, no class
157
     *   {{ username|profileLinkByUserName('image'='images/profile.gif') }}
158
     *
159
     * @param string  $userName  The users name
160
     * @param string  $class     The class name for the link (optional)
161
     * @param string  $image     Path to the image to show instead of the username (optional)
162
     * @param integer $maxLength If set then user names are truncated to x chars
163
     * @return string The output
164
     */
165 View Code Duplication
    public function profileLinkByUserName($userName, $class = '', $image = '', $maxLength = 0, $title = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
166
    {
167
        if (empty($userName)) {
168
            return $userName;
169
        }
170
171
        return $this->determineProfileLink(null, $userName, $class, $image, $maxLength, $title);
172
    }
173
174
    /**
175
     * Internal function used by profileLinkByUserId() and profileLinkByUserName().
176
     *
177
     * @param integer $userId    The users uid
178
     * @param string  $userName  The users name
179
     * @param string  $class     The class name for the link (optional)
180
     * @param string  $imagePath Path to the image to show instead of the username (optional)
181
     * @param integer $maxLength If set then user names are truncated to x chars
182
     * @return string The output
183
     */
184
    private function determineProfileLink($userId = null, $userName = null, $class = '', $imagePath = '', $maxLength = 0, $title = '')
185
    {
186
        if (!isset($userId) && !isset($userName)) {
187
            throw new \InvalidArgumentException();
188
        }
189
        if ($userId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
190
            $user = $this->userRepository->find($userId);
191
        } else {
192
            $user = $this->userRepository->findOneBy(['uname' => $userName]);
193
        }
194
        if (!$user) {
195
            return $userId . $userName; // one or the other is empty
196
        }
197
198
        $userDisplayName = $this->profileModuleCollector->getSelected()->getDisplayName($user->getUid());
199
        $class = !empty($class) ? ' class="' . htmlspecialchars($class, ENT_QUOTES) . '"' : '';
200
201
        if (!empty($imagePath)) {
202
            $show = '<img src="' . htmlspecialchars($imagePath, ENT_QUOTES) . '" alt="' . htmlspecialchars($userDisplayName, ENT_QUOTES) . '" />';
203
        } elseif ($maxLength > 0) {
204
            // truncate the user name to $maxLength chars
205
            $length = strlen($userDisplayName);
206
            $truncEnd = ($maxLength > $length) ? $length : $maxLength;
207
            $show  = htmlspecialchars(substr($userDisplayName, 0, $truncEnd), ENT_QUOTES);
208
        } else {
209
            $show = htmlspecialchars($userDisplayName, ENT_QUOTES);
210
        }
211
        $href = $this->profileModuleCollector->getSelected()->getProfileUrl($user->getUid());
212
        if ($href == '#') {
213
            return $userDisplayName;
214
        }
215
216
        if (empty($title)) {
217
            $title = $this->translator->__('Profile') . ': ' . $userDisplayName;
218
        }
219
220
        return '<a' . $class . ' title="' . htmlspecialchars($title, ENT_QUOTES) . '" href="' . $href . '">' . $show . '</a>';
221
    }
222
}
223