GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

ImportService::fixHeadersEncoding()   A
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 1
nop 1
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Sigmapix\Sonata\ImportBundle\Service;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Port\Csv\CsvReader;
7
use Port\Doctrine\DoctrineWriter;
8
use Port\Excel\ExcelReader;
9
use Port\Steps\Step\MappingStep;
10
use Port\Steps\StepAggregator;
11
use Sonata\AdminBundle\Admin\AdminInterface;
12
use Symfony\Component\DependencyInjection\ContainerInterface;
13
use Symfony\Component\Form\Form;
14
use Symfony\Component\Form\SubmitButton;
15
use Symfony\Component\HttpFoundation\File\UploadedFile;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Session\SessionInterface;
18
use Sigmapix\Sonata\ImportBundle\Step\AddParentStep;
19
use Symfony\Component\PropertyAccess\PropertyPath;
20
21
final class ImportService
22
{
23
    /**
24
     * @var EntityManagerInterface
25
     */
26
    private $em;
27
28
    /**
29
     * @var SessionInterface
30
     */
31
    private $session;
32
33
    /**
34
     * @var ContainerInterface
35
     */
36
    private $container;
37
38
    /**
39
     * @var string
40
     */
41
    private $doctrineWriterClass;
42
43
    /**
44
     * ImportService constructor.
45
     *
46
     * @param EntityManagerInterface $em
47
     * @param $session
48
     * @param ContainerInterface $container
49
     * @param string             $doctrineWriterClass
50
     */
51
    public function __construct(EntityManagerInterface $em, $session, ContainerInterface $container, string $doctrineWriterClass)
52
    {
53
        $this->em = $em;
54
        $this->session = $session;
55
        $this->container = $container;
56
        $this->doctrineWriterClass = $doctrineWriterClass;
57
    }
58
59
    /**
60
     * @param UploadedFile $file
61
     *
62
     * @return array
63
     */
64
    public function getHeaders(UploadedFile $file)
65
    {
66
        $reader = $this->getReader($file);
67
        $columnHeaders = array_filter($reader->getColumnHeaders(), function ($h) {return null !== $h; });
68
        $headers = array_flip($this->fixHeadersEncoding($columnHeaders));
69
        array_walk($headers, function (&$v, $k) use ($headers) { $v = $k; });
70
71
        return $headers;
72
    }
73
74
    /**
75
     * @param UploadedFile   $file
76
     * @param Form           $form
77
     * @param AdminInterface $admin
78
     *
79
     * @return mixed
80
     */
81
    public function import(UploadedFile $file, Form $form, AdminInterface $admin, Request $request)
82
    {
83
        $mapping = [];
84
        foreach ($form as $f) {
85
            if ($f instanceof SubmitButton) {
86
                continue;
87
            }
88
            $mapping[$f->getName()] = $f->getNormData();
89
        }
90
91
        $reader = $this->getReader($file);
92
        // Replace columnsHeader names with entity field name in our $mapping
93
        $columnHeaders = array_map(function ($h) use ($mapping) {
94
            $k = array_search($h, (array) $mapping, true);
95
96
            return false === $k ? $h : $k;
97
        }, $this->fixHeadersEncoding($reader->getColumnHeaders()));
98
        $reader->setColumnHeaders($columnHeaders);
99
100
        /** @var DoctrineWriter $writer */
101
        $writer = new $this->doctrineWriterClass($this->em, \get_class($form->getData()));
102
        if (method_exists($writer, 'setContainer')) {
103
            $writer->setContainer($this->container);
104
        }
105
        $writer->disableTruncate();
106
107
        $workflow = new StepAggregator($reader);
108
109
        if ($admin->isChild() && $admin->getParentAssociationMapping()) {
0 ignored issues
show
Bug introduced by
The method getParentAssociationMapping() does not exist on Sonata\AdminBundle\Admin\AdminInterface. Did you maybe mean getParent()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
110
            $parent = $admin->getParent()->getObject($request->get($admin->getParent()->getIdParameter()));
111
            $propertyAccessor = $admin->getConfigurationPool()->getPropertyAccessor();
0 ignored issues
show
Unused Code introduced by
$propertyAccessor is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
112
            $propertyPath = new PropertyPath($admin->getParentAssociationMapping());
0 ignored issues
show
Bug introduced by
The method getParentAssociationMapping() does not exist on Sonata\AdminBundle\Admin\AdminInterface. Did you maybe mean getParent()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
113
            $workflow->addStep(new AddParentStep($propertyPath, $parent));
114
        }
115
116
        $workflow->addWriter($writer);
117
        $admin->configureImportSteps($workflow);
0 ignored issues
show
Bug introduced by
The method configureImportSteps() does not exist on Sonata\AdminBundle\Admin\AdminInterface. Did you maybe mean configure()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
118
119
        $result = $workflow->process();
120
121
        return $result;
122
    }
123
124
    /**
125
     * Get session.
126
     *
127
     * @return
128
     */
129
    public function getSession()
130
    {
131
        return $this->session;
132
    }
133
134
    /**
135
     * Set session.
136
     *
137
     * @return $this
138
     */
139
    public function setSession($session)
140
    {
141
        $this->session = $session;
142
143
        return $this;
144
    }
145
146
    private function fixHeadersEncoding($columnHeaders)
147
    {
148
        $columnHeaders = array_map(
149
            function ($h) {
150
                if (!empty($h) && \is_string($h) && 'UTF-8' !== mb_detect_encoding($h)) {
151
                    $h = utf8_encode($h);
152
                }
153
154
                return trim($h);
155
            }, $columnHeaders);
156
157
        return $columnHeaders;
158
    }
159
160
    /**
161
     * @param UploadedFile $file
162
     *
163
     * @return CsvReader|ExcelReader
164
     */
165
    private function getReader(UploadedFile $file)
166
    {
167
        $pathFile = $file->getRealPath();
168
        $fileExtension = $file->guessExtension();
169
        $excelExtensions = ['xls', 'xlsx', 'zip'];
170
171
        if (\in_array($fileExtension, $excelExtensions)) {
172
            $reader = new ExcelReader(new \SplFileObject($pathFile), 0, 0, true);
173
        } else {
174
            $reader = new CsvReader(new \SplFileObject($pathFile), ';');
175
            $reader->setHeaderRowNumber(0, CsvReader::DUPLICATE_HEADERS_INCREMENT);
176
        }
177
178
        return $reader;
179
    }
180
}
181