Delete.php 4.55 KB
Newer Older
1
2
3
4
5
6
7
8
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 6/1/16
 * Time: 8:52 AM
 */

Marc Egger's avatar
Marc Egger committed
9
namespace IMATHUZH\Qfq\Core;
10

Marc Egger's avatar
Marc Egger committed
11
use IMATHUZH\Qfq\Core\Database\Database;
12
use IMATHUZH\Qfq\Core\Helper\Path;
Marc Egger's avatar
Marc Egger committed
13
14
15
use IMATHUZH\Qfq\Core\Store\Store;
 
use IMATHUZH\Qfq\Core\Helper\HelperFile;
16
17


18
19
20
21
/**
 * Class Delete
 * @package qfq
 */
22
23
24
25
26
27
class Delete {
    /**
     * @var Database
     */
    private $db = null;

28
29
30
31
32
    /**
     * @var Store
     */
    private $store = null;

33
    /**
34
35
     * @param bool $dbIndexData
     * @param bool $phpUnit
Marc Egger's avatar
Marc Egger committed
36
37
38
39
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
40
     */
41
42
    public function __construct($dbIndexData = false, $phpUnit = false) {

43
        #TODO: rewrite $phpUnit to: "if (!defined('PHPUNIT_QFQ')) {...}"
44
        $this->db = new Database($dbIndexData);
45
        $this->store = Store::getInstance('', $phpUnit);
46
47
48
    }

    /**
49
     * Deletes the record id=$recordId from table $tableName.
50
     * If the table has a column named COLUMN_PATH_FILE_NAME and the value of that specific record column points
Carsten  Rose's avatar
Carsten Rose committed
51
52
     * to a file: delete such a file if their are no other records in the same table which also have a reference to
     * that file.
53
     *
Carsten  Rose's avatar
Carsten Rose committed
54
     * @param string $tableName
55
     * @param integer $recordId
Carsten  Rose's avatar
Carsten Rose committed
56
     *
57
     * @param string $primaryKey
Marc Egger's avatar
Marc Egger committed
58
59
60
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
61
     */
62
    public function process($tableName, $recordId, $primaryKey = F_PRIMARY_KEY_DEFAULT) {
63

64
        if ($tableName === false || $tableName === '') {
Marc Egger's avatar
Marc Egger committed
65
            throw new \CodeException('Missing table name', ERROR_MISSING_TABLE_NAME);
66
67
68
        }

        if ($recordId === 0 || $recordId === '') {
Marc Egger's avatar
Marc Egger committed
69
            throw new \CodeException('Invalid record id', ERROR_MISSING_RECORD_ID);
70
71
        }

72
73
        // Take care the necessary target directories exist.
        $cwd = getcwd();
74
        $sitePath = Path::absoluteApp();
75
        if ($cwd === false || $sitePath === false || !HelperFile::chdir($sitePath)) {
Marc Egger's avatar
Marc Egger committed
76
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
77
                json_encode([ERROR_MESSAGE_TO_USER => 'getcwd() failed or SITE_PATH undefined or chdir() failed', ERROR_MESSAGE_TO_DEVELOPER => "getcwd() failed or SITE_PATH undefined or chdir('$sitePath') failed."]),
78
79
                ERROR_IO_CHDIR);

80
81
        }

82
        // Read record first.
83
        $row = $this->db->sql("SELECT * FROM `$tableName` WHERE `$primaryKey`=?", ROW_EXPECT_0_1, [$recordId]);
84
85
        if (count($row) > 0) {

86
            $this->deleteReferencedFiles($row, $tableName, $primaryKey);
87

88
            $this->db->sql("DELETE FROM `$tableName` WHERE `$primaryKey` =? LIMIT 1", ROW_REGULAR, [$recordId]);
89
        } else {
Marc Egger's avatar
Marc Egger committed
90
            throw new \UserFormException(
Marc Egger's avatar
Marc Egger committed
91
                json_encode([ERROR_MESSAGE_TO_USER => 'Record not found in table', ERROR_MESSAGE_TO_DEVELOPER => "Record $recordId not found in table '$tableName'."]),
92
93
                ERROR_RECORD_NOT_FOUND);

94
95
        }

96
        HelperFile::chdir($cwd);
97
98
99
100
    }

    /**
     * Iterates over array $row and searches for column names with substring COLUMN_PATH_FILE_NAME.
101
     * For any column found, check if it references a writable file.
102
103
104
105
106
107
     * If yes: check if there are other records (same table, same column) which references the same file.
     *         If no: delete the file
     *         If yes: do nothing, continue with the next column.
     * If no: do nothing, continue with the next column.
     *
     * @param array $row
Carsten  Rose's avatar
Carsten Rose committed
108
109
     * @param       $tableName
     *
110
     * @param $primaryKey
Marc Egger's avatar
Marc Egger committed
111
112
113
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
114
     */
115
    private function deleteReferencedFiles(array $row, $tableName, $primaryKey) {
116
117

        foreach ($row AS $key => $file) {
118

119
120
121
            if (false === strpos($key, COLUMN_PATH_FILE_NAME)) {
                continue;
            }
122

123
124
125
126
127
            // check if there is a file referenced in the record which have to be deleted too.
            if ($file !== '' && is_writable($file)) {

                // check if there are other records referencing the same file: do not delete the file now.
                // This check won't find duplicates, if they are spread over different columns or tables.
128
                $samePathFileName = $this->db->sql("SELECT COUNT($primaryKey) AS cnt FROM `$tableName` WHERE `$key` LIKE ?", ROW_EXPECT_1, [$file]);
129
                if ($samePathFileName['cnt'] === 1) {
130
                    HelperFile::unlink($file);
131
                    $this->db->deleteSplitFileAndRecord($row[$primaryKey], $tableName);
132
133
134
                }
            }
        }
135
    }
136

137
}