testElementDirectlyInTheForm()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 35
rs 8.8571
cc 1
eloc 24
nc 1
nop 0
1
<?php
2
3
namespace ZFBrasil\Test\DoctrineMoneyModule\Form;
4
5
use StdClass;
6
use PHPUnit_Framework_TestCase as TestCase;
7
use Money\Money;
8
use Money\InvalidArgumentException;
9
use Zend\Form\Form;
10
use Zend\Form\Fieldset;
11
use Zend\Form\FormElementManager;
12
use Zend\Stdlib\Hydrator\ClassMethods;
13
use ZFBrasil\DoctrineMoneyModule\Form\Factory\MoneyFieldsetFactory;
14
use ZFBrasil\DoctrineMoneyModule\Form\MoneyFieldset;
15
use ZFBrasil\Test\DoctrineMoneyModule\TestAsset\Model\HasMoneyPropertyModel;
16
use Zend\Stdlib\Hydrator\ObjectProperty;
17
18
/**
19
 * Test to see if Form returns a valid object on getData.
20
 *
21
 * @author  Fábio Carneiro <[email protected]>
22
 * @license MIT
23
 */
24
class FormIntegrationTest extends TestCase
25
{
26
    /**
27
     * @return MoneyFieldset
28
     */
29
    private function getMoneyFieldset()
30
    {
31
        $factory = new MoneyFieldsetFactory();
32
        $formManager = $this->getMock(FormElementManager::class);
33
34
        return $factory($formManager);
35
    }
36
37
    public function testElementDirectlyInTheForm()
38
    {
39
        $element = $this->getMoneyFieldset();
40
        $element->init();
41
42
        $form = new Form();
43
        $form->setHydrator(new ObjectProperty());
0 ignored issues
show
Deprecated Code introduced by
The class Zend\Stdlib\Hydrator\ObjectProperty has been deprecated with message: Use Zend\Hydrator\ObjectProperty from zendframework/zend-hydrator instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
44
        $form->setObject(new StdClass());
45
        $form->add($element, ['name' => 'money']);
46
47
        $this->assertFalse($form->setData([])->isValid());
48
        $this->assertFalse($form->setData(['money' => ['amount' => '123', 'currency' => '']])->isValid());
49
        $this->assertFalse($form->setData(['money' => ['amount' => '', 'currency' => 'BRL']])->isValid());
50
51
        $data = [
52
            'money' => [
53
                'amount' => '500.20',
54
                'currency' => 'BRL',
55
            ],
56
        ];
57
58
        $form->setData($data);
59
60
        $this->assertTrue($form->isValid());
61
62
        $amountValue = $form->get('money')->get('amount')->getValue();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Form\ElementInterface as the method get() does only exist in the following implementations of said interface: ZFBrasil\DoctrineMoneyModule\Form\MoneyFieldset, Zend\Form\Element\Collection, Zend\Form\Fieldset, Zend\Form\Form, Zend\Form\InputFilterProviderFieldset.

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...
63
        $currencyValue = $form->get('money')->get('currency')->getValue();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Form\ElementInterface as the method get() does only exist in the following implementations of said interface: ZFBrasil\DoctrineMoneyModule\Form\MoneyFieldset, Zend\Form\Element\Collection, Zend\Form\Fieldset, Zend\Form\Form, Zend\Form\InputFilterProviderFieldset.

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...
64
        $object = $form->getData()->money;
65
66
        $this->assertSame('500.20', $amountValue);
67
        $this->assertSame('BRL', $currencyValue);
68
        $this->assertInstanceOf(Money::class, $object);
69
        $this->assertSame(50020, $object->getAmount());
70
        $this->assertSame('BRL', $object->getCurrency()->getName());
71
    }
72
73
    public function testElementInAFieldsetForSomeModel()
74
    {
75
        $element = $this->getMoneyFieldset();
76
        $element->init();
77
78
        $fieldset = new Fieldset('hasMoneyElementFieldset');
79
        $fieldset->add($element, ['name' => 'price']);
80
        $fieldset->setHydrator(new ClassMethods());
0 ignored issues
show
Deprecated Code introduced by
The class Zend\Stdlib\Hydrator\ClassMethods has been deprecated with message: Use Zend\Hydrator\ClassMethods from zendframework/zend-hydrator instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
81
        $fieldset->setUseAsBaseFieldset(true);
82
83
        $form = new Form();
84
        $form->add($fieldset);
85
86
        // todo: can't load this
87
        $form->bind(new HasMoneyPropertyModel());
88
89
        $data = [
90
            'hasMoneyElementFieldset' => [
91
                'price' => [
92
                    'amount' => '500.25',
93
                    'currency' => 'BRL',
94
                ],
95
            ],
96
        ];
97
98
        $form->setData($data);
99
        $this->assertTrue($form->isValid());
100
101
        $amountValue = $form->get('hasMoneyElementFieldset')->get('price')->get('amount')->getValue();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Form\ElementInterface as the method get() does only exist in the following implementations of said interface: ZFBrasil\DoctrineMoneyModule\Form\MoneyFieldset, Zend\Form\Element\Collection, Zend\Form\Fieldset, Zend\Form\Form, Zend\Form\InputFilterProviderFieldset.

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...
102
        $currencyValue = $form->get('hasMoneyElementFieldset')->get('price')->get('currency')->getValue();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Zend\Form\ElementInterface as the method get() does only exist in the following implementations of said interface: ZFBrasil\DoctrineMoneyModule\Form\MoneyFieldset, Zend\Form\Element\Collection, Zend\Form\Fieldset, Zend\Form\Form, Zend\Form\InputFilterProviderFieldset.

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...
103
        $object = $form->getData();
104
105
        $this->assertSame('500.25', $amountValue);
106
        $this->assertSame('BRL', $currencyValue);
107
        $this->assertInstanceOf(Money::class, $object->getPrice());
108
        $this->assertSame(50025, $object->getPrice()->getAmount());
109
        $this->assertSame('BRL', $object->getPrice()->getCurrency()->getName());
110
    }
111
112
    /**
113
     * @expectedException InvalidArgumentException
114
     * @expectedExceptionMessage The value could not be parsed as money
115
     */
116
    public function testValueCouldNotBeParsedAsMoney()
117
    {
118
        $element = $this->getMoneyFieldset();
119
        $element->init();
120
121
        $form = new Form();
122
        $form->add($element, ['name' => 'money']);
123
124
        $this->assertFalse($form->setData(['money' => ['amount' => 'bad', 'currency' => 'BRL']])->isValid());
125
    }
126
}
127