/
Tag.php
120 lines (105 loc) · 3.37 KB
/
Tag.php
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
/**
* Omeka
*
* @copyright Copyright 2007-2012 Roy Rosenzweig Center for History and New Media
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU GPLv3
*/
/**
* A tag and its metadata.
*
* @package Omeka\Record
*/
class Tag extends Omeka_Record_AbstractRecord {
/**
* The tag text.
*
* @var string
*/
public $name;
/**
* Use the tag text when using this record as a string.
*
* @return string
*/
public function __toString() {
return $this->name;
}
/**
* Delete handling for a tag.
*
* Delete the taggings associated with this tag.
*/
protected function _delete()
{
$taggings = $this->getDb()
->getTable('RecordsTags')
->findBySql('tag_id = ?', array((int) $this->id));
foreach ($taggings as $tagging) {
$tagging->delete();
}
}
/**
* Validate this tag.
*
* The tag "name" must be non-empty and unique.
*/
protected function _validate()
{
if (trim($this->name) == '') {
$this->addError('name', __('Tags must be given a name.'));
}
if (!$this->fieldIsUnique('name')) {
$this->addError('name', __('That name is already taken for this tag.'));
}
}
/**
* Rename a tag.
*
* Any records tagged with the "old" tag will be tagged with each
* of the tags given in $new_names. The original tag will be
* deleted (unless it is given as one of the $new_names).
*
* @param array $new_names Names of the tags this one should be
* renamed to.
*/
public function rename($new_names)
{
$taggings = $this->getTable('RecordsTags')->findBy(array('tag' => $this->name));
$keepOldTaggings = false;
// If the current tag is in the new tag list, we don't need
// to do anything to it or its taggings.
if (in_array($this->name, $new_names)) {
$new_names = array_diff($new_names, array($this->name));
// If the current name was the only new name, stop.
if (!count($new_names)) {
return true;
}
$keepOldTaggings = true;
// Otherwise, we need to delete the old tag.
} else {
$this->delete();
}
// Switch the existing taggings to the first of the new names,
// and create new taggings for the remainder.
foreach ($new_names as $key => $new_name) {
$new_tag = $this->getTable()->findOrNew($new_name);
$new_tag_id = $new_tag->id;
foreach ($taggings as $tagging) {
// After the first pass, or if we didn't delete the
// original tag, operate on new copies of the taggings
if ($key > 0 || $keepOldTaggings) {
$tagging = clone $tagging;
}
$tagging->tag_id = $new_tag_id;
try {
$tagging->save();
} catch (Zend_Db_Exception $e) {
// If we couldn't save, it's because this tagging
// already exists, so we should delete it.
$tagging->delete();
}
}
}
}
}