the browser-facing portion of osu!
at master 2.1 kB view raw
1<?php 2 3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. 4// See the LICENCE file in the repository root for full licence text. 5 6namespace App\Libraries; 7 8use Lang; 9 10class ValidationErrors 11{ 12 private $errors = []; 13 14 public function __construct(private string $prefix, private string $keyBase = 'model_validation.') 15 { 16 } 17 18 public function add($column, $rawMessage, $params = null): self 19 { 20 $this->errors[$column] ?? ($this->errors[$column] = []); 21 22 $params ?? ($params = []); 23 24 if ($rawMessage[0] === '.') { 25 $rawMessage = $this->prefix.$rawMessage; 26 } 27 $rawMessage = $this->keyBase.$rawMessage; 28 29 $attributeKey = $this->keyBase.$this->prefix.'.attributes.'.$column; 30 $params['attribute'] = Lang::has($attributeKey) ? osu_trans($attributeKey) : $column; 31 32 $this->errors[$column][] = osu_trans($rawMessage, $params); 33 34 return $this; 35 } 36 37 public function addTranslated($column, $message): self 38 { 39 $this->errors[$column][] = $message; 40 41 return $this; 42 } 43 44 public function merge(self $validationErrors): self 45 { 46 $errors = $validationErrors->all(); 47 foreach ($errors as $key => $value) { 48 // merge with existing key if any. 49 $this->errors[$key] = array_merge($this->errors[$key] ?? [], $value); 50 } 51 52 return $this; 53 } 54 55 public function reset() 56 { 57 $this->errors = []; 58 } 59 60 public function isEmpty() 61 { 62 return count($this->errors) === 0; 63 } 64 65 public function isAny() 66 { 67 return !$this->isEmpty(); 68 } 69 70 public function all() 71 { 72 return $this->errors; 73 } 74 75 public function allMessages() 76 { 77 $result = []; 78 79 foreach ($this->errors as $_column => $messages) { 80 $result = array_merge($result, $messages); 81 } 82 83 return $result; 84 } 85 86 public function toSentence($separator = "\n") 87 { 88 return implode($separator, $this->allMessages()); 89 } 90}