Completed
Push — master ( b99a49...895f8e )
by Jitendra
07:41 queued 03:12
created

MicroController::indexAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
use Phalcon\Logger;
4
use PhalconExt\Di\ProvidesDi;
5
use PhalconExt\Logger\EchoLogger;
6
use PhalconExt\Mail\Mailer;
7
8
/** Micro Controller */
9
class MicroController
10
{
11
    use ProvidesDi;
12
13
    public function indexAction()
14
    {
15
        return $this->di('view')->render('twig.view', ['engine' => 'Twig', 'mode' => 'MICRO']);
16
    }
17
18
    public function dbAction()
19
    {
20
        $db = $this->di('db');
21
22
        // Assuming we use sqlite for this example
23
        // This table is used to test/demonstrate db extension
24
        $db->execute('CREATE TABLE IF NOT EXISTS phalcon_ext (
25
            id INTEGER PRIMARY KEY AUTOINCREMENT,
26
            name VARCHAR(25),
27
            details VARCHAR(255),
28
            status VARCHAR(10)
29
        )');
30
31
        $db->execute('DELETE FROM phalcon_ext'); // Cleanup so we can test a fresh
32
33
        $info['bulk_insert=1'] = (int) $db->insertAsBulk('phalcon_ext', [
34
            ['name' => 'name1', 'status' => 'status1'],
35
            ['details' => 'detail2', 'name' => 'name2'], // columns dont need to be ordered or balanced
36
        ]);
37
38
        $info['count_by[name1]=1']         = $db->countBy('phalcon_ext', ['name' => 'name1']);
39
        $info['count_by[name2,detail3]=0'] = $db->countBy('phalcon_ext', [
40
            'name'    => 'name1',
41
            'details' => 'detail3',
42
        ]);
43
44
        $info['upsert=1']            = (int) $db->upsert('phalcon_ext', ['details' => 'detail1'], ['name' => 'name1']);
45
        $info['count_by[detail1]=1'] = $db->countBy('phalcon_ext', ['name' => 'name1']);
46
47
        return '<pre>' . print_r($info, 1) . '</pre>'
48
            . '<p>You can check sql logs in <code>example/.var/sql/</code></p>';
49
    }
50
51
    public function diAction()
52
    {
53
        $this->di()->registerAliases([
54
            'theTwig'              => 'twig',
55
            'Phalcon\\Db\\Adapter' => 'db',     // needs alias as `NeedsDb` has its name `_db`
56
            // Mailer::class       => 'mailer', // no need- `DeepNest` uses known name `mailer`
57
        ]);
58
59
        $info['alias[theTwig,twig]=1'] = $this->di('theTwig') === $this->di('twig');
60
61
        $info['resolve[NeedsDb]   =1'] = $this->di(NeedsDb::class) instanceof NeedsDb;
62
        $info['resolve[DeepNest]  =1'] = $this->di(DeepNest::class) instanceof DeepNest;
63
64
        $info['has(NeedsDb)       =1'] = (int) $this->di()->has('NeedsDb');
65
        $info['ProvidesDi(di)     =1'] = (int) ((new DiProvider)->di() instanceof \Phalcon\Di);
66
67
        $this->di()->replace(['twig' => new \stdClass]);
68
        $info['replace[twig]=stdClass'] = get_class($this->di('twig'));
69
        $this->di()->restore();
70
        $info['restore[twig]=PhalconExt\View\Twig'] = get_class($this->di('twig'));
71
72
        return '<pre>' . print_r($info, 1) . '</pre>';
73
    }
74
75
    public function mailAction()
76
    {
77
        $info['newMail[mail]=1'] = $this->di('mailer')->newMail()
78
            ->setTo('me@localhost')->setSubject('Hi')->setBody('Hello')->mail();
79
80
        $info['newTemplateMail[mail]=1'] = $this->di('mailer')->newTemplateMail('mail.template')
81
           ->setTo('me@localhost')->setSubject('Hi')->mail();
82
83
        return '<pre>' . print_r($info, 1) . '</pre>'
84
            . '<p>You can check mail logs in <code>example/.var/mail/</code></p>';
85
    }
86
87
    public function loggerAction()
88
    {
89
        $echo = $this->di(EchoLogger::class, ['config' => ['level' => Logger::INFO]]);
90
91
        ob_start();
92
        $echo->log('info from echo logger<br>', Logger::INFO);
93
        $echo->log('debug from echo logger<br>', Logger::DEBUG); // will not print
94
        $echo->log('error from echo logger<br>', Logger::ERROR);
95
96
        return ob_get_clean();
97
    }
98
99
    public function validationAction()
100
    {
101
        $validation = $this->di('validation'); // or $this->di('validator');
102
103
        // Register new validation rule (if it is used app wide- register when defining in di)
104
        $validation->register('gmail', function ($data) {
105
            return stripos($data['email'] ?? '', '@gmail.com') > 0;
106
        }, 'Field :field must be an email with @gmail.com');
107
108
        $rules = [
109
            'name' => [
110
                'required' => true,
111
                'length'   => ['min' => 5, 'max' => 15],
112
            ],
113
            'id'    => 'required|length:min:1;max:2;|in:domain:1,12,30',
114
            'email' => [
115
                'required' => true,
116
                'gmail'    => true,
117
            ],
118
            // validate if only exist in dataset
119
            'x' => 'length:5|if_exist',
120
        ];
121
122
        // Validate against empty data
123
        $validation->run($rules, []);
124
125
        $info['pass=0']           = (int) $validation->pass();
126
        $info['fail=1']           = (int) $validation->fail();
127
        $info['errors=[0,1...6]'] = $validation->getErrorMessages();
128
129
        return '<pre>' . print_r($info, 1) . '<pre>';
130
    }
131
132
    public function corsAction()
133
    {
134
        return $this->di('view')->render('index/cors', ['cors_uri' => '?_url=/corsheader']);
135
    }
136
137
    public function corsHeaderAction()
138
    {
139
        $response = $this->di('response');
140
141
        return $response->setJsonContent([
142
            'request'  => $this->di('request')->getHeaders(),
143
            'response' => $response->getHeaders()->toArray(),
144
        ]);
145
    }
146
}
147
148
// Dummy classes for DI extension demo
149
class NeedsDb
150
{
151
    public function __construct(\Phalcon\Db\Adapter $_db)
152
    {
153
    }
154
}
155
class DeepNest
156
{
157
    public function __construct(NeedsDb $n, Mailer $mailer)
158
    {
159
    }
160
}
161
class DiProvider
162
{
163
    use ProvidesDi;
164
}
165