Completed
Push — master ( 5e4c32...25ba1d )
by Nikolay
11s queued 11s
created

DefaultMarkupProvider::getModule()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace Kolyunya\Codeception\Lib\MarkupValidator;
4
5
use Exception;
6
use Codeception\Lib\ModuleContainer;
7
use Codeception\Module\PhpBrowser;
8
use Codeception\Module\WebDriver;
9
use Kolyunya\Codeception\Lib\MarkupValidator\MarkupProviderInterface;
10
11
/**
12
 * Default markup provider which attemps to get markup from
13
 * `PhpBrowser` and `WebDriver` modules.
14
 */
15
class DefaultMarkupProvider implements MarkupProviderInterface
16
{
17
    /**
18
     * Module container.
19
     *
20
     * @var ModuleContainer
21
     */
22
    private $moduleContainer;
23
24
    /**
25
     * {@inheritDoc}
26
     */
27
    public function __construct(ModuleContainer $moduleContainer, array $config = array())
28
    {
29
        $this->moduleContainer = $moduleContainer;
30
    }
31
32
    /**
33
     * {@inheritDoc}
34
     */
35
    public function getMarkup()
36
    {
37
        try {
38
            return $this->getMarkupFromPhpBrowser();
39
        } catch (Exception $exception) {
40
            // Wasn't able to get markup from the `PhpBrowser` module.
41
        }
42
43
        try {
44
            return $this->getMarkupFromWebDriver();
45
        } catch (Exception $exception) {
46
            // Wasn't able to get markup from the `WebDriver` module.
47
        }
48
49
        throw new Exception('Unable to obtain current page markup.');
50
    }
51
52
    /**
53
     * Returns current page markup form the `PhpBrowser` module.
54
     *
55
     * @return string Current page markup.
56
     */
57
    private function getMarkupFromPhpBrowser()
58
    {
59
        /* @var $phpBrowser PhpBrowser */
60
        $phpBrowser = $this->getModule('PhpBrowser');
61
        $markup = $phpBrowser->_getResponseContent();
62
63
        return $markup;
64
    }
65
66
    /**
67
     * Returns current page markup form the `WebDriver` module.
68
     *
69
     * @return string Current page markup.
70
     */
71
    private function getMarkupFromWebDriver()
72
    {
73
        /* @var $webDriver WebDriver */
74
        $webDriver = $this->getModule('WebDriver');
75
        $markup = $webDriver->webDriver->getPageSource();
76
77
        return $markup;
78
    }
79
80
    /**
81
     * Returns a module instance by its name.
82
     *
83
     * @param string $name Module name.
84
     * @return object Module instance.
85
     */
86
    private function getModule($name)
87
    {
88
        if (!$this->moduleContainer->hasModule($name)) {
89
            throw new Exception(sprintf('«%s» module is not available.', $name));
90
        }
91
92
        $module = $this->moduleContainer->getModule($name);
93
94
        return $module;
95
    }
96
}
97