当前位置:网站首页>Validation of TTF font by validator of laravel
Validation of TTF font by validator of laravel
2022-06-25 19:12:00 【Mar, LiuNian】
Problem description
Upload ttf after . file mimes The verification failed
namespace App\Http\Controllers\Test;
use Illuminate\Http\Request;
class IndexController
{
public function index(Request $request){
return view('test.index');
}
public function store(Request $request){
$validator = \validator($request->all(),['file'=>['required','mimes:ttf']],['file.mimes'=>' The document type is not ttf']);
if($validator->fails()){
dd($validator->errors());
}
}
}
Look at the source code
vendor/laravel/framework/src/Illuminate/Foundation/helpers.php
Created a validator factory , Create... Through the factory validator
Factory mode
if (! function_exists('validator')) {
/** * Create a new Validator instance. * * @param array $data * @param array $rules * @param array $messages * @param array $customAttributes * @return \Illuminate\Contracts\Validation\Validator|\Illuminate\Contracts\Validation\Factory */
function validator(array $data = [], array $rules = [], array $messages = [], array $customAttributes = [])
{
// Through the example of the container, the chemical plant
$factory = app(ValidationFactory::class);
if (func_num_args() === 0) {
return $factory;
}
// Create validators through the factory
return $factory->make($data, $rules, $messages, $customAttributes);
}
}
vendor/composer/autoload_classmap.php
This file stores most of the container mapping relationships
Through this file we know
validator Factory vendor/laravel/framework/src/Illuminate/Validation/Factory.php
validator class vendor/laravel/framework/src/Illuminate/Validation/Validator.php
Let's go straight to validator class
namespace Illuminate\Validation;
use BadMethodCallException;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Translation\Translator;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ImplicitRule;
use Illuminate\Contracts\Validation\Rule as RuleContract;
use Illuminate\Contracts\Validation\Validator as ValidatorContract;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Support\Arr;
use Illuminate\Support\Fluent;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;
use Illuminate\Support\ValidatedInput;
use InvalidArgumentException;
use RuntimeException;
use stdClass;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Validator implements ValidatorContract
{
use Concerns\FormatsMessages,
Concerns\ValidatesAttributes;
// Omit ......
/** * Determine if the data passes the validation rules. * * @return bool */
public function passes()
{
$this->messages = new MessageBag;
[$this->distinctValues, $this->failedRules] = [[], []];
// We'll spin through each rule, validating the attributes attached to that
// rule. Any error messages will be added to the containers with each of
// the other error messages, returning true if we don't have messages.
foreach ($this->rules as $attribute => $rules) {
if ($this->shouldBeExcluded($attribute)) {
$this->removeAttribute($attribute);
continue;
}
if ($this->stopOnFirstFailure && $this->messages->isNotEmpty()) {
break;
}
foreach ($rules as $rule) {
// We mainly look at the attribute verification here
$this->validateAttribute($attribute, $rule);
if ($this->shouldBeExcluded($attribute)) {
$this->removeAttribute($attribute);
break;
}
if ($this->shouldStopValidating($attribute)) {
break;
}
}
}
// Here we will spin through all of the "after" hooks on this validator and
// fire them off. This gives the callbacks a chance to perform all kinds
// of other validation that needs to get wrapped up in this operation.
foreach ($this->after as $after) {
$after();
}
return $this->messages->isEmpty();
}
/** * Determine if the data fails the validation rules. * * @return bool */
public function fails()
{
return ! $this->passes();
}
/** * Validate a given attribute against a rule. * * @param string $attribute * @param string $rule * @return void */
protected function validateAttribute($attribute, $rule)
{
$this->currentRule = $rule;
[$rule, $parameters] = ValidationRuleParser::parse($rule);
if ($rule === '') {
return;
}
// First we will get the correct keys for the given attribute in case the field is nested in
// an array. Then we determine if the given rule accepts other field names as parameters.
// If so, we will replace any asterisks found in the parameters with the correct keys.
if ($this->dependsOnOtherFields($rule)) {
$parameters = $this->replaceDotInParameters($parameters);
if ($keys = $this->getExplicitKeys($attribute)) {
$parameters = $this->replaceAsterisksInParameters($parameters, $keys);
}
}
$value = $this->getValue($attribute);
// If the attribute is a file, we will verify that the file upload was actually successful
// and if it wasn't we will add a failure for the attribute. Files may not successfully
// upload if they are too large based on PHP's settings so we will bail in this case.
if ($value instanceof UploadedFile && ! $value->isValid() &&
$this->hasRule($attribute, array_merge($this->fileRules, $this->implicitRules))
) {
return $this->addFailure($attribute, 'uploaded', []);
}
// If we have made it this far we will make sure the attribute is validatable and if it is
// we will call the validation method with the attribute. If a method returns false the
// attribute is invalid and we will add a failure message for this failing attribute.
$validatable = $this->isValidatable($rule, $attribute, $value);
if ($rule instanceof RuleContract) {
return $validatable
? $this->validateUsingCustomRule($attribute, $value, $rule)
: null;
}
// If you verify mimes, call validateMimes Method , The method in vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php In file , yes trait
$method = "validate{
$rule}";
if ($validatable && ! $this->$method($attribute, $value, $parameters, $this)) {
$this->addFailure($attribute, $rule, $parameters);
}
}
// Omit ......
}
vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php
namespace Illuminate\Validation\Concerns;
use Countable;
use DateTime;
use DateTimeInterface;
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\DNSCheckValidation;
use Egulias\EmailValidator\Validation\MultipleValidationWithAnd;
use Egulias\EmailValidator\Validation\NoRFCWarningsValidation;
use Egulias\EmailValidator\Validation\RFCValidation;
use Egulias\EmailValidator\Validation\SpoofCheckValidation;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Exists;
use Illuminate\Validation\Rules\Unique;
use Illuminate\Validation\ValidationData;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
trait ValidatesAttributes
{
/** * Validate the guessed extension of a file upload is in a set of file extensions. * * @param string $attribute * @param mixed $value * @param array $parameters * @return bool */
public function validateMimes($attribute, $value, $parameters)
{
if (! $this->isValidFileInstance($value)) {
return false;
}
if ($this->shouldBlockPhpUpload($value, $parameters)) {
return false;
}
if (in_array('jpg', $parameters) || in_array('jpeg', $parameters)) {
$parameters = array_unique(array_merge($parameters, ['jpg', 'jpeg']));
}
// File selected , And mimes In the specified mimes in
//$value yes vendor/laravel/framework/src/Illuminate/Http/UploadedFile.php
return $value->getPath() !== '' && in_array($value->guessExtension(), $parameters);
}
}
vendor/laravel/framework/src/Illuminate/Http/UploadedFile.php
extend
Symfony\Component\HttpFoundation\File\UploadedFile
Symfony\Component\HttpFoundation\File\UploadedFile
extend
mponent\HttpFoundation\File
see Symfony\Component\HttpFoundation\File
public function guessExtension()
{
if (!class_exists(MimeTypes::class)) {
throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
}
//vendor/symfony/mime/MimeTypes.php
return MimeTypes::getDefault()->getExtensions($this->getMimeType())[0] ?? null;
}
see vendor/symfony/mime/MimeTypes.php
public function getExtensions(string $mimeType): array
{
if ($this->extensions) {
$extensions = $this->extensions[$mimeType] ?? $this->extensions[$lcMimeType = strtolower($mimeType)] ?? null;
}
// adopt mimetype To judge mime type
//self::MAP Maintained mime And mimetype The mapping relation of
// Among them, the maintenance class has three corresponding relationships , Think it's ttf
//'font/ttf' => ['ttf'],'pplication/x-font-ttf'>['ttf'],'application/x-font-truetype' => ['ttf']
// Because there is no maintenance application/font-sfnt, Cause to think mime yes null, therefore mime Verification failed
return $extensions ?? self::MAP[$mimeType] ?? self::MAP[$lcMimeType ?? strtolower($mimeType)] ?? [];
}
solve
namespace App\Http\Controllers\Test;
use Illuminate\Http\Request;
class IndexController
{
public function index(Request $request){
return view('test.index');
}
public function store(Request $request){
// Don't verify mimes, verification mimetypes
$validator = \validator($request->all(),['file'=>['required','mimetypes:application/font-sfnt,application/x-font-truetype,application/x-font-ttf,font/ttf']],['file.mimetypes'=>' The document type is not ttf']);
if($validator->fails()){
dd($validator->errors());
}
dd('ok');
}
}
边栏推荐
- Analysis of China's road freight volume, market scale and competition pattern in 2020 [figure]
- LeetCode-101-对称二叉树
- PHP database connection version1.1
- Tcp/ip test questions (4)
- Network security detection and prevention test questions (II)
- 削足适履 - 谈谈赛道上的坡道改造
- Tcp/ip test questions (III)
- 揭秘GES超大规模图计算引擎HyG:图切分
- 最新数据挖掘赛事方案梳理!
- 网络安全检测与防范 测试题(一)
猜你喜欢

Analysis on employment compensation of 2021 college graduates: the average monthly starting salary of doctors, masters, undergraduates and junior colleges is 14823 yuan, 10113 yuan, 5825 yuan and 3910

What are Baidu collection skills? 2022 Baidu article collection skills

Divine reversion EA
![Analysis on market scale and supply of China's needle coke industry in 2020 [figure]](/img/79/6b08b62be8768484f548b6e18bd810.jpg)
Analysis on market scale and supply of China's needle coke industry in 2020 [figure]

One night I worked as an XPath Terminator: XPath Helper Plus
![Analysis on China's aluminum foil output, trade and enterprise leading operation in 2021: dongyangguang aluminum foil output is stable [figure]](/img/e8/027e8a6cbdc4454e7a18ed7aa2122a.jpg)
Analysis on China's aluminum foil output, trade and enterprise leading operation in 2021: dongyangguang aluminum foil output is stable [figure]

Server journey from scratch - Yu Zhongxian integrated version (IP access server, LNMP compilation and installation, Lua environment and socket expansion)
![Current situation of China's hydraulic cylinder industry in 2020 (with application fields, policies and regulations, supply and demand status and enterprise pattern) [figure]](/img/2e/439b5dce9634d4015430c9cf06c5de.jpg)
Current situation of China's hydraulic cylinder industry in 2020 (with application fields, policies and regulations, supply and demand status and enterprise pattern) [figure]
![In 2021, China's private equity market is growing, and the scale of private equity fund management reaches 19.78 trillion yuan [figure]](/img/e9/ffc5303cb6f0f8e05e93b3342a49b2.jpg)
In 2021, China's private equity market is growing, and the scale of private equity fund management reaches 19.78 trillion yuan [figure]

最新數據挖掘賽事方案梳理!
随机推荐
Miner's Diary: why should I go mining on April 5, 2021
Comparison rules of strings in JS
网络安全检测与防范 测试题(五)
SEO outsourcing reliable company, enterprise SEO outsourcing company which reliable?
网络安全检测与防范 测试题(二)
GenICam GenTL 标准 ver1.5(1)
ECS 7-day practical training camp (Advanced route) -- day03 -- ecs+slb load balancing practice
Embark on a new journey and reach the world with wisdom
Solidity get quarterly time
Does GoogleSEO need to change the friend chain? (e6zzseo)
Kotlin compose terminate todo project Click to edit and modify todo
Tiger DAO VC产品正式上线,Seektiger生态的有力补充
Leetcode-78-subset
On Oracle full stack virtual machine -- graalvm
Tcp/ip test questions (4)
Solve the problem that sublime Text3 package control cannot install plug-ins
Current situation of China's hydraulic cylinder industry in 2020 (with application fields, policies and regulations, supply and demand status and enterprise pattern) [figure]
Svn introduction and Usage Summary
Do you want to know how new investors open accounts? Is online account opening safe?
How to quickly close port 8080