Completed
Push — 17.x ( b10fe2...726eb0 )
by Tim
08:00 queued 06:27
created

CleanUpColumnsEntityMerger   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 62
ccs 0
cts 24
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
B merge() 0 27 7
1
<?php
2
3
/**
4
 * TechDivision\Import\Observers\EntityMergers\CleanUpColumnsEntityMerger
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2020 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Observers\EntityMergers;
22
23
use TechDivision\Import\Loaders\LoaderInterface;
24
use TechDivision\Import\Observers\ObserverInterface;
25
use TechDivision\Import\Subjects\CleanUpColumnsSubjectInterface;
26
use TechDivision\Import\Utils\EntityStatus;
27
28
/**
29
 * An entity merge implementation that is aware of cleaning-up attributes, if NOT in the
30
 * array with the columns that has to be cleaned-up, that has no value in it's columns.
31
 *
32
 * @author    Tim Wagner <[email protected]>
33
 * @copyright 2020 TechDivision GmbH <[email protected]>
34
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
35
 * @link      https://github.com/techdivision/import
36
 * @link      http://www.techdivision.com
37
 */
38
class CleanUpColumnsEntityMerger implements EntityMergerInterface
39
{
40
41
    /**
42
     * Array with virtual column name mappings (this is a temporary
43
     * solution till techdivision/import#179 as been implemented).
44
     *
45
     * @var array
46
     * @todo https://github.com/techdivision/import/issues/179
47
     */
48
    private $reverseHeaderMappings = array();
49
50
    /**
51
     * Initializes the merger with the virtual column mapping
52
     *
53
     * @param \TechDivision\Import\Loaders\LoaderInterface|null $haederMappingLoader The loader for the virtual mappings
54
     */
55
    public function __construct(LoaderInterface $haederMappingLoader = null)
56
    {
57
        $this->reverseHeaderMappings = array_merge(
58
            $this->reverseHeaderMappings,
59
            $haederMappingLoader ? array_flip($haederMappingLoader->load()) : array()
60
        );
61
    }
62
63
    /**
64
     * Merge's and return's the entity with the passed attributes.
65
     *
66
     * @param \TechDivision\Import\Observers\ObserverInterface $observer The observer instance to detect the state for
67
     * @param array                                            $entity   The entity loaded from the database
68
     * @param array                                            $attr     The entity data from the import file
69
     *
70
     * @return array The entity attributes that has to be merged
71
     */
72
    public function merge(ObserverInterface $observer, array $entity, array $attr) : array
73
    {
74
75
        // query whether or not the subject has columns that has to be cleaned-up
76
        if (($subject = $observer->getSubject()) instanceof CleanUpColumnsSubjectInterface) {
77
            // load the columns that has to be cleaned-up
78
            $cleanUpColumns =  $subject->getCleanUpColumns();
79
            // load the column/member names from the attributes
80
            $columnNames = array_keys($attr);
81
82
            // iterate over the column names
83
            foreach ($columnNames as $columnName) {
84
                // we do NOT clean-up column names that has to be cleaned-up
85
                if ($observer->hasValue(isset($this->reverseHeaderMappings[$columnName]) ? $this->reverseHeaderMappings[$columnName] : $columnName) ||
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface TechDivision\Import\Observers\ObserverInterface as the method hasValue() does only exist in the following implementations of said interface: TechDivision\Import\Obse...stractAttributeObserver, TechDivision\Import\Observers\AbstractObserver, TechDivision\Import\Obse...tionalAttributeObserver, TechDivision\Import\Observers\AttributeSetObserver, TechDivision\Import\Obse...ColumnCollectorObserver, TechDivision\Import\Obse...enericValidatorObserver.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
86
                    in_array($columnName, $cleanUpColumns) ||
87
                    $columnName === EntityStatus::MEMBER_NAME
88
                ) {
89
                    continue;
90
                }
91
                // unset the column, because it has NOT been cleaned-up
92
                unset($attr[$columnName]);
93
            }
94
        }
95
96
        // return the processed attributes
97
        return $attr;
98
    }
99
}
100