aboutsummaryrefslogtreecommitdiff
path: root/lib/models/Tag.php
blob: 48b15d32c3d22985428ae029765f2b2cb27c43f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php

/**
 * @license GPL2 or any later version
 *
 * @property int $id database column
 * @property string $name database column
 * @property int|null $active database column
 * @property int|null $chdate database column
 * @property int|null $mkdate database column
 * @property SimpleORMapCollection<TagRelation> $related_objects has_many TagRelation
 */
class Tag extends SimpleORMap
{
    protected static function configure($config = [])
    {
        $config['db_table'] = 'tags';
        $config['has_many']['related_objects'] = [
            'class_name' => TagRelation::class,
            'assoc_foreign_key' => 'tag_id',
            'order_by' => 'ORDER BY `range_type` ASC, `range_id` ASC',
            'on_store' => 'store',
            'on_delete' => 'delete'
        ];
        parent::configure($config);
    }

    public static function isActive($tag_name)
    {
        $tag_name = self::normalizeName($tag_name);
        $tag = static::findOneByName($tag_name);
        return $tag === false || $tag['active'] > 0;
    }

    public static function getByRange($range_id, $range_type)
    {
        return Tag::findBySQL('INNER JOIN `tags_relations` ON (`tags_relations`.`tag_id` = `tags`.`id`)
            WHERE `tags_relations`.`range_id` = :range_id
                AND `tags_relations`.`range_type` = :range_type AND `tags`.`active` = 1 ORDER BY `tags`.`name` ASC', [
                    'range_id' => $range_id,
                    'range_type' => $range_type
        ]);
    }

    public static function normalizeName($name)
    {
        $name = mb_strtolower($name);
        $name = str_replace(
            [' ', "\n", '|', '#'],
            ['-', '-',  '-', ''],
            $name
        );
        return $name;
    }
}