Completed
Push — master ( 72a5c2...ae9e87 )
by Valerka
08:45
created

Recaptcha   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 2
cbo 4
dl 0
loc 84
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A render() 0 12 2
A verify() 0 4 1
A filterOptions() 0 10 1
A buildOptions() 0 12 1
1
<?php
2
3
namespace PheRum\Recaptcha;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Collection;
7
use ReCaptcha\ReCaptcha as GoogleReCaptcha;
8
9
class Recaptcha
10
{
11
    /**
12
     * @var array
13
     */
14
    protected $config;
15
    
16
    /**
17
     * @var GoogleReCaptcha
18
     */
19
    protected $recaptcha;
20
    
21
    /**
22
     * @param array $config
23
     */
24
    public function __construct(array $config)
25
    {
26
        $this->config = $config;
27
        
28
        $this->recaptcha = new GoogleReCaptcha($this->config['private_key']);
29
    }
30
    
31
    /**
32
     * @param array $options
33
     *
34
     * @return mixed
35
     */
36
    public function render($options = [])
37
    {
38
        $mergedOptions = array_merge($this->config['options'], $options);
39
        
40
        $data = [
41
            'public_key' => $this->config['public_key'],
42
            'lang'       => array_only($mergedOptions, 'lang') ? $mergedOptions['lang'] : null,
43
            'options'    => $this->buildOptions($mergedOptions),
44
        ];
45
        
46
        return view('pherum::recaptcha', $data)->render();
47
    }
48
    
49
    /**
50
     * @param \Illuminate\Http\Request $request
51
     *
52
     * @return bool
53
     */
54
    public function verify(Request $request)
55
    {
56
        return $this->recaptcha->verify($request->get('g-recaptcha-response'), $request->ip())->isSuccess();
57
    }
58
    
59
    /**
60
     * @param array $options
61
     *
62
     * @return array
63
     */
64
    protected function filterOptions(array $options = [])
65
    {
66
        return array_only($options, [
67
            'data-theme',
68
            'data-type',
69
            'data-size',
70
            'data-tabindex',
71
            'data-expired-callback',
72
        ]);
73
    }
74
    
75
    /**
76
     * @param array $options
77
     *
78
     * @return array|string
79
     */
80
    protected function buildOptions(array $options = [])
81
    {
82
        $options = $this->filterOptions($options);
83
        
84
        $options = Collection::make($options)->reject(function ($value) {
85
            return empty($value);
86
        })->map(function ($value, $key) {
87
            return $key . '="' . $value . '"';
88
        })->implode(', ');
89
        
90
        return $options;
91
    }
92
}
93