Completed
Push — develop ( dfe314...df0194 )
by
unknown
07:26
created

AjaxUrl::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license    MIT
7
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
8
 */
9
10
/** */
11
namespace Core\View\Helper;
12
13
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
14
use Zend\View\Helper\AbstractHelper;
15
use Zend\View\Renderer\PhpRenderer;
16
17
/**
18
 * Builds urls to use the ajax call api.
19
 * The basepath is prepended automatically.
20
 *
21
 * Build urls with name and optional params
22
 * <pre>
23
 * <a href="<?=$this->ajaxUrl('ajaxEventName')?>">Link withoout params (e.g. "?ajax=ajaxEventName")</a>
24
 * <a href="<?=$this->ajaxUrl('anotherEvent', ['param1' => 'value1'])?>">Link: ?ajax=anotherEvent&param1=value1</a>
25
 * </pre>
26
 *
27
 * Build urls by passing only params:
28
 * <pre>
29
 * <?=$this->ajaxUrl(['ajax' => 'name', 'param1' => 'value', ...])?>
30
 * </pre>
31
 *
32
 * Note:
33
 *      When passing only parameters array, a key named "ajax" is REQUIRED.
34
 *
35
 * @author Mathias Gelhausen <[email protected]>
36
 * @since  0.29
37
 */
38
class AjaxUrl extends AbstractHelper
39
{
40
    /**
41
     * The basepath
42
     *
43
     * @var string
44
     */
45
    protected $basePath;
46
47
    /**
48
     * @param string $basePath
49
     */
50
    public function __construct($basePath = '')
51
    {
52
        $this->basePath = rtrim($basePath, '/') . '/';
53
    }
54
55
    /**
56
     * Build an ajax url.
57
     *
58
     * @param string|array $name
59
     * @param array        $params
60
     *
61
     * @return string
62
     * @throws \InvalidArgumentException
63
     */
64
    public function __invoke($name, array $params = [])
65
    {
66
        if (is_array($name)) {
67
            if (!isset($name[ 'ajax' ])) {
68
                throw new \InvalidArgumentException('Key "ajax" is required when passing array as first argument.');
69
            }
70
            $params = $name;
71
        } else {
72
            $params = array_merge(['ajax' => $name], $params);
73
        }
74
75
        $url = sprintf(
76
            '%s?%s',
77
            $this->basePath,
78
            http_build_query($params)
79
        );
80
81
        return $url;
82
    }
83
}
84