Completed
Push — master ( ec0b76...22789e )
by Craig
06:04
created

ProfileExtension::determineProfileLink()   C

Complexity

Conditions 11
Paths 51

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 25
c 1
b 0
f 0
nc 51
nop 6
dl 0
loc 38
rs 5.2653

How to fix   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
/*
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\Entity\RepositoryInterface\UserRepositoryInterface;
17
18
class ProfileExtension extends \Twig_Extension
19
{
20
    /**
21
     * @var UserRepositoryInterface
22
     */
23
    private $userRepository;
24
25
    /**
26
     * @var ProfileModuleCollector
27
     */
28
    private $profileModuleCollector;
29
30
    /**
31
     * @var TranslatorInterface
32
     */
33
    private $translator;
34
35
    /**
36
     * ProfileExtension constructor.
37
     * @param UserRepositoryInterface $userRepository
38
     * @param ProfileModuleCollector $profileModuleCollector
39
     * @param TranslatorInterface $translator
40
     */
41
    public function __construct(
42
        UserRepositoryInterface $userRepository,
43
        ProfileModuleCollector $profileModuleCollector,
44
        TranslatorInterface $translator
45
    ) {
46
        $this->userRepository = $userRepository;
47
        $this->profileModuleCollector = $profileModuleCollector;
48
        $this->translator = $translator;
49
    }
50
51
    public function getFunctions()
52
    {
53
        return [
54
            new \Twig_SimpleFunction('userAvatar', [$this, 'getUserAvatar'], ['is_safe' => ['html']])
55
        ];
56
    }
57
58
    public function getFilters()
59
    {
60
        return [
61
            new \Twig_SimpleFilter('profileLinkByUserId', [$this, 'profileLinkByUserId'], ['is_safe' => ['html']]),
62
            new \Twig_SimpleFilter('profileLinkByUserName', [$this, 'profileLinkByUserName'], ['is_safe' => ['html']])
63
        ];
64
    }
65
66
    /**
67
     * Displays the avatar of a given user.
68
     *
69
     * @param int|string $uid        The user's id or name
70
     * @param array      $parameters Any additional arguments (e.g. width, height, size, rating)
71
     *
72
     * @return string
73
     */
74
    public function getUserAvatar($uid = 0, array $parameters = [])
75
    {
76
        return $this->profileModuleCollector->getSelected()->getAvatar($uid, $parameters);
77
    }
78
79
    /**
80
     * Create a link to a users profile from the UID.
81
     *
82
     * Examples
83
     *
84
     *   Simple version, shows the username
85
     *   {{ uid|profileLinkByUserId() }}
86
     *   Simple version, shows username, using class="classname"
87
     *   {{ uid|profileLinkByUserId(class='classname') }}
88
     *   Using profile.gif instead of username, no class
89
     *   {{ uid|profileLinkByUserId(image='images/profile.gif') }}
90
     *
91
     * @param integer $userId    The users uid
92
     * @param string  $class     The class name for the link (optional)
93
     * @param string  $image     Path to the image to show instead of the username (optional)
94
     * @param integer $maxLength If set then user names are truncated to x chars
95
     * @return string The output
96
     */
97 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...
98
    {
99
        if (empty($userId) || (int)$userId < 1) {
100
            return $userId;
101
        }
102
103
        return $this->determineProfileLink((int)$userId, null, $class, $image, $maxLength, $title);
104
    }
105
106
    /**
107
     * Create a link to a users profile from the username.
108
     *
109
     * Examples
110
     *
111
     *   Simple version, shows the username
112
     *   {{ username|profileLinkByUserName() }}
113
     *   Simple version, shows username, using class="classname"
114
     *   {{ username|profileLinkByUserName(class='classname') }}
115
     *   Using profile.gif instead of username, no class
116
     *   {{ username|profileLinkByUserName('image'='images/profile.gif') }}
117
     *
118
     * @param string  $userName  The users name
119
     * @param string  $class     The class name for the link (optional)
120
     * @param string  $image     Path to the image to show instead of the username (optional)
121
     * @param integer $maxLength If set then user names are truncated to x chars
122
     * @return string The output
123
     */
124 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...
125
    {
126
        if (empty($userName)) {
127
            return $userName;
128
        }
129
130
        return $this->determineProfileLink(null, $userName, $class, $image, $maxLength, $title);
131
    }
132
133
    /**
134
     * Internal function used by profileLinkByUserId() and profileLinkByUserName().
135
     *
136
     * @param integer $userId    The users uid
137
     * @param string  $userName  The users name
138
     * @param string  $class     The class name for the link (optional)
139
     * @param string  $imagePath Path to the image to show instead of the username (optional)
140
     * @param integer $maxLength If set then user names are truncated to x chars
141
     * @return string The output
142
     */
143
    private function determineProfileLink($userId = null, $userName = null, $class = '', $imagePath = '', $maxLength = 0, $title = '')
144
    {
145
        if (!isset($userId) && !isset($userName)) {
146
            throw new \InvalidArgumentException();
147
        }
148
        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...
149
            $user = $this->userRepository->find($userId);
150
        } else {
151
            $user = $this->userRepository->findOneBy(['uname' => $userName]);
152
        }
153
        if (!$user) {
154
            return $userId . $userName; // one or the other is empty
155
        }
156
157
        $userDisplayName = $this->profileModuleCollector->getSelected()->getDisplayName($user->getUid());
158
        $class = !empty($class) ? ' class="' . htmlspecialchars($class, ENT_QUOTES) . '"' : '';
159
160
        if (!empty($imagePath)) {
161
            $show = '<img src="' . htmlspecialchars($imagePath, ENT_QUOTES) . '" alt="' . htmlspecialchars($userDisplayName, ENT_QUOTES) . '" />';
162
        } elseif ($maxLength > 0) {
163
            // truncate the user name to $maxLength chars
164
            $length = strlen($userDisplayName);
165
            $truncEnd = ($maxLength > $length) ? $length : $maxLength;
166
            $show = htmlspecialchars(substr($userDisplayName, 0, $truncEnd), ENT_QUOTES);
167
        } else {
168
            $show = htmlspecialchars($userDisplayName, ENT_QUOTES);
169
        }
170
        $href = $this->profileModuleCollector->getSelected()->getProfileUrl($user->getUid());
171
        if ($href == '#') {
172
            return $userDisplayName;
173
        }
174
175
        if (empty($title)) {
176
            $title = $this->translator->__('Profile') . ': ' . $userDisplayName;
177
        }
178
179
        return '<a' . $class . ' title="' . htmlspecialchars($title, ENT_QUOTES) . '" href="' . $href . '">' . $show . '</a>';
180
    }
181
}
182