Completed
Push — develop ( bffb2a...35cb48 )
by
unknown
07:30
created

ManageController::profileAction()   D

Complexity

Conditions 17
Paths 20

Size

Total Lines 111
Code Lines 72

Duplication

Lines 17
Ratio 15.32 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 17
loc 111
rs 4.8361
cc 17
eloc 72
nc 20
nop 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
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** Auth controller */
11
namespace Auth\Controller;
12
13
use Zend\Mvc\Controller\AbstractActionController;
14
use Zend\View\Model\JsonModel;
15
use Core\Form\SummaryFormInterface;
16
17
/**
18
 * Main Action Controller for Authentication module.
19
 *
20
 */
21
class ManageController extends AbstractActionController
22
{
23
    /**
24
     * attaches further Listeners for generating / processing the output
25
     * @return $this
26
     */
27 View Code Duplication
    public function attachDefaultListeners()
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...
28
    {
29
        parent::attachDefaultListeners();
30
        $serviceLocator  = $this->getServiceLocator();
31
        $defaultServices = $serviceLocator->get('DefaultListeners');
32
        $events          = $this->getEventManager();
33
        $events->attach($defaultServices);
0 ignored issues
show
Documentation introduced by
$defaultServices is of type object|array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
34
        return $this;
35
    }
36
37
    /**
38
     * @return array|JsonModel
39
     */
40
    public function profileAction()
0 ignored issues
show
Coding Style introduced by
profileAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
profileAction uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
41
    {
42
        $serviceLocator = $this->getServiceLocator();
43
        $forms = $serviceLocator->get('forms');
44
        $container = $forms->get('Auth/userprofilecontainer');
45
        $user = $serviceLocator->get('AuthenticationService')->getUser(); /* @var $user \Auth\Entity\User */
46
        $postProfiles = (array)$this->params()->fromPost('social_profiles');
47
        $userProfiles = $user->getProfile();
48
        $formSocialProfiles = $forms->get('Auth/SocialProfiles')
49
            ->setUseDefaultValidation(true)
50
            ->setData(['social_profiles' => array_map(function ($array)
51
            {
52
                return $array['data'];
53
            }, $userProfiles)]);
54
        
55
        $translator = $serviceLocator->get('Translator');
56
		$formSocialProfiles->getBaseFieldset()
57
            ->setOption('description', $translator->translate("you can add your social profile to your application. You can preview and remove the attached profile before submitting the application."));
58
        $container->setEntity($user);
59
60
        if ($this->request->isPost()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Stdlib\RequestInterface as the method isPost() does only exist in the following implementations of said interface: Zend\Http\PhpEnvironment\Request, Zend\Http\Request.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
61
            $formName  = $this->params()->fromQuery('form');
62
            $form      = $container->getForm($formName);
63
            
64
            if ($form) {
65
                $postData  = $form->getOption('use_post_array') ? $_POST : array();
66
                $filesData = $form->getOption('use_files_array') ? $_FILES : array();
67
                $data      = array_merge($postData, $filesData);
68
                $form->setData($data);
69
                
70 View Code Duplication
                if (!$form->isValid()) {
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...
71
                    return new JsonModel(
72
                        array(
73
                        'valid' => false,
74
                        'errors' => $form->getMessages(),
75
                        )
76
                    );
77
                }
78
                
79
                $serviceLocator->get('repositories')->store($user);
80
                
81
                if ('file-uri' === $this->params()->fromPost('return')) {
82
                    $content = $form->getHydrator()->getLastUploadedFile()->getUri();
83 View Code Duplication
                } else {
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...
84
                    if ($form instanceof SummaryFormInterface) {
85
                        $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
86
                        $viewHelper = 'summaryform';
87
                    } else {
88
                        $viewHelper = 'form';
89
                    }
90
                    $content = $serviceLocator->get('ViewHelperManager')->get($viewHelper)->__invoke($form);
91
                }
92
                
93
                return new JsonModel(
94
                    array(
95
                    'valid' => $form->isValid(),
96
                    'content' => $content,
97
                    )
98
                );
99
            }
100
            elseif ($postProfiles) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $postProfiles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
101
                $formSocialProfiles->setData($this->params()->fromPost());
102
                
103
                if ($formSocialProfiles->isValid()) {
104
                    $dataProfiles = $formSocialProfiles->getData()['social_profiles'];
105
                    $userRepository = $serviceLocator->get('repositories')->get('Auth/User'); /* @var $userRepository \Auth\Repository\User */
106
                    $hybridAuth = $serviceLocator->get('HybridAuthAdapter')
107
                        ->getHybridAuth();
108
                    
109
                    foreach ($dataProfiles as $network => $postProfile) {
110
                        // remove
111
                        if (isset($userProfiles[$network]) && !$dataProfiles[$network]) {
112
                            $user->removeProfile($network);
113
                        }
114
                        
115
                        // add
116
                        if (!isset($userProfiles[$network]) && $dataProfiles[$network]) {
117
                            $authProfile = $hybridAuth->authenticate($network)
118
                                ->getUserProfile();
119
                            // check for existing profiles
120
                            if ($userRepository->isProfileAssignedToAnotherUser($user->getId(), $authProfile->identifier, $network)) {
121
                                $dataProfiles[$network] = null;
122
                                $formSocialProfiles->setMessages(array(
123
                                    'social_profiles' => [
124
                                        $network => [sprintf($translator->translate('Could not connect your %s profile with your user account. The profile is already connected to another user account.'), $authProfile->displayName)]
125
                                    ]
126
                                ));
127
                            } else {
128
                                $profile = [
129
                                    'auth' => (array)$authProfile,
130
                                    'data' => \Zend\Json\Json::decode($dataProfiles[$network])
131
                                ];
132
                                $user->addProfile($network, $profile);
133
                            }
134
                        }
135
                    }
136
                }
137
                
138
                // keep data in sync & properly decoded
139
                $formSocialProfiles->setData(['social_profiles' => array_map(function ($array)
140
                {
141
                    return \Zend\Json\Json::decode($array) ?: '';
142
                }, $dataProfiles)]);
0 ignored issues
show
Bug introduced by
The variable $dataProfiles 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...
143
            }
144
        }
145
        
146
        return array(
147
            'form' => $container,
148
            'socialProfilesForm' => $formSocialProfiles
149
        );
150
    }
151
}
152