Completed
Pull Request — master (#6)
by
unknown
01:43
created

Subscriber/Backend/QueryManagerCron.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Query Manager
4
 * Copyright (c) Webmatch GmbH
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 */
16
17
namespace WbmQueryManager\Subscriber\Backend;
18
19
use Enlight\Event\SubscriberInterface;
20
use Shopware\Components\DependencyInjection\Container;
21
use WbmQueryManager\Models\Query;
22
23
/**
24
 * Class QueryManagerCron
25
 * @package WbmQueryManager\Subscriber\Backend
26
 */
27
class QueryManagerCron implements SubscriberInterface
28
{
29
30
    /**
31
     * @var Container
32
     */
33
    private $container;
34
35
    /**
36
     * @return array
37
     */
38
    public static function getSubscribedEvents()
39
    {
40
        return [
41
            'Shopware_CronJob_WbmQueryManagerCron' => 'runQueryManagerCron'
42
        ];
43
    }
44
45
    /**
46
     * QueryManagerCron constructor.
47
     * @param Container $container
48
     */
49
    public function __construct(Container $container)
50
    {
51
        $this->container = $container;
52
    }
53
54
    /**
55
     * @return array
56
     */
57
    public function runQueryManagerCron()
58
    {
59
        $now = date('Y-m-d H:i:s');
60
61
        /** @var \Doctrine\ORM\QueryBuilder $qb */
62
        $qb = $this->container->get('models')->createQueryBuilder();
63
        $qb->select(
64
                array(
65
                    'query'
66
                )
67
            )
68
            ->from('WbmQueryManager\Models\Query', 'query')
69
            ->where('query.hasCronjob = 1')
70
            ->andWhere('query.nextRun <= :nextRun')
71
            ->setParameter('nextRun', $now)
72
            ->orderBy('query.name', 'ASC');
73
74
        $cronJobs = $qb->getQuery()->getArrayResult();
75
76
        $data = array();
77
        $clearCacheAfter = false;
78
79
        foreach($cronJobs as $cronJob){
80
            $i = 0;
81
            $numRows = 0;
82
            try {
83
                /** @var \mysqli|\Zend_Db_Statement_Pdo $query */
84
                $query = $this->container->get('wbm_query_manager.db')->query($cronJob['sqlString']);
85
                if($query instanceof \Zend_Db_Statement_Pdo) {
86
                    $query->closeCursor();
87
                }
88
89
                /** @var \Enlight_Components_Snippet_Namespace $snippets */
90
                $snippets = $this->container->get('snippets')->getNamespace("backend/plugins/wbm/querymanager");
91
92
                do {
93
                    if($this->container->get('wbm_query_manager.db')->getColumnCount($query)){
94
                        $records = $this->container->get('wbm_query_manager.db')->fetchAll($query);
95
                        $rowCount = $this->container->get('wbm_query_manager.db')->getRowCount($query);
96
                        $recordFields = array_keys($records[0]);
97
98
                        $date = new \DateTime();
99
100
                        $file = preg_replace("/[^a-z0-9\.]/", "", strtolower($cronJob['name'])) . "_" . $date->format('Y_m_d_h_i_s') . '_' . $i++ . ".csv";
101
102
                        $csvPath = $this->container->get('application')->DocPath() . 'var/log/' . $file;
103
104
                        $outputBuffer = fopen($csvPath, 'w');
105 View Code Duplication
                        foreach(array_merge(array(0 => $recordFields),$records) as $val) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
106
                            fputcsv($outputBuffer, $val, $this->container->get('config')->getByNamespace('WbmQueryManager', 'csv_field_separator'));
107
                        }
108
                        fclose($outputBuffer);
109
110
                        $mailRecipient = $this->container->get('config')->getByNamespace('WbmQueryManager', 'mail_address_receiver');
111
                        if(!empty($cronJob['mailRecipient'])){
112
                            $mailRecipient = $cronJob['mailRecipient'];
113
                        }
114
                        if(!empty($mailRecipient)){
115
                            $mail = clone $this->container->get('mail');
116
                            $mail->setFrom($this->container->get('config')->get('mail'));
117
                            $mail->addTo(explode(',', $mailRecipient));
118
                            $mail->setSubject($cronJob['name']);
119
                            $mail->setBodyText($rowCount . ' ' . $snippets->get('rowsAffected', 'Reihen betroffen'));
120
                            $mail->createAttachment(
121
                                fopen($csvPath, 'r'),
122
                                'application/pdf',
123
                                \Zend_Mime::DISPOSITION_ATTACHMENT,
124
                                \Zend_Mime::ENCODING_BASE64,
125
                                $file
126
                            );
127
                            $mail->send();
128
                        }
129
130
                        if(!$this->container->get('config')->getByNamespace('WbmQueryManager', 'log_csv')){
131
                            unlink($csvPath);
132
                        }
133
134
                        $numRows += $rowCount;
135
                    } else {
136
                        $numRows += $this->container->get('wbm_query_manager.db')->getRowCount($query);
137
                    }
138
                } while ($this->container->get('wbm_query_manager.db')->nextResult($query));
139
140
                $this->container->get('wbm_query_manager.db')->close($query);
141
142
                $result = $numRows . ' ' . $snippets->get('rowsAffected', 'Reihen betroffen');
143
            } catch (\Exception $e) {
144
                $result = $e->getMessage();
145
            }
146
            /** @var Query $query */
147
            $query = $this->container->get('models')->getRepository('WbmQueryManager\Models\Query')->find($cronJob['id']);
148
            $query->setLastLog($result);
149
            /** @var \DateTime $lastRun */
150
            $lastRun = $query->getLastRun() ? : new \DateTime();
151
            $query->setLastRun($now);
152
            $query->setNextRun($lastRun->add(\DateInterval::createFromDateString($query->getIntervalInt() . ' seconds')));
153
154
            $this->container->get('models')->persist($query);
155
            $this->container->get('models')->flush();
156
            $this->container->get('models')->clear();
157
158
            if($cronJob['clear_cache']){
159
                $clearCacheAfter = true;
160
            }
161
162
            $data[$cronJob['name']] = $result;
163
        }
164
165
        if($clearCacheAfter){
166
            $cacheManager = $this->container->get('shopware.cache_manager');
167
            $cacheManager->clearHttpCache();
168
            $cacheManager->clearTemplateCache();
169
            $cacheManager->clearConfigCache();
170
            $cacheManager->clearSearchCache();
171
            $cacheManager->clearProxyCache();
172
        }
173
174
        return $data;
175
    }
176
}
177