2014-12-24 6 views
0

cakephp-file-storage-plugin에서 제공하는 동작에 설정을 전달하려고합니다. 그러나 설정이 인식되지 않습니다. 예를 들어 GIF 파일을 배열 밖으로 나갈 때 제외하려고해도 오류없이 업로드 할 수 있습니다. 로깅을 사용하면 동작이 모델에 연결되어 있음을 확인할 수 있지만 설정을 로그하면 비어 있습니다. 나는 플러그인/비헤이비어가 작동한다는 것을 안다.하지만 불행히도 플러그인/비헤이비어에 대한 문서는 거의 없다. 그래서 누군가 내가 잘못하고있는 것을 알아낼 수 있기를 바란다.CakePHP : 플러그인에서 동작 설정을로드 할 수 없습니다.

다음은 내 모델 코드입니다. 여기서 $actsAs과 설정이 작동하지 않는 이유를 파악하기 위해 로깅을 추가 한 전체 동작 파일을 전달합니다. 해당 로깅의 출력은 다음과 같습니다. ListingPhoto은 다른 클래스의 hasMany 연관으로 Photo이라는 별칭이 지정되어 있습니다. 따라서이 이름이 디버그 출력에 나타납니다. 하지만 왜 하나의 요청에 대해 행동 코드가 여러 번 실행되는 것일 지 완전히 설명 할 수는 없습니다.

내 모델 :

<?php 

App::uses('ImageStorage', 'FileStorage.Model'); 
class ListingPhoto extends ImageStorage { 

    public $name = 'ListingPhoto'; 

    public $actsAs = array(
     'Imagine.Imagine', 
     'FileStorage.UploadValidator' => array(
      'localFile' => true, 
      'validate' => false, 
      'allowedExtensions' => array('jpg', 'jpeg', 'png') 
     ), 
    ); 

    public function upload($listing_id, $data) { 
     $data[$this->alias]['adapter'] = 'Local'; 
     $data[$this->alias]['model'] = 'ListingPhoto'; 
     $data[$this->alias]['foreign_key'] = $listing_id; 
     $this->create(); 
     return $this->save($data); 

    } 

    public function afterDelete() { 
     parent::afterDelete(); 
     $this->log($this->record); 
     StorageManager::adapter($this->record['Photo']['adapter'])->delete($this->record['Photo']['path']); 

    } 

} 

전체 행동 파일, 내 로깅이 추가로 :

<?php 
App::uses('File', 'Utility'); 
App::uses('CakeNumber', 'Utility'); 

/** 
* Upload Validation Behavior 
* 
* This behavior will validate uploaded files, nothing more, it won't take care of storage. 
* 
* @author Florian Krämer 
* @copyright 2012 Florian Krämer 
* @license MIT 
*/ 
class UploadValidatorBehavior extends ModelBehavior { 

/** 
* Settings array 
* 
* @var array 
*/ 
    public $settings = array(); 

/** 
* Default settings array 
* 
* @var array 
*/ 
    protected $_defaults = array(
     'fileField' => 'file', 
     'validate' => true, 
     'allowNoFileError' => true, 
     'allowedMime' => null, 
     'allowedExtensions' => null, 
     'localFile' => false 
    ); 

/** 
* Error message 
* 
* If something fails this is populated with an error message that can be passed to the view 
* 
* @var string 
*/ 
    public $uploadError = null; 

/** 
* Behavior setup 
* 
* Merge settings with default config, then it is checking if the target directory 
* exists and if it is writeable. It will throw an error if one of both fails. 
* 
* @param \AppModel|\Model $Model 
* @param array $settings 
* @throws InvalidArgumentException 
* @return void 
*/ 
    public function setup(Model $Model, $settings = array()) { 
     if (!is_array($settings)) { 
      throw new InvalidArgumentException(__d('file_storage', 'Settings must be passed as array!')); 
     } 
     $this->log("SETTINGS for {$Model->alias}:"); 
     $this->log($settings); 
     // $this->settings[$Model->alias] = array_merge($this->_defaults, $settings); 
    } 

/** 
* Before validation callback 
* 
* Check if the file is really an uploaded file and run custom checks for file 
* extensions and/or mime type if configured to do so. 
* 
* @param Model $Model 
* @param array $options 
* @return boolean True on success 
*/ 
    public function beforeValidate(Model $Model, $options = array()) { 

     $this->log('beforeValidate...'); 

     $this->log('options'); 
     $this->log($options); 

     $this->log('$this->settings[$Model->alias]'); 
     $this->log($this->settings[$Model->alias]); 

     $this->log('$this->settings'); 
     $this->log($this->settings); 

     extract($this->settings[$Model->alias]); 

     $this->log('$validate'); 
     $this->log($validate); 

     if ($validate === true && isset($Model->data[$Model->alias][$fileField]) && is_array($Model->data[$Model->alias][$fileField])) { 

      if ($Model->validateUploadError($Model->data[$Model->alias][$fileField]['error']) === false) { 
       $Model->validationErrors[$fileField] = array($this->uploadError); 
       return false; 
      } 

      if (!empty($Model->data[$Model->alias][$fileField])) { 
       if (empty($localFile) && !is_uploaded_file($Model->data[$Model->alias][$fileField]['tmp_name'])) { 
        $this->uploadError = __d('file_storage', 'The uploaded file is no valid upload.'); 
        $Model->invalidate($fileField, $this->uploadError); 
        return false; 
       } 
      } 

      if (is_array($allowedMime)) { 
       if (!$this->validateAllowedMimeTypes($Model, $allowedMime)) { 
        return false; 
       } 
      } 
      $this->log('allowedExtensions'); 
      $this->log($allowedExtensions); 
      if (is_array($allowedExtensions)) { 
       if (!$this->validateUploadExtension($Model, $allowedExtensions)) { 
        return false; 
       } 
      } 
     } 
     return true; 
    } 

/** 
* Validates the extension 
* 
* @param Model $Model 
* @param $validExtensions 
* @return boolean True if the extension is allowed 
*/ 
    public function validateUploadExtension(Model $Model, $validExtensions) { 
     $this->log('validateUploadExtension'); 
     extract($this->settings[$Model->alias]); 
     $extension = $this->fileExtension($Model, $Model->data[$Model->alias][$fileField]['name'], false); 

     if (!in_array(strtolower($extension), $validExtensions)) { 
      $this->uploadError = __d('file_storage', 'You are not allowed to upload files of this type.'); 
      $Model->invalidate($fileField, $this->uploadError); 
      return false; 
     } 
     return true; 
    } 

/** 
* Validates if the mime type of an uploaded file is allowed 
* 
* @param Model $Model 
* @param array Array of allowed mime types 
* @return boolean 
*/ 
    public function validateAllowedMimeTypes(Model $Model, $mimeTypes = array()) { 
     extract($this->settings[$Model->alias]); 
     if (!empty($mimeTypes)) { 
      $allowedMime = $mimeTypes; 
     } 

     $File = new File($Model->data[$Model->alias][$fileField]['tmp_name']); 
     $mimeType = $File->mime(); 

     if (!in_array($mimeType, $allowedMime)) { 
      $this->uploadError = __d('file_storage', 'You are not allowed to upload files of this type.'); 
      $Model->invalidate($fileField, $this->uploadError); 
      return false; 
     } 
     return true; 
    } 

/** 
* Valdates the error value that comes with the file input file 
* 
* @param Model $Model 
* @param integer Error value from the form input [file_field][error] 
* @return boolean True on success, if false the error message is set to the models field and also set in $this->uploadError 
*/ 
    public function validateUploadError(Model $Model, $error = null) { 
     if (!is_null($error)) { 
      switch ($error) { 
       case UPLOAD_ERR_OK: 
        return true; 
       break; 
       case UPLOAD_ERR_INI_SIZE: 
        $this->uploadError = __d('file_storage', 'The uploaded file exceeds limit of %s.', CakeNumber::toReadableSize(ini_get('upload_max_filesize'))); 
       break; 
       case UPLOAD_ERR_FORM_SIZE: 
        $this->uploadError = __d('file_storage', 'The uploaded file is to big, please choose a smaller file or try to compress it.'); 
       break; 
       case UPLOAD_ERR_PARTIAL: 
        $this->uploadError = __d('file_storage', 'The uploaded file was only partially uploaded.'); 
       break; 
       case UPLOAD_ERR_NO_FILE: 
        if ($this->settings[$Model->alias]['allowNoFileError'] === false) { 
         $this->uploadError = __d('file_storage', 'No file was uploaded.'); 
         return false; 
        } 
        return true; 
       break; 
       case UPLOAD_ERR_NO_TMP_DIR: 
        $this->uploadError = __d('file_storage', 'The remote server has no temporary folder for file uploads. Please contact the site admin.'); 
       break; 
       case UPLOAD_ERR_CANT_WRITE: 
        $this->uploadError = __d('file_storage', 'Failed to write file to disk. Please contact the site admin.'); 
       break; 
       case UPLOAD_ERR_EXTENSION: 
        $this->uploadError = __d('file_storage', 'File upload stopped by extension. Please contact the site admin.'); 
       break; 
       default: 
        $this->uploadError = __d('file_storage', 'Unknown File Error. Please contact the site admin.'); 
       break; 
      } 
      return false; 
     } 
     return true; 
    } 

/** 
* Returns the latest error message 
* 
* @param \AppModel|\Model $Model 
* @return string 
* @access public 
*/ 
    public function uploadError(Model $Model) { 
     return $this->uploadError; 
    } 

/** 
* Returns an array that matches the structure of a regular upload for a local file 
* 
* @param Model $Model 
* @param $file 
* @param string File with path 
* @return array Array that matches the structure of a regular upload 
*/ 
    public function uploadArray(Model $Model, $file, $filename = null) { 
     $File = new File($file); 

     if (empty($fileName)) { 
      $filename = basename($file); 
     } 

     return array(
      'name' => $filename, 
      'tmp_name' => $file, 
      'error' => 0, 
      'type' => $File->mime(), 
      'size' => $File->size()); 
    } 

/** 
* Return file extension from a given filename 
* 
* @param Model $Model 
* @param $name 
* @param bool $realFile 
* @internal param $string 
* @return boolean string or false 
*/ 
    public function fileExtension(Model $Model, $name, $realFile = true) { 
     if ($realFile) { 
      return pathinfo($name, PATHINFO_EXTENSION); 
     } 
     return substr(strrchr($name,'.'), 1); 
    } 

} 

내 로깅 출력 :

2014-12-23 20:04:32 Error: SETTINGS for ImageStorage: 
2014-12-23 20:04:32 Error: Array 
(
    [localFile] => 1 
    [validate] => 
    [allowedExtensions] => Array 
     (
      [0] => jpg 
      [1] => jpeg 
      [2] => png 
      [3] => gif 
     ) 

) 

2014-12-23 20:04:33 Error: SETTINGS for Photo: 
2014-12-23 20:04:33 Error: Array 
(
    [localFile] => 1 
    [validate] => 
    [allowedExtensions] => Array 
     (
      [0] => jpg 
      [1] => jpeg 
      [2] => png 
      [3] => gif 
      [4] => jpg 
      [5] => png 
      [6] => xxx 
     ) 

) 

2014-12-23 20:04:33 Error: beforeValidate... 
2014-12-23 20:04:33 Error: options 
2014-12-23 20:04:33 Error: Array 
(
    [validate] => 1 
    [fieldList] => Array 
     (
     ) 

    [callbacks] => 1 
    [counterCache] => 1 
) 

2014-12-23 20:04:33 Error: $this->settings[$Model->alias] 
2014-12-23 20:04:33 Error: 
2014-12-23 20:04:33 Error: $this->settings 
2014-12-23 20:04:33 Error: Array 
(
    [priority] => 10 
) 

2014-12-23 20:04:33 Error: $validate 
2014-12-23 20:04:33 Error: 
2014-12-23 20:04:38 Error: SETTINGS for ImageStorage: 
2014-12-23 20:04:38 Error: Array 
(
    [localFile] => 1 
    [validate] => 
    [allowedExtensions] => Array 
     (
      [0] => jpg 
      [1] => jpeg 
      [2] => png 
      [3] => gif 
     ) 

) 

2014-12-23 20:04:39 Error: SETTINGS for Photo: 
2014-12-23 20:04:39 Error: Array 
(
    [localFile] => 1 
    [validate] => 
    [allowedExtensions] => Array 
     (
      [0] => jpg 
      [1] => jpeg 
      [2] => png 
      [3] => gif 
      [4] => jpg 
      [5] => png 
      [6] => xxx 
     ) 

) 

갱신 1

내가 대신이를 대체하는, 내 설정이 기본값으로 추가하기 것 같다 로그 출력에 발견 : 내 플러그인의 경우 문제가 아니다

2014-12-23 21:55:07 Error: SETTINGS for Photo: 
2014-12-23 21:55:07 Error: Array 
(
    [localFile] => 1 
    [validate] => 
    [allowedExtensions] => Array 
     (
      [0] => jpg 
      [1] => jpeg 
      [2] => png 
      [3] => gif 
      [4] => jpg <--my addition 
      [5] => png <--my addition 
      [6] => xxx <--my addition 
     ) 

) 
+0

어떤 플러그인을 사용하고 있습니까? 또한 파일 업로드가 확인되지 않았습니까? – burzum

+0

README.md의 설치 지침을 따른 후 master 브랜치에 있습니다. 문제는 기본 설정 만 작동하도록 할 수 있다는 것입니다. 내 고유 한 확장자 나 파일 크기를 선택할 수 없습니다. 내가 무엇을 설정했는지 상관없이 defaultss가 적용됩니다. – emersonthis

+1

PHP에서'extends '할 때. 속성을 대체하고 병합하지 않습니다. 이 작업을 수행하려면'ImageStorage. $ actsAs '의 설정 중 일부가 필요할 수 있습니다. 나는 플러그인을 사용한 적이 없다. 그래서 모르겠지만 기본 모델에서 'Imagine.Imagine' 동작을 제거했습니다. – cgTag

답변

0

합니다. 그러나 핵심 클래스 Object::_mergeVars(), 모델 클래스를 상속합니다. 그것은 당신이 그것을 얻는 방법 $actsAs property을 병합합니다.

내 플러그인에서 이미 기존 configureUploadValidation() 메서드를 사용하는 것 외에는이 문제를 해결할 수있는 방법이 없습니다. 나는 이것을 플러그인의 문서에 메모로 내일 추가 할 것이다.

+0

감사! 하지만 불행히도 실제로'name' 속성 집합을 사용하여 실제로 시도했지만 여전히 작동하지 않았습니다.(나는 완성 된 * 모델 파일로 질문을 갱신했다.) – emersonthis

+0

BTW, 나는'$ actsAs'를 완전히 제거하고 (단위 테스트에서와 같이) 동작을 즉시로드 (load)했다. 결과. 내 다음 이론은 내 모델이 ImageStorage를 확장하기 때문에 동작이 다르게 작동하는 것일 수 있습니다. 저는 다른 조상과 함께 시도하고 다시보고 할 것입니다. – emersonthis

+0

저장 전화를하기 전에 문제를 다시로드하십시오. $ this-> Behaviors-> load (...); 구성을 다시해야합니다. 확장 모델에서 configureUploadValidation ($ options)을 호출 할 수도 있습니다 (FileStorage 모델 참조).이 메소드는이 메소드를 구현합니다. – burzum

관련 문제