Multiple fields on afterFind

37 views Asked by At

I have cakephp app model in which I need to decrypt two fields. For this purpose I'm using the afterFind callback. It works well but when I add a second field to my $encryptedFields decrypt only does one field.

My callback code is as follows:

public $encryptedFields = array('name', 'details');


public function beforeSave($options = array()) {
    foreach($this->encryptedFields as $fieldName){
        if(!empty($this->data[$this->alias][$fieldName])){
            $k = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
            $this->data[$this->alias][$fieldName] = Security::encrypt($this->data[$this->alias][$fieldName], $k);
        }                                           
    }
    return true;
}



public function afterFind($results, $primary = false) {
    foreach($this->encryptedFields as $fieldName){
        foreach ($results as $key => $val) {
            if (isset($val[$this->alias][$fieldName])) {
                $k = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
                $results[$key][$this->alias][$fieldName] = Security::decrypt($val[$this->alias][$fieldName], $k);
            }
        }
        return $results;
       }

}

I have included the encryption functionality in the beforeSave for illustrative purposes but this is working well and encrypting the two fields, as said before my problem seems to be related with the afterFind $results but I'm out of ideas. Can anyone help me?

1

There are 1 answers

1
bill On

The problem is that you return from your foreach loop before you iterate over each item in the $encryptedFields array. Move return $results; out of the foreach loop and you should be able to decrypt both fields.

public function afterFind($results, $primary = false) {
    foreach($this->encryptedFields as $fieldName){
        foreach ($results as $key => $val) {
            if (isset($val[$this->alias][$fieldName])) {
                $k = 'wt1U5MACWJFTXGenFoZoiLwQGrLgdbHA';
                $results[$key][$this->alias][$fieldName] = Security::decrypt($val[$this->alias][$fieldName], $k);
            }
        }
    }
    return $results; // move this here
}