Passed
Push — master ( 240c83...03f39b )
by Mathias
06:41
created

ManageController::profileAction()   D

Complexity

Conditions 18
Paths 13

Size

Total Lines 121
Code Lines 77

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 193.2661

Importance

Changes 0
Metric Value
eloc 77
dl 0
loc 121
ccs 10
cts 54
cp 0.1852
rs 4.8666
c 0
b 0
f 0
cc 18
nc 13
nop 0
crap 193.2661

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 Auth\Adapter\HybridAuth;
14
use Auth\AuthenticationService;
15
use Auth\Entity\UserImage;
16
use Auth\Entity\UserInterface;
17
use Auth\Form\SocialProfiles;
18
use Auth\Form\UserProfileContainer;
19
use Auth\Service\UploadHandler;
20
use Core\Entity\ImageMetadata;
21
use Core\Repository\RepositoryService;
22
use Core\Service\FileManager;
23
use Interop\Container\ContainerInterface;
24
use Laminas\Mvc\Controller\AbstractActionController;
25
use Laminas\Mvc\I18n\Translator;
26
use Laminas\View\HelperPluginManager;
27
use Laminas\View\Model\JsonModel;
28
use Core\Form\SummaryFormInterface;
29
30
/**
31
 * Main Action Controller for Authentication module.
32
 *
33
 */
34
class ManageController extends AbstractActionController
35
{
36
	private $userProfileContainer;
37
	
38
	private $authService;
39
	
40
	private $socialProfileForm;
41
	
42
	private $translator;
43
	
44
	private $repositories;
45
	
46
	private $viewHelper;
47
	
48
	private $hybridAuthAdapter;
49 1
50
    private UploadHandler $manageHandler;
51 1
52 1
    /**
53 1
	 * @param ContainerInterface $container
54 1
	 * @return ManageController
55 1
	 */
56 1
	static public function factory(ContainerInterface $container)
57 1
	{
58 1
		$forms = $container->get('forms');
59 1
		$userProfileContainer = $forms->get('Auth/UserProfileContainer');
60 1
		$socialProfileForm = $forms->get('Auth/SocialProfiles');
61
		$authService = $container->get('AuthenticationService');
62
		$translator = $container->get('translator');
63
		$repositories = $container->get('repositories');
64
		$viewHelper = $container->get('ViewHelperManager');
65
		$hybridAuthAdapter = $container->get('HybridAuthAdapter');
66
		$uploadHandler = $container->get(UploadHandler::class);
67
68 1
		return new ManageController(
69
			$userProfileContainer,
70
			$authService,
71 1
			$repositories,
72
			$socialProfileForm,
73
			$translator,
74
			$viewHelper,
75
			$hybridAuthAdapter,
76
            $uploadHandler
77
		);
78
	}
79
	
80
	public function __construct(
81 1
        UserProfileContainer $userProfileContainer,
82 1
        AuthenticationService $authService,
83 1
        RepositoryService $repositories,
84 1
        SocialProfiles $socialProfileForm,
85 1
        Translator $translator,
86 1
        HelperPluginManager $viewHelper,
87 1
        HybridAuth $hybridAuthAdapter,
88
        UploadHandler $manageHandler
89
	)
90
	{
91
		$this->userProfileContainer = $userProfileContainer;
92
		$this->authService = $authService;
93 1
		$this->socialProfileForm = $socialProfileForm;
94
		$this->repositories = $repositories;
95
		$this->translator = $translator;
96 1
		$this->viewHelper = $viewHelper;
97 1
		$this->hybridAuthAdapter = $hybridAuthAdapter;
98 1
        $this->manageHandler = $manageHandler;
99 1
    }
100 1
	
101 1
	/**
102
     * @return array|JsonModel
103
     */
104
    public function profileAction()
105 1
    {
106
        /* @var \Auth\Form\UserProfileContainer $userProfileContainer */
107 1
        $userProfileContainer = $this->userProfileContainer;
108
        $user = $this->authService->getUser(); /* @var $user \Auth\Entity\User */
109 1
        $postProfiles = (array)$this->params()->fromPost('social_profiles');
110 1
        $userProfiles = $user->getProfile();
111 1
        $formSocialProfiles = $this->socialProfileForm
112 1
            ->setUseDefaultValidation(true)
113
            ->setData(['social_profiles' => array_map(function ($array)
114 1
            {
115
                return $array['data'];
116 1
            }, $userProfiles)]);
117
        
118
        $translator = $this->translator;
119
        /* @var \Auth\Form\SocialProfiles $formSocialProfiles */
120
        $formSocialProfiles->getBaseFieldset()
121
            ->setOption(
122
                'description',
123
                $translator->translate('You can connect your user profile with social networks. This allows you to log in via these networks.')
124
            );
125
        $userProfileContainer->setEntity($user);
126
127
        if ($this->request->isPost()) {
0 ignored issues
show
Bug introduced by
The method isPost() does not exist on Laminas\Stdlib\RequestInterface. It seems like you code against a sub-type of Laminas\Stdlib\RequestInterface such as Laminas\Http\Request. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

127
        if ($this->request->/** @scrutinizer ignore-call */ isPost()) {
Loading history...
128
            $formName  = $this->params()->fromQuery('form');
129
            $form      = $userProfileContainer->getForm($formName);
130
131
            if(!is_null($form) && 'info.image' === $formName) {
132
                $user = $this->manageHandler->handleUpload($user, $_FILES['image']);
133
                $form->getParent()->setEntity($user->getInfo());
0 ignored issues
show
Bug introduced by
The method getParent() does not exist on Laminas\Form\FormInterface. It seems like you code against a sub-type of Laminas\Form\FormInterface such as Core\Form\Form or Core\Form\SummaryForm. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

133
                $form->/** @scrutinizer ignore-call */ 
134
                       getParent()->setEntity($user->getInfo());
Loading history...
134
                $content = $this->viewHelper->get('form')->__invoke($form);
135
                return new JsonModel(
136
                    array(
137
                        'valid' => true,
138
                        'content' => $content,
139
                    )
140
                );
141
            }elseif($form) {
142
                $postData  = $form->getOption('use_post_array') ? $_POST : array();
143
                //@TODO: [ZF3] option use_files_array is false by default
144
                //$filesData = $form->getOption('use_files_array') ? $_FILES : array();
145
	            $filesData = $_FILES;
146
                $data      = array_merge($postData, $filesData);
147
                $form->setData($data);
148
149
                if (!$form->isValid()) {
150
                    return new JsonModel(array(
151
                        'valid' => false,
152
                        'errors' => $form->getMessages(),
153
                    ));
154
                }
155
156
                $this->repositories->store($user);
157
                
158
                if ('file-uri' === $this->params()->fromPost('return')) {
159
                    $content = $form->getHydrator()->getLastUploadedFile()->getUri();
0 ignored issues
show
Bug introduced by
The method getLastUploadedFile() does not exist on Laminas\Hydrator\HydratorInterface. It seems like you code against a sub-type of Laminas\Hydrator\HydratorInterface such as Core\Entity\Hydrator\FileCollectionUploadHydrator. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

159
                    $content = $form->getHydrator()->/** @scrutinizer ignore-call */ getLastUploadedFile()->getUri();
Loading history...
Bug introduced by
The method getHydrator() does not exist on Core\Form\Container. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

159
                    $content = $form->/** @scrutinizer ignore-call */ getHydrator()->getLastUploadedFile()->getUri();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
160
                } else {
161
                    if ($form instanceof SummaryFormInterface) {
162
                        $form->setRenderMode(SummaryFormInterface::RENDER_SUMMARY);
163
                        $viewHelper = 'summaryForm';
164
                    } else {
165
                        $viewHelper = 'form';
166
                    }
167
                    $content = $this->viewHelper->get($viewHelper)->__invoke($form);
168
                }
169
                
170
                return new JsonModel(
171
                    array(
172
                    'valid' => $form->isValid(),
173
                    'content' => $content,
174
                    )
175
                );
176
            }
177
            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...
178
                $formSocialProfiles->setData($this->params()->fromPost());
179
                
180
                if ($formSocialProfiles->isValid()) {
181
                    $dataProfiles = $formSocialProfiles->getData()['social_profiles'];
182
                    $userRepository = $this->repositories->get('Auth/User'); /* @var $userRepository \Auth\Repository\User */
183
                    $hybridAuth = $this->hybridAuthAdapter->getHybridAuth();
184
                    
185
                    foreach ($dataProfiles as $network => $postProfile) {
186
                        // remove
187
                        if (isset($userProfiles[$network]) && !$dataProfiles[$network]) {
188
                            $user->removeProfile($network);
189
                        }
190
                        
191
                        // add
192
                        if (!isset($userProfiles[$network]) && $dataProfiles[$network]) {
193
                            $authProfile = $hybridAuth->authenticate($network)
194
                                ->getUserProfile();
195
                            // check for existing profiles
196
                            if ($userRepository->isProfileAssignedToAnotherUser($user->getId(), $authProfile->identifier, $network)) {
0 ignored issues
show
Bug introduced by
$user->getId() of type MongoDB\BSON\ObjectId|string is incompatible with the type integer expected by parameter $curentUserId of Auth\Repository\User::is...AssignedToAnotherUser(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

196
                            if ($userRepository->isProfileAssignedToAnotherUser(/** @scrutinizer ignore-type */ $user->getId(), $authProfile->identifier, $network)) {
Loading history...
197
                                $dataProfiles[$network] = null;
198
                                $formSocialProfiles->setMessages(array(
199
                                    'social_profiles' => [
200
                                        $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)]
201
                                    ]
202
                                ));
203
                            } else {
204 1
                                $profile = [
205 1
                                    'auth' => (array)$authProfile,
206
                                    'data' => \Laminas\Json\Json::decode($dataProfiles[$network])
207
                                ];
208
                                $user->addProfile($network, $profile);
209
                            }
210
                        }
211
                    }
212
                }
213
                
214
                // keep data in sync & properly decoded
215
                $formSocialProfiles->setData(['social_profiles' => array_map(function ($array)
216
                {
217
                    return \Laminas\Json\Json::decode($array) ?: '';
218
                }, $dataProfiles)]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dataProfiles does not seem to be defined for all execution paths leading up to this point.
Loading history...
219
            }
220
        }
221
        
222
        return array(
223
            'form' => $userProfileContainer,
224
            'socialProfilesForm' => $formSocialProfiles
225
        );
226
    }
227
}
228