Completed
Push — master ( 060b04...657701 )
by
unknown
04:35
created

NewsMapper::find()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
/**
3
 * ownCloud - News
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Alessandro Cosentino <[email protected]>
9
 * @author Bernhard Posselt <[email protected]>
10
 * @copyright Alessandro Cosentino 2012
11
 * @copyright Bernhard Posselt 2012, 2014
12
 */
13
14
namespace OCA\News\Db;
15
16
use OCP\IDBConnection;
17
use OCP\AppFramework\Db\Mapper;
18
19
abstract class NewsMapper extends Mapper {
20
21 16
    public function __construct(IDBConnection $db, $table, $entity) {
22 16
        parent::__construct($db, $table, $entity);
23 16
    }
24
25
    /**
26
     * @param int $id the id of the feed
27
     * @param string $userId the id of the user
28
     * @return \OCP\AppFramework\Db\Entity
29
     */
30
    abstract public function find($id, $userId);
31
32
    /**
33
     * Performs a SELECT query with all arguments appened to the WHERE clause
34
     * The SELECT will be performed on the current table and take the entity
35
     * that is related for transforming the properties into column names
36
     *
37
     * Important: This method does not filter marked as deleted rows!
38
     *
39
     * @param array $search an assoc array from property to filter value
40
     * @param int $limit
41
     * @paran int $offset
42
     * @return array
43
     */
44 10
    public function where(array $search=[], $limit=null, $offset=null) {
45 10
        $entity = new $this->entityClass;
46
47
        // turn keys into sql query filter, e.g. feedId -> feed_id = :feedId
48 10
        $filter = array_map(function ($property) use ($entity) {
49
            // check if the property actually exists on the entity to prevent
50
            // accidental Sql injection
51 10
            if (!property_exists($entity, $property)) {
52
                $msg = 'Property ' . $property . ' does not exist on '
53
                    . $this->entityClass;
54
                throw new \BadFunctionCallException($msg);
55
            }
56
57 10
            $column = $entity->propertyToColumn($property);
58 10
            return $column . ' = :' . $property;
59 10
        }, array_keys($search));
60
61 10
        $andStatement = implode(' AND ', $filter);
62
63 10
        $sql = 'SELECT * FROM `' . $this->getTableName() . '`';
64
65 10
        if (count($search) > 0) {
66 10
            $sql .= 'WHERE ' . $andStatement;
67 10
        }
68
69 10
        return $this->findEntities($sql, $search, $limit, $offset);
70
    }
71
72
}
73