Skip to content

Commit dadd7b2

Browse files
author
b-richard
committed
fix code complexity (from ci reports)
1 parent e220ec5 commit dadd7b2

File tree

4 files changed

+185
-89
lines changed

4 files changed

+185
-89
lines changed

src/Command/DumpJsConfig.php

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313

1414
class DumpJsConfig extends ContainerAwareCommand
1515
{
16+
const ARG_HOST = 'host';
17+
18+
const ARG_PORT = 'port';
19+
20+
const ARG_QUASAR_STYLE = 'quasarStyle';
21+
1622
/**
1723
* @var \Twig_Environment
1824
*/
@@ -84,9 +90,9 @@ protected function configure()
8490
->setName('app:dump-js-config')
8591
->setDescription('Create the config.js file.')
8692
->setHelp('Dump symfony configuration into a config.js file available from assets/js/*')
87-
->addArgument('host', InputArgument::OPTIONAL, 'The full hostname of the web-server.', 'localhost')
88-
->addArgument('port', InputArgument::OPTIONAL, 'The port for the web-server.', '80')
89-
->addArgument('quasarStyle', InputArgument::OPTIONAL, 'The style for quasar framework: mat or ios.', 'mat');
93+
->addArgument(self::ARG_HOST, InputArgument::OPTIONAL, 'The full hostname of the web-server.', 'localhost')
94+
->addArgument(self::ARG_PORT, InputArgument::OPTIONAL, 'The port for the web-server.', '80')
95+
->addArgument(self::ARG_QUASAR_STYLE, InputArgument::OPTIONAL, 'The style for quasar framework: mat or ios.', 'mat');
9096
}
9197

9298
/**
@@ -100,9 +106,9 @@ protected function configure()
100106
protected function execute(InputInterface $input, OutputInterface $output)
101107
{
102108
$env = $this->getEnv();
103-
$host = $input->getArgument('host');
104-
$port = $input->getArgument('port');
105-
$quasarStyle = $input->getArgument('quasarStyle');
109+
$host = $input->getArgument(self::ARG_HOST);
110+
$port = $input->getArgument(self::ARG_PORT);
111+
$quasarStyle = $input->getArgument(self::ARG_QUASAR_STYLE);
106112

107113
if (!$this->validateInputs($output, $port, $quasarStyle)) {
108114
return;
@@ -118,6 +124,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
118124
}
119125

120126
/**
127+
* @param OutputInterface $output
121128
* @return array
122129
*/
123130
protected function loadApiPlatformConfig(OutputInterface $output): array
@@ -129,21 +136,23 @@ protected function loadApiPlatformConfig(OutputInterface $output): array
129136
$values = Yaml::parseFile($configDir . 'packages/api_platform.yaml');
130137
$config = $values['api_platform'];
131138

132-
if ($config['collection'] && $config['collection']['pagination']) {
133-
foreach ($mandatoryKeys as $key) {
134-
if (!array_key_exists($key, $config['collection']['pagination'])) {
135-
$missingKeys[] = $key;
136-
}
137-
}
139+
if (!($config['collection'] && $config['collection']['pagination'])) {
140+
throw new \Exception('Missing pagination section in api_platform.yaml');
141+
}
138142

139-
if (count($missingKeys)) {
140-
throw new \Exception(sprintf('those keys are mandatory for the frontend configuration: %s', join(', ', $missingKeys)));
143+
foreach ($mandatoryKeys as $key) {
144+
if (array_key_exists($key, $config['collection']['pagination'])) {
145+
continue;
141146
}
142147

143-
return $config['collection']['pagination'];
148+
$missingKeys[] = $key;
149+
}
150+
151+
if (count($missingKeys)) {
152+
throw new \Exception(sprintf('those keys are mandatory for the frontend configuration: %s', join(', ', $missingKeys)));
144153
}
145154

146-
throw new \Exception('Missing pagination section in api_platform.yaml');
155+
return $config['collection']['pagination'];
147156
} catch (\Exception $e) {
148157
$output->writeln(sprintf('api_platform.yaml error: "%s"', $e->getMessage()));
149158
}
@@ -177,15 +186,15 @@ protected function validateInputs(OutputInterface $output, $port, $quasarStyle):
177186
$validator = Validation::createValidator();
178187
$violations = [];
179188

180-
$violations['port'] = $validator->validate($port, [
189+
$violations[self::ARG_PORT] = $validator->validate($port, [
181190
new Assert\Type(['type' => 'numeric', ]),
182191
]);
183192

184-
$violations['quasarStyle'] = $validator->validate($quasarStyle, [
193+
$violations[self::ARG_QUASAR_STYLE] = $validator->validate($quasarStyle, [
185194
new Assert\Choice(['choices' => ['mat', 'ios'], ]),
186195
]);
187196

188-
if (0 !== count($violations['port']) && 0 !== count($violations['quasarstyle'])) {
197+
if (0 !== count($violations[self::ARG_PORT]) && 0 !== count($violations[self::ARG_QUASAR_STYLE])) {
189198
$output->writeln([
190199
'Params errors',
191200
'=======================', ]);

src/DataFixtures/Library/AppFixtures.php

Lines changed: 81 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,35 @@ protected function addEditor($bookFixture, Book $book, Connection $dbh, ObjectMa
190190
* @throws \Doctrine\DBAL\DBALException
191191
*/
192192
protected function addAuthor($bookFixture, Book $book, Connection $dbh, ObjectManager $manager)
193+
{
194+
$rows = $this->getAuthorsInfo($bookFixture, $dbh);
195+
196+
if (!count($rows)) {
197+
return;
198+
}
199+
200+
$i = 0;
201+
foreach ($rows as $row) {
202+
$authorName = explode('| ', $row['name']);
203+
if (!in_array($row['id'], $this->cache['authors'])) {
204+
$author = $this->getNewAuthor($manager, $authorName, $row);
205+
} else {
206+
$author = $this->getExistingAuthor($manager, $authorName);
207+
}
208+
209+
$this->attachAuthorToBook($book, $author, $i);
210+
211+
$i++;
212+
}
213+
}
214+
215+
/**
216+
* @param $bookFixture
217+
* @param Connection $dbh
218+
* @return array
219+
* @throws \Doctrine\DBAL\DBALException
220+
*/
221+
protected function getAuthorsInfo($bookFixture, Connection $dbh): array
193222
{
194223
$bookId = $bookFixture['id'];
195224

@@ -206,41 +235,59 @@ protected function addAuthor($bookFixture, Book $book, Connection $dbh, ObjectMa
206235
$sth->bindParam('bookId', $bookId, PDO::PARAM_INT);
207236
$sth->execute();
208237
$rows = $sth->fetchAll();
238+
return $rows;
239+
}
209240

210-
if (count($rows)) {
211-
$i = 0;
212-
foreach ($rows as $row) {
213-
$authorName = explode('| ', $row['name']);
214-
if (!in_array($row['id'], $this->cache['authors'])) {
215-
$author = new Author();
216-
if (2 === count($authorName)) {
217-
$author->setFirstname($authorName[0])
218-
->setLastname($authorName[1]);
219-
} else {
220-
$author->setFirstname($authorName[0]);
221-
}
222-
223-
$manager->persist($author);
224-
225-
$this->cache['authors'][] = $row['id'];
226-
} else {
227-
$criterias = ['firstname' => $authorName[0], 'lastname' => null, ];
228-
if (2 === count($authorName)) {
229-
$criterias['lastname'] = $authorName[1];
230-
}
231-
$author = $manager
232-
->getRepository('\\App\\Entity\\Library\\Author')
233-
->findOneBy($criterias);
234-
}
235-
236-
$job = $this->cache['jobs'][0];
237-
if (1 === $i) {
238-
$job = $this->cache['jobs'][0];
239-
}
240-
$book->addAuthor($author, $job);
241-
242-
$i++;
243-
}
241+
/**
242+
* @param ObjectManager $manager
243+
* @param $authorName
244+
* @param $row
245+
* @return Author
246+
*/
247+
protected function getNewAuthor(ObjectManager $manager, $authorName, $row): Author
248+
{
249+
$author = new Author();
250+
if (2 === count($authorName)) {
251+
$author->setFirstname($authorName[0])
252+
->setLastname($authorName[1]);
253+
} else {
254+
$author->setFirstname($authorName[0]);
255+
}
256+
257+
$manager->persist($author);
258+
259+
$this->cache['authors'][] = $row['id'];
260+
return $author;
261+
}
262+
263+
/**
264+
* @param ObjectManager $manager
265+
* @param $authorName
266+
* @return null|object
267+
*/
268+
protected function getExistingAuthor(ObjectManager $manager, $authorName)
269+
{
270+
$criterias = ['firstname' => $authorName[0], 'lastname' => null,];
271+
if (2 === count($authorName)) {
272+
$criterias['lastname'] = $authorName[1];
273+
}
274+
$author = $manager
275+
->getRepository('\\App\\Entity\\Library\\Author')
276+
->findOneBy($criterias);
277+
return $author;
278+
}
279+
280+
/**
281+
* @param Book $book
282+
* @param $author
283+
* @param $i
284+
*/
285+
protected function attachAuthorToBook(Book $book, $author, $i): void
286+
{
287+
$job = $this->cache['jobs'][0];
288+
if (1 === $i) {
289+
$job = $this->cache['jobs'][0];
244290
}
291+
$book->addAuthor($author, $job);
245292
}
246293
}

src/Security/CsrfTokenAuthenticator.php

Lines changed: 58 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<?php
22
namespace App\Security;
33

4+
use http\Exception\RuntimeException;
45
use Psr\Container\ContainerInterface;
56
use Symfony\Component\HttpFoundation\Request;
67
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -148,20 +149,22 @@ public function supports(Request $request)
148149
public function getCredentials(Request $request)
149150
{
150151
// for GET Method
151-
if (strtolower($request->getMethod()) !== 'get') {
152-
// for other Methods, then there must be a body HTTP with JSON content
153-
$content = json_decode($request->getContent());
154-
if (is_null($content)) {
155-
if (json_last_error()) {
156-
throw new AuthenticationException('Json format: ' . json_last_error_msg(), 420);
157-
}
152+
if (strtolower($request->getMethod()) === 'get') {
153+
throw new RuntimeException('Should not be here when method is get, check the CLASS::supports methods');
154+
}
158155

159-
$content = [];
156+
// for other Methods, then there must be a body HTTP with JSON content
157+
$content = json_decode($request->getContent());
158+
if (is_null($content)) {
159+
if (json_last_error()) {
160+
throw new AuthenticationException('Json format: ' . json_last_error_msg(), 420);
160161
}
161162

162-
$json = new \ArrayObject($content, \ArrayObject::STD_PROP_LIST);
163+
$content = [];
163164
}
164165

166+
$json = new \ArrayObject($content, \ArrayObject::STD_PROP_LIST);
167+
165168
if (!isset($json[$this->csrfTokenParameter])) {
166169
throw new AuthenticationException($this->csrfTokenParameter . ' mandatory', 420);
167170
}
@@ -173,21 +176,14 @@ public function getCredentials(Request $request)
173176
);
174177
}
175178

176-
if (!isset($json[$this->loginUsernamePath])) {
177-
throw new AuthenticationException($this->loginUsernamePath . ' mandatory', 420);
178-
}
179-
180-
if (!isset($json[$this->loginPasswordPath])) {
181-
throw new AuthenticationException($this->loginPasswordPath . ' mandatory', 420);
182-
}
183-
184-
return array(
185-
'token' => $json[$this->csrfTokenParameter],
186-
'username' => $json[$this->loginUsernamePath],
187-
'password' => $json[$this->loginPasswordPath]
188-
);
179+
return $this->checkAndBuildFullCredentials($json);
189180
}
190181

182+
/**
183+
* @param mixed $credentials
184+
* @param UserProviderInterface $userProvider
185+
* @return mixed|null|UserInterface
186+
*/
191187
public function getUser($credentials, UserProviderInterface $userProvider)
192188
{
193189
if (false === $this->csrfTokenManager->isTokenValid(new SymfonyCsrfToken($this->csrfTokenId, $credentials['token']))) {
@@ -216,6 +212,11 @@ public function getUser($credentials, UserProviderInterface $userProvider)
216212
}
217213
}
218214

215+
/**
216+
* @param mixed $credentials
217+
* @param UserInterface $user
218+
* @return bool
219+
*/
219220
public function checkCredentials($credentials, UserInterface $user)
220221
{
221222
// The CsrfTokenAuthenticator has just been used to validate csrf token on non GET route
@@ -230,12 +231,23 @@ public function checkCredentials($credentials, UserInterface $user)
230231
return true;
231232
}
232233

234+
/**
235+
* @param Request $request
236+
* @param TokenInterface $token
237+
* @param string $providerKey
238+
* @return null|Response
239+
*/
233240
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
234241
{
235242
// on success, let the request continue
236243
return null;
237244
}
238245

246+
/**
247+
* @param Request $request
248+
* @param AuthenticationException $exception
249+
* @return null|JsonResponse|Response
250+
*/
239251
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
240252
{
241253
$message = $exception->getMessage() ? $exception->getMessage() : strtr($exception->getMessageKey(), $exception->getMessageData());
@@ -265,8 +277,32 @@ public function start(Request $request, AuthenticationException $authException =
265277
return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
266278
}
267279

280+
/**
281+
* @return bool
282+
*/
268283
public function supportsRememberMe()
269284
{
270285
return false;
271286
}
287+
288+
/**
289+
* @param $json
290+
* @return array
291+
*/
292+
protected function checkAndBuildFullCredentials($json): array
293+
{
294+
if (!isset($json[$this->loginUsernamePath])) {
295+
throw new AuthenticationException($this->loginUsernamePath . ' mandatory', 420);
296+
}
297+
298+
if (!isset($json[$this->loginPasswordPath])) {
299+
throw new AuthenticationException($this->loginPasswordPath . ' mandatory', 420);
300+
}
301+
302+
return array(
303+
'token' => $json[$this->csrfTokenParameter],
304+
'username' => $json[$this->loginUsernamePath],
305+
'password' => $json[$this->loginPasswordPath]
306+
);
307+
}
272308
}

0 commit comments

Comments
 (0)