示例#1
0
 /**
  * Format the model to HTML file. Bind it's attributes to view.
  *
  * @method format
  *
  * @param string $field
  * @param string $format
  *
  * @return mixed
  */
 public function format($field = null, $format = null)
 {
     $numArgs = func_num_args();
     if ($numArgs === 0) {
         $formatter = $this->collection->option('format');
         if (is_null($formatter)) {
             $schema = $this->schemaByIndex(0);
             if (!is_null($schema)) {
                 return isset($this[$schema['name']]) ? val($this[$schema['name']]) : null;
             } else {
                 return '-- no formatter and schema --';
             }
         } else {
             if ($formatter instanceof Closure) {
                 return $formatter($this);
             } elseif (is_string($formatter)) {
                 $result = preg_replace_callback('/{(\\w+)}/', function ($matches) {
                     return $this->format($matches[1]);
                 }, $formatter);
                 return $result;
             } else {
                 throw new Exception('Unknown format for Model formatter.');
             }
         }
     } else {
         $format = $format ?: 'plain';
         $schema = $this->schema($field);
         // TODO return value if no formatter or just throw exception?
         if (is_null($schema)) {
             throw new Exception("[Norm/Model] No formatter [{$format}] for field [{$field}].");
         } else {
             $value = isset($this[$field]) ? val($this[$field]) : null;
             return $schema->format($format, $value, $this);
         }
     }
 }