Completed
Push — master ( cc9b98...5f169a )
by Louis
14s
created

PhotoUpdateCommand::execute()   D

Complexity

Conditions 15
Paths 67

Size

Total Lines 86
Code Lines 61

Duplication

Lines 31
Ratio 36.05 %

Importance

Changes 0
Metric Value
dl 31
loc 86
rs 4.9121
c 0
b 0
f 0
cc 15
eloc 61
nc 67
nop 2

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
namespace KI\UserBundle\Command;
4
5
use KI\UserBundle\Entity\User;
6
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class PhotoUpdateCommand extends ContainerAwareCommand
13
{
14
    protected function configure()
15
    {
16
        $this
17
            ->setName('upont:update:photo')
18
            ->setDescription('Import missing photos from Facebook for the given promo')
19
            ->addArgument('promo', InputArgument::REQUIRED, 'The promo whose photos are to be updated.')
20
            ->addOption('preview', 'p', InputOption::VALUE_NONE, 'Make a preview of the photos to be imported without importing them')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 134 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
21
            ->addOption('similarity-threshold', 's', InputOption::VALUE_REQUIRED, 'Similarity threshold with Fb profiles above which photos are imported (in % between 0 and 100)', 85)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 183 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
22
        ;
23
    }
24
25
    protected function execute(InputInterface $input, OutputInterface $output)
26
    {
27
        $em = $this->getContainer()->get('doctrine')->getManager();
28
        $repo = $this->getContainer()->get('doctrine')->getRepository(User::class);
29
        $curlService = $this->getContainer()->get('ki_core.service.curl');
30
        $imageService = $this->getContainer()->get('ki_core.service.image');
31
        $fbToken = $this->getContainer()->getParameter('facebook_token');
32
33
        $users = $repo->findByPromo($input->getArgument('promo'));
34
35
        $token = '?access_token=' . $fbToken;
36
37
        // Ids des différents groupes facebook
38 View Code Duplication
        switch ($input->getArgument('promo')) {
39
            // Attention, toujours préciser l'id facebook de la promo d'après
40
            // pour avoir les étrangers
41
            case '015':
42
                $id = '359646667495742';
43
                break;  // Wei't spirit
44
            case '016':
45
                $id = '1451446761806184';
46
                break; // Wei't the phoque
47
            case '017':
48
                $id = '737969042997359';
49
                break;  // F'wei'ght Club
50
            case '018':
51
                $id = '1739424532975028';
52
                break;  // WEI'STED
53
            case '019':
54
                $id = '313192685791329';
55
                break;  // WEI'T FOR IT
56
            case '020':
57
                $id = '313192685791329';
58
                break;  // WEI'T FOR IT
59
            default:
60
                return;
61
        }
62
63
        // On récupère la liste des membres
64
        $baseUrl = 'https://graph.facebook.com/v2.10';
65
        $data = json_decode($curlService->curl($baseUrl . '/' . $id . '/members' . $token . '&limit=10000'), true);
66
67
        $updateCount = 0;
68
        $unfoundCount = 0;
69
70
        $output->writeln('Fb photos '.($input->getOption('preview') ? 'would be ' : '').'imported for the following people (> '.$input->getOption('similarity-threshold').'% similar) :');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 186 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
71
72
        foreach ($users as $user) {
73
            $bestMatch = null;
74
            $bestPercent = -1;
75
76
            if ($user->imageUrl() === 'uploads/others/default-user.png') {
77 View Code Duplication
                foreach ($data['data'] as $member) {
78
                    $percent = $this->isSimilar($user, $member);
79
                    if ($percent > $bestPercent) {
80
                        $bestPercent = $percent;
81
                        $bestMatch = $member;
82
                    }
83
                }
84
85
                if ($bestPercent > $input->getOption('similarity-threshold')) {
86
                    if (!$input->getOption('preview')) {
87
                        $url = '/' . $bestMatch['id'] . '/picture' . $token . '&width=9999&redirect=false';
88
                        $dataImage = json_decode($curlService->curl($baseUrl . $url), true);
89
                        $image = $imageService->upload($dataImage['data']['url'], true);
90
                        $user->setImage($image);
91
                    }
92
                    $output->writeln($user->getFirstName().' '.$user->getLastName().' <- '.$bestMatch['name'].' ('.$bestPercent.'% similar)');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 142 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
93
                    $updateCount++;
94
                }
95
                else {
96
                    $unfoundCount++;
97
                }
98
99
                $em->flush();
100
            }
101
        }
102
        $output->writeln(
103
          ['End of list',
104
          '',
105
          'Students in promo '.$input->getArgument('promo').': '.count($users),
106
          'Missing photos in promo: '.($updateCount+$unfoundCount),
107
          ($input->getOption('preview') ? 'To be i' : 'I').'mported missing photos :'.$updateCount,
108
          'Remaining missing photos (unfound Facebook profiles): '.$unfoundCount
109
          ]);
110
    }
111
112
    // Compare un User uPont et un utilisateur Facebook et essaye de deviner si
113
    // ce sont les mêmes personnes
114
    private function isSimilar(User $user, array $member)
115
    {
116
        $percent = 0;
117
        similar_text($user->getFirstName() . ' ' . $user->getLastName(), $member['name'], $percent);
118
        return $percent;
119
    }
120
}
121