1<?php
2
3namespace TbUpdaterModule;
4
5/**
6 * Class Backup
7 *
8 * @package TbUpdaterModule
9 */
10class Backup
11{
12    const PRIMARY = 'id_files_for_backup';
13    const TABLE = 'tbupdater_files_for_backup';
14    const CHUNK_SIZE = 100;
15
16    /**
17     * Get files for backup
18     *
19     * @param int $limit
20     *
21     * @return array
22     */
23    public static function getBackupFiles($limit)
24    {
25        return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(
26            (new DbQuery())
27                ->select('*')
28                ->from(static::TABLE)
29                ->limit($limit),
30            true,
31            false
32        );
33    }
34
35    /**
36     * Add files
37     *
38     * @param array $files
39     *
40     * @return bool
41     */
42    public static function addFiles(array $files)
43    {
44        foreach ($files as &$file) {
45            $file = ['file' => Db::getInstance()->escape($file)];
46        }
47        unset($file);
48
49        $success = true;
50        foreach (array_chunk($files, static::CHUNK_SIZE) as $chunk) {
51            $success &= Db::getInstance()->insert(
52                static::TABLE,
53                $chunk,
54                false,
55                false
56            );
57        }
58
59        return $success;
60    }
61
62    /**
63     * @param int[] $range
64     *
65     * @return bool
66     */
67    public static function removeFiles(array $range)
68    {
69        return Db::getInstance()->delete(
70            static::TABLE,
71            static::PRIMARY.' IN ('.implode(',', array_map('intval', $range)).')',
72            0,
73            false
74        );
75    }
76
77    /**
78     * @return int
79     */
80    public static function count()
81    {
82        return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(
83            (new DbQuery())
84                ->select('COUNT(*)')
85                ->from(static::TABLE),
86            false
87        );
88    }
89}
90