Avail feature updated
[ninja.git] / system / libraries / ORM_Versioned.php
blob88e3f3642e9d643c3d9138efd7c6df1b08a587fe
1 <?php
2 /**
3 * Object Relational Mapping (ORM) "versioned" extension. Allows ORM objects to
4 * be revisioned instead of updated.
6 * $Id$
8 * @package ORM
9 * @author Kohana Team
10 * @copyright (c) 2007-2008 Kohana Team
11 * @license http://kohanaphp.com/license.html
13 class ORM_Versioned extends ORM {
15 protected $last_version = NULL;
17 /**
18 * Overload ORM::save() to support versioned data
20 * @chainable
21 * @return ORM
23 public function save()
25 $this->last_version = 1 + ($this->last_version === NULL ? $this->object['version'] : $this->last_version);
26 $this->__set('version', $this->last_version);
28 parent::save();
30 if ($this->saved)
32 $data = array();
33 foreach ($this->object as $key => $value)
35 if ($key === 'id')
36 continue;
38 $data[$key] = $value;
40 $data[$this->foreign_key()] = $this->id;
42 $this->db->insert($this->table_name.'_versions', $data);
45 return $this;
48 /**
49 * Loads previous version from current object
51 * @chainable
52 * @return ORM
54 public function previous()
56 if ( ! $this->loaded)
57 return $this;
59 $this->last_version = ($this->last_version === NULL) ? $this->object['version'] : $this->last_version;
60 $version = $this->last_version - 1;
62 $query = $this->db
63 ->where($this->foreign_key(), $this->object[$this->primary_key])
64 ->where('version', $version)
65 ->limit(1)
66 ->get($this->table_name.'_versions');
68 if ($query->count())
70 $this->load_values($query->result(FALSE)->current());
73 return $this;
76 /**
77 * Restores the object with data from stored version
79 * @param integer version number you want to restore
80 * @return ORM
82 public function restore($version)
84 if ( ! $this->loaded)
85 return $this;
87 $query = $this->db
88 ->where($this->foreign_key(), $this->object[$this->primary_key])
89 ->where('version', $version)
90 ->limit(1)
91 ->get($this->table_name.'_versions');
93 if ($query->count())
95 $row = $query->result(FALSE)->current();
97 foreach ($row as $key => $value)
99 if ($key === $this->primary_key OR $key === $this->foreign_key())
101 // Do not overwrite the primary key
102 continue;
105 if ($key === 'version')
107 // Always use the current version
108 $value = $this->version;
111 $this->__set($key, $value);
114 $this->save();
117 return $this;
121 * Overloads ORM::delete() to delete all versioned entries of current object
122 * and the object itself
124 * @param integer id of the object you want to delete
125 * @return ORM
127 public function delete($id = NULL)
129 if ($id === NULL)
131 // Use the current object id
132 $id = $this->object[$this->primary_key];
135 if ($status = parent::delete($id))
137 $this->db->where($this->foreign_key(), $id)->delete($this->table_name.'_versions');
140 return $status;