Skip to content

Commit 3a83eb8

Browse files
committed
Merge pull request #3 from s3rajkarnikar/master
Adding newInstance and attributesToArray methods
2 parents 01dd31e + 899e4d8 commit 3a83eb8

File tree

1 file changed

+79
-3
lines changed

1 file changed

+79
-3
lines changed

src/Dtisgodsson/Elocrypt/ElocryptTrait.php

+79-3
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,13 @@ public function __get($key)
3939
return $value;
4040
}
4141

42-
public static function create(Array $attributes = [])
42+
/**
43+
* Save a new model and return the instance.
44+
*
45+
* @param array $attributes
46+
* @return static
47+
*/
48+
public static function create(array $attributes)
4349
{
4450
$model = new static;
4551

@@ -66,11 +72,17 @@ public static function create(Array $attributes = [])
6672
return parent::create($attributes);
6773
}
6874

69-
public function update(Array $attributes = [])
75+
/**
76+
* Update the model in the database.
77+
*
78+
* @param array $attributes
79+
* @return bool|int
80+
*/
81+
public function update(array $attributes = array())
7082
{
7183
if(!isset($this->encryptable))
7284
{
73-
return parent::update($id, $attributes);
85+
return parent::update($attributes);
7486
}
7587

7688
foreach ($attributes as $key => $value) {
@@ -91,4 +103,68 @@ public function update(Array $attributes = [])
91103

92104
return parent::update($attributes);
93105
}
106+
107+
/**
108+
* Create a new instance of the given model.
109+
*
110+
* @param array $attributes
111+
* @param bool $exists
112+
* @return static
113+
*/
114+
public function newInstance($attributes = array(), $exists = false)
115+
{
116+
if(!isset($this->encryptable))
117+
{
118+
return parent::newInstance($attributes, $exists);
119+
}
120+
121+
foreach ($attributes as $key => $value) {
122+
123+
if(in_array($key, $this->encryptable))
124+
{
125+
try
126+
{
127+
$decrypted = Crypt::decrypt($value);
128+
$attributes[$key] = $value;
129+
}
130+
catch(DecryptException $exception)
131+
{
132+
$attributes[$key] = Crypt::encrypt($value);
133+
}
134+
}
135+
}
136+
137+
return parent::newInstance($attributes, $exists);
138+
}
139+
140+
/**
141+
* Convert the model's attributes to an array.
142+
*
143+
* @return array
144+
*/
145+
public function attributesToArray()
146+
{
147+
$attributes = parent::attributesToArray();
148+
149+
if(!isset($this->encryptable))
150+
{
151+
return $attributes;
152+
}
153+
154+
foreach ($this->encryptable as $key)
155+
{
156+
if ( ! isset($attributes[$key])) continue;
157+
158+
try
159+
{
160+
$attributes[$key] = Crypt::decrypt($attributes[$key]);
161+
}
162+
catch(DecryptException $exception)
163+
{
164+
//Do nothing, attribute already exists
165+
}
166+
}
167+
168+
return $attributes;
169+
}
94170
}

0 commit comments

Comments
 (0)