brunoconte3 / dev-utils
Dev-utils 是一个完整、验证、格式化、比较数据,并附带实用工具的库
2.6.2
2024-08-08 12:30 UTC
Requires
- php: ^8.1|^8.2|^8.3
Requires (Dev)
- phpstan/phpstan: 1.10.67
- phpunit/phpunit: 10.5.20
Suggests
- ext-gd: to use the GD implementation
- ext-intl: to use Format with Date
- ext-mbstring: to use Format::lower() etc...
- dev-master
- 2.6.2
- 2.6.1
- 2.6.0
- 2.5.6
- 2.5.5
- 2.5.4
- 2.5.3
- 2.5.2
- 2.5.1
- 2.5.0
- 2.4.2
- 2.4.1
- 2.4.0
- 2.3.0
- 2.2.0
- 2.1.0
- 2.0.1
- 2.0.0
- 1.12.1
- 1.12.0
- 1.11.2
- 1.11.1
- 1.11.0
- 1.10.1
- 1.10.0
- 1.9.1
- 1.9.0
- 1.8.0
- 1.7.1
- 1.7.0
- 1.6.4
- 1.6.3
- 1.6.2
- 1.6.1
- 1.6.0
- 1.5.3
- 1.5.2
- 1.5.1
- 1.5.0
- 1.4.0
- 1.3.0
- 1.2.2
- 1.2.1
- 1.2.0
- 1.1.1
- 1.1.0
- 1.0.1
- 1.0.0
This package is auto-updated.
Last update: 2024-08-30 23:04:13 UTC
README
一个完整的库,具有PSR标准,并保证所有方法都通过phpunit单元测试和phpstan通过。
- 数组类
- 比较类
- 格式化类
- 实用类
- 验证一般数据
- 验证上传文件
安装
composer.json
"brunoconte3/dev-utils": "2.6.2"
使用composer,需要
$ composer require brunoconte3/dev-utils
数据验证示例
数据
$data = [ 'name' => 'brunoconte3', 'email' => 'brunoconte3@gmail.com', 'validatePassingJson' => '@&451', 'newPassword' => 'min:5', 'confirmPassword' => 'min:5|equals:newPassword', ];
规则
$rules = [ 'name' => 'required|regex:/^[a-zA-Z\s]+$/', 'email' => 'required|email|max:50', 'validatePassingJson' => '{"required":"true","type":"alpha"}', ];
根据规则验证数据
require 'vendor/autoload.php'; $validator = new DevUtils\Validator(); $validator->set($data, $rules); if(!$validator->getErros()){ echo 'Data successfully validated'; } else { var_dump($validator->getErros()); }
验证文件上传
使用validators fileName, maxFile, maxUploadSize, mimeType, minFile, minUploadSize, minHeight, minWidth, maxHeight, maxWidth 和 requiredFile,您可以设置文件的最小和最大大小(字节);最小和最大文件数量;允许的扩展名;图片的最小和最大高度和长度,验证文件名并定义字段类型为“File”是否为必填项。
示例
<!DOCTYPE html> <html lang="pt-BR"> <head> ... </head> <body> <form method="POST" enctype="multipart/form-data"> <!-- Upload a single file. --> <input type="file" name="fileUploadSingle" /> <!-- Uploading single or multiple files. --> <input type="file" name="fileUploadMultiple[]" multiple="multiple" /> <button type="submit">Upload</button> </form> </body> </html>
<?php /** * Comments * * maxFile, minFile, minHeight, minWidth, maxUploadSize, maxHeight, maxWidth and minUploadSize: They must be of the integer type. * mimeType: To pass an array with the allowed extensions, just use the ';' between values. */ if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { $fileUploadSingle = $_FILES['fileUploadSingle']; $fileUploadMultiple = $_FILES['fileUploadMultiple']; $datas = [ 'fileUploadSingle' => $fileUploadSingle, 'fileUploadMultiple' => $fileUploadMultiple, ]; $rules = [ 'fileUploadSingle' => 'requiredFile|fileName|mimeType:jpeg;png;jpg;txt;docx;xlsx;pdf|minUploadSize:10| maxUploadSize:100|minWidth:200|maxWidth:200', 'fileUploadMultiple' => 'fileName|mimeType:jpeg|minFile:1|maxFile:3|minUploadSize:10| minWidth:200|maxWidth:200|maxUploadSize:100, Mensagem personalizada aqui', ]; $validator = new DevUtils\Validator(); Format::convertTypes($datas, $rules); $validator->set($datas, $rules); if (!$validator->getErros()) { echo 'Data successfully validated'; } else { echo '<pre>'; print_r($validator->getErros()); } }
验证类型(验证器)
- alpha:
检查字段是否只包含字母字符
- alphaNoSpecial:
检查字段是否包含常规文本字符,不能有重音符号
- alphaNum:
检查字段是否包含字母数字字符
- alphaNumNoSpecial:
检查字段是否包含无重音的字母、数字,不能有特殊字符
- array:
检查变量是否为数组
- arrayValues:
检查变量是否具有指定数组中的选项之一
- bool:
逻辑类型的值。
例如:true 或 false,1 或 0,是 或 否
- companyIdentification:
验证CNPJ是否有效,可以传递带或不带掩码的CNPJ
- dateAmerican:
验证美国日期是否有效
- dateBrazil:
验证巴西日期是否有效
- dateNotFuture:
验证日期不大于当前日期(接受巴西或美国格式)
- ddd:
验证在YYY或YY格式中提供的ddd,通过UF或一般方式
例如:ddd:pr,ddd为巴拉那州/巴西,或仅ddd
- email:
检查是否为有效的电子邮件
- equals:
检查字段是否与另一个字段相同,例如在文档中上面查找equals
- fileName:
检查文件名是否为有效名称,并通过删除特殊字符格式化名称
- float:
检查值是否为浮点类型(值类型)
- hour:
验证时间是否有效
- identifier:
验证CPF是否有效,可以传递带或不带掩码的CPF
- identifierOrCompany:
验证CPF或CNPJ是否有效,可以传递带或不带掩码的CPF或CNPJ
- int:
检查值是否为整数类型(如果格式为String,则尝试解析它)
- integer:
检查值是否为整数类型(此处检查精确类型)
- ip:
检查值是否为有效的IP地址
- json:
检查值是否为有效的json
- lower:
检查所有字符是否为小写
- mac:
检查值是否为有效的MAC地址
- max:
设置值的最大大小
- minHeight:
设置图像的最小高度大小(像素)
- minWidth:
设置图像的最小长度(像素)
- maxHeight: 设置图像的最大高度(像素)
- maxWidth:
设置图像的最大长度(像素)
- maxFile:
设置上传的最大文件数量
- maxUploadSize:
设置最大文件大小(字节)
- maxWords:
定义字符串中的最大单词数
- min:
设置值的最低大小
- minFile:
设置上传的最小文件数量
- minWords:
定义字符串中的最小单词数
- mimeType:
定义允许上传的扩展名
- minUploadSize:
设置最小文件大小(字节)
- numeric:
检查值是否只包含数字(左边的零可接受)
- numMax:
设置最大值,最小值为零
- numMin:
设置最小值,最小值为零
- numMonth:
检查值是否为有效的月份(1到12)
- notSpace:
检查字符串是否包含空格
- noWeekend:
检查日期(巴西或美国的日期不是周末)
- optional:
如果插入,则仅在值不同于空、null或false时进行验证
- phone:
检查值是否匹配有效的电话号码。(区号 + 号码)10或11位数字
- plate:
检查值是否匹配车牌的形状
- regex:
通过正则表达式定义值的规则
- required:
将字段设置为必填
- requiredFile:
将类型为'File'的字段设置为必填
- rgbColor:
检查字符串是否具有有效的RGB颜色
- timestamp:
检查值是否是有效的时间戳(接受巴西或美国的格式)
- upper:
检查是否所有字符都是大写
- url:
检查值是否是有效的URL地址
- zipcode:
检查值是否匹配邮编的格式
定义自定义消息
在定义了一些我们的规则之后,您还可以在特定的规则中使用逗号分隔符添加自定义消息,或者使用默认消息。
示例
<?php $validator->set($datas, [ 'name' => 'required, The name field cannot be empty', 'email' => 'email, The email field is incorrect|max:50', 'password' => 'min:8, nat least 8 characters|max:12, no máximo 12 caracteres.', ]);
格式化示例
<?php require 'vendor/autoload.php'; use DevUtils\Format; Format::companyIdentification('39678379000129'); //CNPJ ==> 39.678.379/0001-29 Format::convertTimestampBrazilToAmerican('15/04/2021 19:50:25'); //Convert Timestamp Brazil to American format Format::currency('113', 'R$ '); //Default currency BR ==> 123.00 - the 2nd parameter chooses the Currency label Format::currencyUsd('1123.45'); //Default currency USD ==> 1,123.45 - the 2nd parameter chooses the Currency label Format::dateAmerican('12-05-2020'); //return date ==> 2020-05-12 Format::dateBrazil('2020-05-12'); //return date ==> 12/05/2020 Format::identifier('73381209000'); //CPF ==> 733.812.090-00 Format::identifierOrCompany('30720870089'); //CPF/CNPJ Brazil ==> 307.208.700-89 Format::falseToNull(false); //Return ==> null Format::lower('CArrO'); //lowercase text ==> carro - the 2nd parameter chooses the charset, UTF-8 default //[Apply any type of Mask, accepts space, points and others] Format::mask('#### #### #### ####', '1234567890123456'); //Mask ==> 1234 5678 9012 3456 Format::maskStringHidden('065.775.009.96', 3, 4, '*'); //Mask of string ==> 065.***.009.96 Format::onlyNumbers('548Abc87@'); //Returns only numbers ==> 54887; Format::onlyLettersNumbers('548Abc87@'); //Returns only letters and numbers ==> 548Abc87; Format::pointOnlyValue('1.350,45'); //Currency for recording on the BD ==> 1350.45 Format::removeAccent('Açafrão'); //Remove accents and character 'ç' ==> Acafrao //Removes all special characters ==> "Acafrao com Espaco", 2nd parameter chooses whether to allow space, default true Format::removeSpecialCharacters('Açafrão com Espaco %$#@!', true); Format::returnPhoneOrAreaCode('44999998888', false); //Returns only the phone number ==> 999998888 Format::returnPhoneOrAreaCode('44999998888', true); //Returns only the phone's area code ==> 44 Format::reverse('Abacaxi'); //Returns inverted string ==> ixacabA Format::telephone('44999998888'); //Return phone format brazil ==> (44) 99999-8888 Format::ucwordsCharset('aÇafrÃo maCaRRão'); //Return first capital letter ==> Açafrão Macarrão Format::upper('Moto'); //lowercase text ==> MOTO - the 2nd parameter chooses the charset, UTF-8 default Format::zipCode('87030585'); //CEP format brazil ==> 87030-585 Format::writeDateExtensive('06/11/2020'); //Date by Long Brazilian format ==> sexta-feira, 06 de novembro de 2020 Format::writeCurrencyExtensive(1.97); //Coin by Extensive Brazilian format ==> um real e noventa e sete centavos Format::convertStringToBinary('amor'); //String to binary ==> 1100001 1101101 1101111 1110010 Format::slugfy('Polenta frita e Parmesão'); //Returns a slug from a string ==> polenta-frita-e-parmesao $data = [ 'treatingIntType' => '12', 'handlingFloatType' => '9.63', 'treatingBooleanType' => 'true', 'handlingNumericType' => '11', ]; $rules = [ 'treatingIntType' => 'convert|int', 'handlingFloatType' => 'convert|float', 'treatingBooleanType' => 'convert|bool', 'handlingNumericType' => 'convert|numeric', ]; Format::convertTypes($data, $rules); //Convert the value to its correct type ['bool', 'float', 'int', 'numeric',] /*** Return [ 'treatingIntType' => int 12 'handlingFloatType' => float 9.63 'treatingBooleanType' => boolean true 'handlingNumericType' => float 11 ] ***/ $array = [ 0 => '1', 1 => '123', 'a' => '222', 'b' => 333, 'c' => '', ]; $newArray = Format::emptyToNull($array); //Convert empty to null, - the 2nd parameter is optional, passing the desired exception /*** Return [ 0 => 1, 1 => 123, 'a' => 222, 'b' => 333, 'c' => null, ]; **/ //$value = Format::arrayToInt($array); ==> Option for other than by Reference Format::arrayToIntReference($array); //Formats array values in integer ==> [ 0 => 1, 1 => 123, 'a' => 222, 'b' => 333, 'c' => 0, ];
格式化上传文件
示例:上传单个文件
<?php $fileUploadSingle = [ 'name' => 'JPG - Upload Validation v.1.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/phpODnLGo', 'error' => 0, 'size' => 8488, ]; Format::restructFileArray($fileUploadSingle); // Call of the method responsible for normalizing the array [ 0 => [ 'name' => 'jpg___upload_validation_v_1.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/phpBmqX1i', 'error' => 0, 'size' => 8488, 'name_upload' => '22-01-2021_13_1830117018768373446425980271611322393600ad419619ec_jpg___upload_validation_v_1.jpg', ] ]
示例:上传多个文件
<?php $fileUploadMultiple = [ 'name' => [ '0' => 'JPG - Upload Validation v.1.jpg', '1' => 'PDF - Upload Validation v.1.pdf', '2' => 'PNG - Upload Validation v.1.png', ], 'type' => [ '0' => 'image/jpeg', '1' => 'application/pdf', '2' => 'image/png', ], 'tmp_name' => [ '0' => '/tmp/phpODnLGo', '1' => '/tmp/phpfmb0tL', '2' => '/tmp/phpnoejk8', ], 'error' => [ '0' => 0, '1' => 0, '2' => 0, ], 'size' => [ '0' => 8488, '1' => 818465, '2' => 1581312, ], ]; Format::restructFileArray($fileUploadMultiple); // Call of the method responsible for normalizing the array [ 0 => [ 'name' => 'jpg___upload_validation_v_1.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/phpBmqX1i', 'error' => 0, 'size' => 8488, 'name_upload' => '22-01-2021_13_1830117018768373446425980271611322393600ad419619ec_jpg___upload_validation_v_1.jpg', ], 1 => [ 'name' => 'pdf___upload_validation_v_1.pdf', 'type' => 'application/pdf', 'tmp_name' => '/tmp/phpYo0w7c', 'error' => 0, 'size' => 818465, 'name_upload' => '22-01-2021_13_170624609160164419213582611971611322393600ad41961a5a_pdf___upload_validation_v_1.pdf', ], 2 => [ 'name' => 'png___upload_validation_v_1.png', 'type' => 'image/png', 'tmp_name' => '/tmp/phpme7Yf7', 'error' => 0, 'size' => 1581312, 'name_upload' => '22-01-2021_13_8675237129330338531328755051611322393600ad41961ac8_png___upload_validation_v_1.png', ], ]
比较示例
<?php require 'vendor/autoload.php'; use DevUtils\Compare; //Returns +30 (+30 days difference) Compare::daysDifferenceBetweenData('31/05/2020', '30/06/2020'); //Accepts American date too //Compares if start date is less than end date => Returns [bool] Compare::startDateLessThanEnd('30/07/2020', '30/06/2020'); //Accepts American date too //Difference between hours ==> 01:36:28 [Hours displays negative and positive difference] Compare::differenceBetweenHours('10:41:55', '12:18:23'); //Compares if the start time is less than the end time (3rd parameter, accept custom message) Compare::startHourLessThanEnd('12:05:01', '10:20:01'); //Compares the date to the current date, and returns the person's age Compare::calculateAgeInYears('20/05/1989'); //Compares fields for equality, returns boolean //optional third parameter, false to not compare caseSensitive, default true Compare::checkDataEquality('AçaFrão', 'Açafrão'); //Compares if desired content exists in String, returns boolean Compare::contains('AçaFrão', 'çaF'); //Compares the corresponding URL with the second parameter, starts with the string entered in the first parameter. Returns boolean. Compare::beginUrlWith('/teste', '/teste/variavel'); //Compares the corresponding URL with the second parameter, ends with the string entered in the first parameter. Returns boolean. Compare::finishUrlWith('/teste', 'sistema/teste'); //Compares if the corresponding string with the first parameter is equal to the substring obtained from the second parameter. Extracting to compare 7 characters from the second parameter starting at position 0. Returns boolean. Compare::compareStringFrom('sistema', 'sistema/teste', 0, 7);
以方法形式进行的验证
<?php require 'vendor/autoload.php'; use DevUtils\ValidateCnpj; ValidateCnpj::validateCnpj('57.169.078/0001-51'); //Returns boolean, example true [Can pass with mask] use DevUtils\validateCpf; ValidateCpf::validateCpf('257.877.760-89'); //Returns boolean, example true [Can pass with mask] use DevUtils\ValidateDate; //Examples return true ValidateDate::validateDateBrazil('29/04/2021'); //Return boolean [Format dd/mm/yyyy] ValidateDate::validateDateAmerican('2021-04-29'); //Return boolean [Format yyyy-mm-dd] ValidateDate::validateTimeStamp('2021-04-29 11:17:12'); //Return boolean [Format yyyy-mm-dd hh:mm:ss] use DevUtils\ValidateHour; ValidateHour::validateHour('08:50'); //Return boolean [Format YY:YY] use DevUtils\ValidatePhone; ValidatePhone::validate('44999999999'); //Return boolean [[You can wear a mask] use DevUtils\ValidateString; ValidateString::minWords('Bruno Conte', 2) //Return boolean ValidateString::maxWords('Bruno Conte', 2) //Return boolean
操作数组
<?php require 'vendor/autoload.php'; use DevUtils\Array; $array = ['primeiro' => 15, 'segundo' => 25]; var_dump(Arrays::searchKey($array, 'primeiro')); // Search for key in array, and Return position ==> returns 0 var_dump(Arrays::searchKey($array, 'segundo')); // Search for key in array, and Return position ==> returns 1 var_dump(Arrays::searchKey($array, 'nao-existe')); // Search for key in array, and Return position ==> returns null $array = ['primeiro' => 10, 'segundo' => 20]; Arrays::renameKey($array, 'primeiro', 'novoNome'); var_dump($array); //Rename array key ==> ['novoNome' => 10, 'segundo' => 20]; $array = [ 'frutas' => ['fruta_1' => 'Maçã', 'fruta_2' => 'Pêra', 'fruta_3' => 'fruta', 'fruta_4' => 'Uva'], 'verduras' => ['verdura_1' => 'Rúcula', 'verdura_2' => 'Acelga', 'verdura_3' => 'Alface'], 'legume' => 'Tomate' ]; // Checks in the array, if there is any index with the desired value var_dump(Arrays::checkExistIndexByValue($array, 'Tomate')); // Performs the search in the array, through the key and Return an array with all indexes located var_dump(Arrays::findValueByKey($array, 'verduras')); // Performs the search in the array, through a value and returns an array with all items located var_dump(Arrays::findIndexByValue($array, 'Tomate')); $xml = new SimpleXMLElement('<root/>'); Arrays::convertArrayToXml($array, $xml); // Convert array to Xml var_dump($xml->asXML()); $array = [ 'frutas' => ['fruta_1' => 'Maçã', 'fruta_2' => 'Pêra', 'fruta_3' => 'fruta', 'fruta_4' => 'Uva'], 'verduras' => '{"verdura_1": "Rúcula", "verdura_2": "Acelga", "verdura_3": "Alface"}' ]; // Checks the array, if it has any index with JSON and turns it into an array Arrays::convertJsonIndexToArray($array); var_dump($array); $array = [ 'pessoa' => [ 'pedidos' => ['pedido1', 'pedido2'], 'categorias' => [ 'subcategorias' => [ 'subcategoria1' => 'valor teste' ] ] ] ]; // Checks if a specific index exists in a multilevel array var_dump(Arrays::checkExistIndexArrayRecursive($array, 'subcategoria1')); // Return true
工具
<?php require 'vendor/autoload.php'; use DevUtils\Utility; Utility::captureClientIp(); // Return user IP, capture per layer available, eg 201.200.25.40 /* Return an automatically generated password, there are 5 parameters, only the first one is mandatory int $size ==> Number of characters in the password (Required) bool $uppercase ==> If there will be capital letters bool $lowercase ==> If there will be lowercase letters bool $numbers ==> if there will be numbers bool $symbols ==> if there will be symbols */ Utility::generatePassword(10); /* * @return string -> Full URL string * @param string $host -> system domain * @param string $absolutePath -> absolute path * @param string $https -> 'on' to generate https url, null or other value, generate http url */ Utility::buildUrl('localhost', '/sua-url/complemento', 'on'); // Return to URL
使用PHPUnit检查CI/CD单元测试的最小覆盖率
file: .gitlab-ci.yml Add Lines: script: - composer install - ./vendor/bin/phpunit --coverage-xml coverage #Here generates the coverage file - php ./vendor/brunoconte3/dev-utils/src/CI.php coverage/index.xml 80 #Change the value 80 to your value file: .gitignore Add Line: /coverage/
将执行拉取请求,请执行单元测试和phpstan级别9
./vendor/bin/phpunit --coverage-xml coverage
如果您不知道如何运行phpstan,我将执行并调整必要的任何内容
许可证
验证器是一个开源应用程序,根据MIT许可证授权。