Completed
Push — master ( 535b09...0667cb )
by
unknown
56:23
created

LoadLeadsData   B

Complexity

Total Complexity 17

Size/Duplication

Total Lines 235
Duplicated Lines 15.32 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 3
Bugs 1 Features 1
Metric Value
wmc 17
lcom 1
cbo 17
dl 36
loc 235
rs 7.8571
c 3
b 1
f 1

10 Methods

Rating   Name   Duplication   Size   Complexity  
A getDependencies() 0 9 1
A setContainer() 0 5 1
A load() 0 6 1
A initSupportingEntities() 10 10 2
A loadSources() 0 21 2
B loadLeads() 26 34 5
A setSecurityContext() 0 6 1
A createLead() 0 67 2
A persist() 0 4 1
A flush() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace OroCRM\Bundle\DemoDataBundle\Migrations\Data\Demo\ORM;
4
5
use Symfony\Component\DependencyInjection\ContainerInterface;
6
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
7
8
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
9
use Doctrine\Common\DataFixtures\AbstractFixture;
10
use Doctrine\Common\Persistence\ObjectManager;
11
use Doctrine\Common\Collections\Collection;
12
use Doctrine\ORM\EntityManager;
13
14
use Oro\Bundle\AddressBundle\Entity\Address;
15
use Oro\Bundle\AddressBundle\Entity\Country;
16
use Oro\Bundle\AddressBundle\Entity\Region;
17
use Oro\Bundle\EntityConfigBundle\Config\ConfigManager;
18
use Oro\Bundle\EntityExtendBundle\Entity\AbstractEnumValue;
19
use Oro\Bundle\EntityExtendBundle\Entity\Repository\EnumValueRepository;
20
use Oro\Bundle\EntityExtendBundle\Tools\ExtendHelper;
21
use Oro\Bundle\OrganizationBundle\Entity\Organization;
22
use OroCRM\Bundle\SalesBundle\Entity\LeadAddress;
23
use OroCRM\Bundle\SalesBundle\Entity\LeadPhone;
24
use OroCRM\Bundle\SalesBundle\Entity\LeadEmail;
25
use OroCRM\Bundle\SalesBundle\Entity\Lead;
26
use Oro\Bundle\SecurityBundle\Authentication\Token\UsernamePasswordOrganizationToken;
27
use Oro\Bundle\UserBundle\Entity\User;
28
29
class LoadLeadsData extends AbstractFixture implements ContainerAwareInterface, DependentFixtureInterface
30
{
31
    const FLUSH_MAX = 50;
32
33
    /** @var ContainerInterface */
34
    protected $container;
35
36
    /** @var User[] */
37
    protected $users;
38
39
    /** @var Country[] */
40
    protected $countries;
41
42
    /** @var  EntityManager */
43
    protected $em;
44
45
    /** @var  ConfigManager */
46
    protected $configManager;
47
48
    /**
49
     * @var Organization
50
     */
51
    protected $organization;
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function getDependencies()
57
    {
58
        return [
59
            'OroCRM\Bundle\DemoDataBundle\Migrations\Data\Demo\ORM\LoadUsersData',
60
            'OroCRM\Bundle\DemoDataBundle\Migrations\Data\Demo\ORM\LoadAccountData',
61
            'OroCRM\Bundle\DemoDataBundle\Migrations\Data\Demo\ORM\LoadLeadSourceData',
62
            'OroCRM\Bundle\DemoDataBundle\Migrations\Data\Demo\ORM\LoadChannelData'
63
        ];
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     */
69
    public function setContainer(ContainerInterface $container = null)
70
    {
71
        $this->container = $container;
72
        $this->configManager = $container->get('oro_entity_config.config_manager');
0 ignored issues
show
Bug introduced by
It seems like $container is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
73
    }
74
75
    /**
76
     * {@inheritDoc}
77
     */
78
    public function load(ObjectManager $manager)
79
    {
80
        $this->initSupportingEntities($manager);
81
        $this->loadLeads($manager);
82
        $this->loadSources($manager);
83
    }
84
85
    /**
86
     * @param ObjectManager $manager
87
     */
88 View Code Duplication
    protected function initSupportingEntities(ObjectManager $manager = null)
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...
89
    {
90
        if ($manager) {
91
            $this->em = $manager;
92
        }
93
94
        $this->users = $this->em->getRepository('OroUserBundle:User')->findAll();
95
        $this->countries = $this->em->getRepository('OroAddressBundle:Country')->findAll();
96
        $this->organization = $this->getReference('default_organization');
97
    }
98
99
    /**
100
     * @param ObjectManager $manager
101
     */
102
    public function loadSources(ObjectManager $manager)
103
    {
104
        $className = ExtendHelper::buildEnumValueClassName('lead_source');
105
106
        /** @var EnumValueRepository $enumRepo */
107
        $enumRepo = $manager->getRepository($className);
108
109
        /** @var AbstractEnumValue[] $sources */
110
        $sources = $enumRepo->findAll();
111
        $randomSource = count($sources)-1;
112
113
        $leads = $this->em->getRepository('OroCRMSalesBundle:Lead')->findAll();
114
115
        foreach ($leads as $lead) {
116
            /** @var Lead $lead */
117
            $source = $sources[mt_rand(0, $randomSource)];
118
            $lead->setSource($source);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class OroCRM\Bundle\SalesBundle\Entity\Lead as the method setSource() does only exist in the following sub-classes of OroCRM\Bundle\SalesBundle\Entity\Lead: OroCRM\Bundle\SalesBundl...s\Unit\Fixture\LeadStub. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
119
            $manager->persist($lead);
120
        }
121
        $manager->flush();
122
    }
123
124
    public function loadLeads(ObjectManager $manager)
125
    {
126
        $dictionaryDir = $this->container
127
            ->get('kernel')
128
            ->locateResource('@OroCRMDemoDataBundle/Migrations/Data/Demo/ORM/dictionaries');
129
130
        $handle = fopen($dictionaryDir . DIRECTORY_SEPARATOR. "leads.csv", "r");
131 View Code Duplication
        if ($handle) {
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...
132
            $headers = array();
133
            if (($data = fgetcsv($handle, 1000, ",")) !== false) {
134
                //read headers
135
                $headers = $data;
136
            }
137
            $randomUser = count($this->users) - 1;
138
            $i = 0;
139
            while (($data = fgetcsv($handle, 1000, ",")) !== false) {
140
                $user = $this->users[mt_rand(0, $randomUser)];
141
                $this->setSecurityContext($user);
142
143
                $data = array_combine($headers, array_values($data));
144
145
                $lead = $this->createLead($manager, $data, $user);
146
                $this->persist($this->em, $lead);
147
148
                $i++;
149
                if ($i % self::FLUSH_MAX == 0) {
150
                    $this->flush($this->em);
151
                }
152
            }
153
154
            $this->flush($this->em);
155
            fclose($handle);
156
        }
157
    }
158
159
    /**
160
     * @param User $user
161
     */
162
    protected function setSecurityContext($user)
163
    {
164
        $securityContext = $this->container->get('security.context');
165
        $token = new UsernamePasswordOrganizationToken($user, $user->getUsername(), 'main', $this->organization);
166
        $securityContext->setToken($token);
167
    }
168
169
    /**
170
     * @param  array $data
171
     * @param User $user
172
     *
173
     * @return Lead
174
     */
175
    protected function createLead(ObjectManager $manager, array $data, $user)
176
    {
177
        $lead = new Lead();
178
179
        $className = ExtendHelper::buildEnumValueClassName(Lead::INTERNAL_STATUS_CODE);
180
        $defaultStatus = $manager->getRepository($className)->find(ExtendHelper::buildEnumValueId('new'));
181
        
182
        $lead->setStatus($defaultStatus);
183
        $lead->setName($data['Company']);
184
        $lead->setFirstName($data['GivenName']);
185
        $lead->setLastName($data['Surname']);
186
187
        $phone = new LeadPhone($data['TelephoneNumber']);
188
        $phone->setPrimary(true);
189
        $lead->addPhone($phone);
190
191
        $email = new LeadEmail($data['EmailAddress']);
192
        $email->setPrimary(true);
193
        $lead->addEmail($email);
194
195
        $lead->setCompanyName($data['Company']);
196
        $lead->setOwner($user);
197
        $lead->setOrganization($this->organization);
198
        $lead->setDataChannel($this->getReference('default_channel'));
199
        $lead->setTwitter($data['Twitter']);
200
201
        /** @var LeadAddress $address */
202
        $address = new LeadAddress();
203
        $address->setLabel('Primary Address');
204
        $address->setCity($data['City']);
205
        $address->setStreet($data['StreetAddress']);
206
        $address->setPostalCode($data['ZipCode']);
207
        $address->setFirstName($data['GivenName']);
208
        $address->setLastName($data['Surname']);
209
        $address->setPrimary(true);
210
211
        $isoCode = $data['Country'];
212
        $country = array_filter(
213
            $this->countries,
214
            function (Country $a) use ($isoCode) {
215
                return $a->getIso2Code() == $isoCode;
216
            }
217
        );
218
219
        $country = array_values($country);
220
        /** @var Country $country */
221
        $country = $country[0];
222
223
        $idRegion = $data['State'];
224
        /** @var Collection $regions */
225
        $regions = $country->getRegions();
226
227
        $region = $regions->filter(
228
            function (Region $a) use ($idRegion) {
229
                return $a->getCode() == $idRegion;
230
            }
231
        );
232
233
        $address->setCountry($country);
234
        if (!$region->isEmpty()) {
235
            $address->setRegion($region->first());
236
        }
237
238
        $lead->addAddress($address);
239
240
        return $lead;
241
    }
242
243
    /**
244
     * Persist object
245
     *
246
     * @param mixed $manager
247
     * @param mixed $object
248
     */
249
    private function persist($manager, $object)
250
    {
251
        $manager->persist($object);
252
    }
253
254
    /**
255
     * Flush objects
256
     *
257
     * @param mixed $manager
258
     */
259
    private function flush($manager)
260
    {
261
        $manager->flush();
262
    }
263
}
264