Ошибка преобразования массива в строку -Slim Twig- - PullRequest
0 голосов
/ 18 мая 2018

Настройка: у меня тонкое приложение, и я вытащил в режиме просмотра Illuminate DB и Twig.

if (!$validator->passed()) {
        $errors = $validator->errors();
        $users = User::all();
        return $this->view($response, 'auth.login', compact('errors','users'));
    }

Проблема: Когда я запускаю приведенный выше код, я могу получить переменную users в моем представлении, но переменная errors выдает следующую ошибку.

Примечание: преобразование массива в строку в /Users/davidchen/Documents/sites/slim.com/vendor/twig/twig/lib/Twig/Environment.php(378): eval () 'd код в строке 70 Array

Переменная errors возвращает многомерный массив, ниже вы найдете результат, полученный от print_r ($ errors).

Array ( 
    [username] => Array ( 
        [0] => username already exists 
    ) 
    [password] => Array ( 
        [0] => password must consist of at least 6 characters 
    ) 
)

Вот мои связанные файлы проекта:

  1. Файл установки Twig (app.php)

$c = $app->getContainer();

$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($config['config']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();

$c['db'] = function($c) use ($capsule){
    return $capsule;
};

$c['view'] = function($c){
    $options['cache']=false;
    $view = new \Slim\Views\Twig(__DIR__."/../views", $options);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $c->router,
        $c->request->getUri()
    ));
    $view->getEnvironment()->addGlobal('flash', $c->flash);
    return $view;
};

$c['flash'] = function($c){
    return new Slim\Flash\Messages();
};
Класс валидатора

namespace App\Models\Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;
use Carbon\Carbon;
use DateTime;


class Validator extends Model
{
    protected   $field_name,
                $data,
                $errors = [];

/*
* Main validator
*/

    public function __construct($request, $fields = []){
        $data = $request->getParams();
        $this->data = $data;
        foreach ($fields as $field => $constraints) {
            $this->field_name = $field;
            if (isset($data[$field])) {
                $field_value = $data[$field];
                foreach (explode("|", $constraints) as  $constraint) {
                    $obj = explode(":", $constraint);
                    $function_name = $obj[0];
                    if (isset($obj[1])) {
                        if(method_exists($this, $function_name))
                        {
                            $this->$function_name($obj[1],$field_value);
                        }
                    }
                }
            }else{
                if (strpos($constraints, 'required') !== false) {
                    $validator->report($validator->field_name.' field is requried');
                }   
            }
        }
        return $this;
    }
/*
* Object Interface Methods
*/
    private function report($message){
        $this->errors[$this->field_name][]= $message;
    }

    public function errors(){

        return $this->errors;
    }

    public function passed(){
        if (!count($this->errors)) {
            return true;
        }
    }

/*
* Validation Rules
*/

    public function max($length,$value){
        if (strlen($value)>$length) {
            $this->report("{$this->field_name} must consist of less than {$length} characters");
        }
    }

    public function min($length,$value){
        if (strlen($value)<$length) {
            $this->report("{$this->field_name} must consist of atleast {$length} characters");
        }
    }

    public function distinct($tableName,$value){
        if (DB::table($tableName)->where($this->field_name, $value)->exists()) {
            $this->report("{$this->field_name} already exists");
        }
    }

    public function date($format,$date){     

        if (!preg_match("/\d{4}-\d{2}-\d{2}\b/",$date)) {
            $this->report("incorrect {$this->field_name} values");
        }else{
            $d = DateTime::createFromFormat($format, $date); 
            if ($d && $d->format($format) !== $date) {
                $this->report("{$this->field_name} format should be {$format}");
            }
        }        
    }

    public function match($matchField,$value){
        if (isset($this->data[$matchField])) {
            $valueTwo = $this->data[$matchField];
            if ($value !== $valueTwo) {
                $this->report("{$this->field_name} does not match {$matchField}");
            }
        }else{
            $this->report("{$matchField} is required");
        }


    }

    public function format($type,$value){
        switch ($type) {
            case 'noWhiteSpace':
                if (preg_match("/\s/",$value)) {
                    $this->report("{$this->field_name} may not contain any spaces");
            }break;

            case 'alpha':
                if (preg_match("/[^a-zA-Z]/",$value)) {
                    $this->report("{$this->field_name} may only contain letters");
            }break;

            case 'alphaNum':
                if (preg_match("/[^a-zA-Z0-9]/",$value)) {
                    $this->report("{$this->field_name} may only contain letters");
            }break;

            case 'email':
                if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                    $this->report("in correct {$this->field_name} format");
            }break;

            default:
                # code...
                break;
        }
    }

}
Базовый контроллер

namespace App\Controllers;
/**
* 
*/
class Controller 
{
    protected $c;
    function __construct($container)
    {
        $this->c = $container;
    }

    public function view($response, $path,$variables = []){
        $this->c->view->render($response, str_replace(".","/",$path).".twig", $variables);
    }

    public function pathFor($routeName,$data = []){
        return $this->c->router->pathFor($routeName,$data);
    }
}
Auth Controller

namespace App\Controllers\Auth;
use App\Models\User\User;
use App\Controllers\Controller;
use App\Models\Auth\Validator;
/**
* 
*/
class AuthController extends Controller
{
    public function getLogin($request, $response){
        return $this->view($response, 'auth.login');
    }

    public function postLogin($request, $response){
        $validator =  new Validator($request,[
            'username'=>'required|min:3|max:64|format:alphaNum|distinct:users',
            'password'=>'required|min:6|max:64|',
        ]);

        if (!$validator->passed()) {
            $errors = $validator->errors();
            $users = User::all();
            return $this->view($response, 'auth.login', compact('errors','users'));
        }
        return $this->view($response, 'home.login');
    }
}
файл login.twig

файл login.twig

enter image description here

Надеюсь, один из вас сможет пролить свет наЭта проблема.Я боролся с этим все утро.

1 Ответ

0 голосов
/ 18 мая 2018

Вы можете попытаться перебрать каждый элемент в последовательности.Например, для отображения списка пользователей, представленных в переменной с именем users:

<h1>Members</h1>
<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>

Подробнее

...