Reformat code automatically

This commit is contained in:
Meritoo
2022-02-12 14:46:47 +01:00
parent a3af138f0c
commit a3adae50b8
116 changed files with 19152 additions and 19091 deletions

View File

@@ -8,24 +8,23 @@ $finder = PhpCsFixer\Finder::create()
])
->notPath([
'tests/Resources/var/',
])
;
]);
return PhpCsFixer\Config::create()
->setRules([
'@Symfony' => true,
'@PhpCsFixer' => true,
'@PHP71Migration' => true,
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'@Symfony' => true,
'@PhpCsFixer' => true,
'@PHP71Migration' => true,
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'align_double_arrow' => true,
],
'blank_line_before_return' => false,
'cast_spaces' => false,
'concat_space' => [
'blank_line_before_return' => false,
'cast_spaces' => false,
'concat_space' => [
'spacing' => 'one',
],
'ordered_class_elements' => [
'ordered_class_elements' => [
'order' => [
'use_trait',
'constant_public',
@@ -43,11 +42,11 @@ return PhpCsFixer\Config::create()
],
],
'phpdoc_add_missing_param_annotation' => true,
'phpdoc_align' => false,
'phpdoc_order' => true,
'phpdoc_separation' => false,
'phpdoc_summary' => false,
'trim_array_spaces' => false,
'phpdoc_align' => false,
'phpdoc_order' => true,
'phpdoc_separation' => false,
'phpdoc_summary' => false,
'trim_array_spaces' => false,
])
->setFinder($finder)
;

View File

@@ -2,6 +2,10 @@
Common and useful classes, methods, exceptions etc.
# 1.1.8
1.
# 1.1.7
1. [Arrays] Allow to define a key of next level elements in a function that returns elements from given level
@@ -32,8 +36,8 @@ Common and useful classes, methods, exceptions etc.
# 1.1.1
1. [BaseCollection] Treat the `null` index as "no index" only while adding new element, iow. do not treat empty
string as "no index" behaviour.
1. [BaseCollection] Treat the `null` index as "no index" only while adding new element, iow. do not treat empty string
as "no index" behaviour.
2. [Miscellaneous] [Regex] Use simpler & stronger pattern to match name of file
3. Do not install `hirak/prestissimo` package while running Travis CI (incompatible with your PHP version, PHP
extensions and Composer version)
@@ -41,9 +45,9 @@ string as "no index" behaviour.
# 1.1.0
1. Rename Meritoo\Common\Collection\Collection class to Meritoo\Common\Collection\BaseCollection.
Add BaseCollection::isValidType() method to validate type of element before add it to collection.
Add BaseCollection ::prepareElements() method to allow preparation of elements in custom way.
1. Rename Meritoo\Common\Collection\Collection class to Meritoo\Common\Collection\BaseCollection. Add BaseCollection::
isValidType() method to validate type of element before add it to collection. Add BaseCollection ::prepareElements()
method to allow preparation of elements in custom way.
# 1.0.6
@@ -68,7 +72,7 @@ Add BaseCollection ::prepareElements() method to allow preparation of elements i
1. Travis CI > run many tasks using Phing > update configuration
2. Template with placeholders > verification of placeholders without values > make stronger and point out which are
missing
missing
3. Reflection > getPropertyValue() method > look for the property in parent classes
# 1.0.2
@@ -82,13 +86,13 @@ missing
7. PHPUnit > execute tests in random order
8. Implement [Psalm](https://github.com/vimeo/psalm)
9. Infection (Mutation Testing Framework) > fix bugs while running (generate proper code coverage, bugs while running
tests randomly)
tests randomly)
10. Phing > php-coveralls > add task
# 1.0.1
1. Regex > make compatible with PHP 7.3 Tests > Regex > fix "preg_match(): Compilation failed: invalid range in
character class at offset 4" bug
character class at offset 4" bug
2. Collection/storage of templates
3. Template with placeholders that may be filled by real data
4. RenderableInterface > something that may be rendered
@@ -135,7 +139,8 @@ character class at offset 4" bug
1. Tests > refactoring & minor improvements
2. Utilities > CssSelector > useful methods related to CSS selectors
3. Utilities > Bootstrap4CssSelector > useful methods related to CSS selectors and the Bootstrap4 (front-end component library)
3. Utilities > Bootstrap4CssSelector > useful methods related to CSS selectors and the Bootstrap4 (front-end component
library)
# 0.1.2
@@ -174,5 +179,6 @@ character class at offset 4" bug
4. StyleCI & PHP Coding Standards Fixer: update configuration
5. Documentation > Docker > add paragraph for PHP Coding Standards Fixer
6. Coding standard > fix automatically
7. StyleCI configuration > fix bug "The provided fixer 'binary_operator_spaces' cannot be enabled again because it was already enabled"
7. StyleCI configuration > fix bug "The provided fixer 'binary_operator_spaces' cannot be enabled again because it was
already enabled"
8. StyleCI > disable & remove

View File

@@ -25,9 +25,9 @@ composer require meritoo/common-library
2. [Collection of elements](docs/Collection/BaseCollection.md)
3. [Exceptions](docs/Static-methods.md)
4. [Static methods](docs/Static-methods.md)
1. [Arrays](docs/Static-methods/Arrays.md)
2. [Regex](docs/Static-methods/Regex.md)
3. [Uri](docs/Static-methods/Uri.md)
1. [Arrays](docs/Static-methods/Arrays.md)
2. [Regex](docs/Static-methods/Regex.md)
3. [Uri](docs/Static-methods/Uri.md)
5. [Value Objects](docs/Value-Objects.md)
# Development

View File

@@ -3,12 +3,12 @@
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<available file="${project.basedir}/phing/properties" property="custom.properties.available" />
<then>
<property file="${project.basedir}/phing/properties"/>
<property file="${project.basedir}/phing/properties" />
</then>
<else>
<property file="${project.basedir}/phing/properties.dist"/>
<property file="${project.basedir}/phing/properties.dist" />
</else>
</if>
@@ -20,11 +20,11 @@
<!-- Build app -->
<target name="build:app">
<phing phingfile="${project.basedir}/phing/app.xml" haltonfailure="true"/>
<phing phingfile="${project.basedir}/phing/app.xml" haltonfailure="true" />
</target>
<!-- Build tests -->
<target name="build:tests">
<phing phingfile="${project.basedir}/phing/tests.xml" haltonfailure="true"/>
<phing phingfile="${project.basedir}/phing/tests.xml" haltonfailure="true" />
</target>
</project>

View File

@@ -10,7 +10,7 @@ Located here: `Meritoo\Common\Test\Base\BaseTestCase`.
1. Just extend the `BaseTestCase` class or implement `Meritoo\Common\Traits\Test\Base\BaseTestCaseTrait` trait.
2. Use one of available data providers, e.g. `@dataProvider provideEmptyValue`, or asserts,
e.g. `static::assertMethodVisibility($method, $visibilityType);`
e.g. `static::assertMethodVisibility($method, $visibilityType);`
##### Examples
@@ -55,9 +55,9 @@ class MimeTypesTest extends BaseTestCase
3. [Templates](Collection/Templates.md)
4. [Exceptions](Exceptions.md)
5. [Static methods](Static-methods.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
6. [Value Objects](Value-Objects.md)
[&lsaquo; Back to `Readme`](../README.md)

View File

@@ -10,8 +10,9 @@ Common and useful classes, methods, exceptions etc.
### Info
It's a set of some elements with the same type, e.g. objects. It's iterable and countable. Provides very useful
methods. Some of them:
It's a set of some elements with the same type, e.g. objects. It's iterable and countable. Provides very useful methods.
Some of them:
- `getFirst()` - returns the first element in the collection
- `getLast()` - returns the last element in the collection
- `isEmpty()` - returns information if collection is empty
@@ -82,8 +83,8 @@ var_dump($simpleCollection->has('dolor')); // bool(true)
3. [Templates](Templates.md)
4. [Exceptions](../Exceptions.md)
5. [Static methods](../Static-methods.md)
1. [Arrays](../Static-methods/Arrays.md)
2. [Regex](../Static-methods/Regex.md)
1. [Arrays](../Static-methods/Arrays.md)
2. [Regex](../Static-methods/Regex.md)
6. [Value Objects](../Value-Objects.md)
[&lsaquo; Back to `Readme`](../../README.md)

View File

@@ -18,25 +18,26 @@ New instance can be created using:
1. Constructor:
```php
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]);
```
```php
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]);
```
2. Static method `fromArray(array $templates)` - creates and returns the collection from given array
```php
Templates::fromArray([
'first' => 'First name: %first_name%',
'last' => 'Last name: %last_name%',
]);
```
```php
Templates::fromArray([
'first' => 'First name: %first_name%',
'last' => 'Last name: %last_name%',
]);
```
##### Methods
Has all methods of parent class `Meritoo\Common\Collection\Collection` + `findTemplate(string $index)` method that finds and returns template with given index.
Has all methods of parent class `Meritoo\Common\Collection\Collection` + `findTemplate(string $index)` method that finds
and returns template with given index.
Example of usage:
@@ -49,7 +50,8 @@ $templates = new Templates([
$template = $templates->findTemplate('first'); // new Template('First name: %first_name%')
```
Throws an `Meritoo\Common\Exception\ValueObject\Template\TemplateNotFoundException` exception if template with given index was not found.
Throws an `Meritoo\Common\Exception\ValueObject\Template\TemplateNotFoundException` exception if template with given
index was not found.
# More
@@ -58,8 +60,8 @@ Throws an `Meritoo\Common\Exception\ValueObject\Template\TemplateNotFoundExcepti
3. [**Templates**](Templates.md)
4. [Exceptions](../Exceptions.md)
5. [Static methods](../Static-methods.md)
1. [Arrays](../Static-methods/Arrays.md)
2. [Regex](../Static-methods/Regex.md)
1. [Arrays](../Static-methods/Arrays.md)
2. [Regex](../Static-methods/Regex.md)
6. [Value Objects](../Value-Objects.md)
[&lsaquo; Back to `Readme`](../../README.md)

View File

@@ -17,9 +17,9 @@ Development-related information
2. Rebuild project by running command (installs packages, prepares required directories and runs tests):
```bash
docker-compose exec php phing
```
```bash
docker-compose exec php phing
```
> [What is Docker?](https://www.docker.com/what-docker)
@@ -128,6 +128,7 @@ root@18f2f0cfaa5d:/var/www/application# XDEBUG_MODE=coverage phing -f phing/test
##### Terminal
Example of output:
```bash
125 mutations were generated:
105 mutants were killed

View File

@@ -6,7 +6,8 @@ Common and useful classes, methods, exceptions etc.
### Create instance of exception
This package contains a lot of exceptions. Each of them contains static method `create()` with proper arguments that is used to create instance of the exception. Example:
This package contains a lot of exceptions. Each of them contains static method `create()` with proper arguments that is
used to create instance of the exception. Example:
```php
use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException;
@@ -17,11 +18,14 @@ throw IncorrectBundleNameException::create('RisusIpsum');
##### Short description
It's a `Meritoo\Common\Exception\Base\UnknownTypeException` class. Related to `Meritoo\Common\Type\Base\BaseType` class that represents type of something, e.g. type of button, order.
It's a `Meritoo\Common\Exception\Base\UnknownTypeException` class. Related to `Meritoo\Common\Type\Base\BaseType` class
that represents type of something, e.g. type of button, order.
##### Usage
You can extend `Meritoo\Common\Exception\Base\UnknownTypeException` class and create your own static method, e.g. `createException()`, which will be used create instance of the exception. Inside the `createException()` method you can call `parent::create()` method.
You can extend `Meritoo\Common\Exception\Base\UnknownTypeException` class and create your own static method,
e.g. `createException()`, which will be used create instance of the exception. Inside the `createException()` method you
can call `parent::create()` method.
##### Example
@@ -58,9 +62,9 @@ class UnknownSimpleTypeException extends UnknownTypeException
3. [Templates](Collection/Templates.md)
4. [**Exceptions**](Exceptions.md)
5. [Static methods](Static-methods.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
6. [Value Objects](Value-Objects.md)
[&lsaquo; Back to `Readme`](../README.md)

View File

@@ -4,7 +4,8 @@ Common and useful classes, methods, exceptions etc.
# Static methods
This package contains a lot of class with static methods, so usage is not so complicated. Just run the static method who would you like to use. Example:
This package contains a lot of class with static methods, so usage is not so complicated. Just run the static method who
would you like to use. Example:
```php
use Meritoo\Common\Utilities\Arrays;
@@ -20,9 +21,9 @@ var_dump($firstElement); // string(5) "lorem"
3. [Templates](Collection/Templates.md)
4. [Exceptions](Exceptions.md)
5. [**Static methods**](Static-methods.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
6. [Value Objects](Value-Objects.md)
[&lsaquo; Back to `Readme`](../README.md)

View File

@@ -21,16 +21,18 @@ File: `src/Utilities/Arrays.php`
1)
- array: `[]` (an empty array)
- result: `false`
- array: `[]` (an empty array)
- result: `false`
2)
- array: `["", -1]`
- result: `false`
- array: `["", -1]`
- result: `false`
3)
- array: `["", null, ""]`
- result: `true`
- array: `["", null, ""]`
- result: `true`
### getNonEmptyValues(array $values)
@@ -44,18 +46,18 @@ File: `src/Utilities/Arrays.php`
1)
- values: `[]` (no values)
- result: `[]` (an empty array)
- values: `[]` (no values)
- result: `[]` (an empty array)
2)
- values: `[null, ""]` (all empty values)
- result: `[]` (an empty array)
- values: `[null, ""]` (all empty values)
- result: `[]` (an empty array)
3)
- values: `["test 1", "", 123, null, 0]`
- result: `["test 1", 123, 0]`
- values: `["test 1", "", 123, null, 0]`
- result: `["test 1", 123, 0]`
### getNonEmptyValuesAsString(array $values, $separator = ', ')
@@ -70,27 +72,27 @@ File: `src/Utilities/Arrays.php`
1)
- values: `[]` (no values)
- separator: default or any other string
- result: `""` (an empty string)
- values: `[]` (no values)
- separator: default or any other string
- result: `""` (an empty string)
2)
- values: `[null, ""]` (all empty values)
- separator: default or any other string
- result: `""` (an empty string)
- values: `[null, ""]` (all empty values)
- separator: default or any other string
- result: `""` (an empty string)
3)
- values: `["test 1", "", 123, null, 0]`
- separator: `", "` (default)
- result: `"test 1, 123, 0"`
- values: `["test 1", "", 123, null, 0]`
- separator: `", "` (default)
- result: `"test 1, 123, 0"`
4)
- values: `["test 1", "", 123, null, 0]`
- separator: `" | "`
- result: `"test 1 | 123 | 0"`
- values: `["test 1", "", 123, null, 0]`
- separator: `" | "`
- result: `"test 1 | 123 | 0"`
# More
@@ -99,9 +101,9 @@ File: `src/Utilities/Arrays.php`
3. [Templates](../Collection/Templates.md)
4. [Exceptions](../Exceptions.md)
5. [Static methods](../Static-methods.md)
1. [**Arrays**](Arrays.md)
2. [Regex](Regex.md)
3. [Uri](Uri.md)
1. [**Arrays**](Arrays.md)
2. [Regex](Regex.md)
3. [Uri](Uri.md)
6. [Value Objects](../Value-Objects.md)
[&lsaquo; Back to `Readme`](../../README.md)

View File

@@ -21,18 +21,18 @@ File: `src/Utilities/Regex.php`
1)
- value: non-scalar or `null`
- result: `false`
- value: non-scalar or `null`
- result: `false`
2)
- value: `""` (an empty string)
- result: `""` (an empty string)
- value: `""` (an empty string)
- result: `""` (an empty string)
3)
- value: `"Lorem ipsum. Dolor sit 12.34 amet."`
- result: `"lorem-ipsum-dolor-sit-1234-amet"`
- value: `"Lorem ipsum. Dolor sit 12.34 amet."`
- result: `"lorem-ipsum-dolor-sit-1234-amet"`
### clearBeginningSlash(string): string
@@ -46,18 +46,18 @@ File: `src/Utilities/Regex.php`
1)
- string: `"lorem ipsum"`
- result: `"lorem ipsum"`
- string: `"lorem ipsum"`
- result: `"lorem ipsum"`
2)
- string: `"/lorem ipsum"`
- result: `"lorem ipsum"`
- string: `"/lorem ipsum"`
- result: `"lorem ipsum"`
3)
- string: `"/ lorem 123 ipsum"`
- result: `" lorem 123 ipsum"`
- string: `"/ lorem 123 ipsum"`
- result: `" lorem 123 ipsum"`
### clearEndingSlash(string): string
@@ -71,18 +71,18 @@ File: `src/Utilities/Regex.php`
1)
- string: `"lorem ipsum"`
- result: `"lorem ipsum"`
- string: `"lorem ipsum"`
- result: `"lorem ipsum"`
2)
- string: `"lorem ipsum/"`
- result: `"lorem ipsum"`
- string: `"lorem ipsum/"`
- result: `"lorem ipsum"`
3)
- string: `"lorem 123 ipsum /"`
- result: `"lorem 123 ipsum "`
- string: `"lorem 123 ipsum /"`
- result: `"lorem 123 ipsum "`
# More
@@ -91,9 +91,9 @@ File: `src/Utilities/Regex.php`
3. [Templates](../Collection/Templates.md)
4. [Exceptions](../Exceptions.md)
5. [Static methods](../Static-methods.md)
1. [Arrays](../Static-methods/Arrays.md)
2. [**Regex**](Regex.md)
3. [Uri](Uri.md)
1. [Arrays](../Static-methods/Arrays.md)
2. [**Regex**](Regex.md)
3. [Uri](Uri.md)
6. [Value Objects](../Value-Objects.md)
[&lsaquo; Back to `Readme`](../../README.md)

View File

@@ -22,15 +22,15 @@ File: `src/Utilities/Uri.php`
1)
- rootUrl: `"http://my.example"`
- urlParts: `""` (an empty string)
- result: `"http://my.example"`
- rootUrl: `"http://my.example"`
- urlParts: `""` (an empty string)
- result: `"http://my.example"`
2)
- rootUrl: `"http://my.example"`
- urlParts: `"/test", "/123"`
- result: `"http://my.example/test/123"`
- rootUrl: `"http://my.example"`
- urlParts: `"/test", "/123"`
- result: `"http://my.example/test/123"`
# More
@@ -39,9 +39,9 @@ File: `src/Utilities/Uri.php`
3. [Templates](../Collection/Templates.md)
4. [Exceptions](../Exceptions.md)
5. [Static methods](../Static-methods.md)
1. [Arrays](Arrays.md)
2. [Regex](Regex.md)
3. [**Uri**](Uri.md)
1. [Arrays](Arrays.md)
2. [Regex](Regex.md)
3. [**Uri**](Uri.md)
6. [Value Objects](../Value-Objects.md)
[&lsaquo; Back to `Readme`](../../README.md)

View File

@@ -15,6 +15,7 @@ Located in `Meritoo\Common\ValueObject` namespace and in `src/ValueObject/` dire
##### Info
Represents address of company, institution, user etc. Contains properties:
1. `$street` - the street
2. `$buildingNumber` - the number of building
3. `$flatNumber` - the number of flat
@@ -66,6 +67,7 @@ $asString = (string)$address; // "4th Avenue 10/200, 00123, New York"
##### Info
Represents bank account. Contains properties:
1. `$bankName` - name of bank
2. `$accountNumber` - number of bank's account
@@ -101,6 +103,7 @@ $asString = (string)$bank; // "Bank of America, 1234567890"
##### Info
Represents a company. Contains properties:
1. `$name` - name of company
2. `$address` - address of company
3. `$bankAccount` - bank account of company
@@ -145,7 +148,9 @@ $asString = (string)$company; // "Test 1, 4th Avenue 10/200, 00123, New York, Ba
##### Info
Represents human. Based on `\Meritoo\Common\Traits\ValueObject\HumanTrait` trait. Contains properties same as `HumanTrait` trait:
Represents human. Based on `\Meritoo\Common\Traits\ValueObject\HumanTrait` trait. Contains properties same
as `HumanTrait` trait:
1. `$firstName` - first name
2. `$lastName` - last name
3. `$email` - email address
@@ -186,6 +191,7 @@ $asString2 = (string)$human2; // "John Scott <john@scott.com>"
##### Info
Size, e.g. of image. Contains properties:
1. `width` - the width
2. `height` - the height
3. `unit` - unit used when width or height should be returned with unit, default: `"px"`
@@ -218,13 +224,15 @@ New instance can be created using static methods:
##### Methods
Has:
- getters and setters for `width` and `height` properties.
- setter for `separator` property
- `toString()` and `toArray()` methods that returns size represented as string and array
##### Conversion to string (using `__toString()` method)
Instance of `Size` may be represented as string that contains width and height separated by separator (default: `" x "`).
Instance of `Size` may be represented as string that contains width and height separated by separator (default: `" x "`)
.
Example:
@@ -248,6 +256,7 @@ $asString2 = (string)$size; // "200X100"
##### Info
Template with placeholders that may be filled by real data. Contains properties:
1. `$content` - raw string with placeholders (content of the template)
##### New instance
@@ -258,7 +267,9 @@ New instance can be created using constructor:
new Template('First name: %first_name%');
```
Each placeholder should be wrapped by `%` character, e.g. `%first_name%`. If content of template is an empty string or does not contain 1 placeholder at least, an `Meritoo\Common\Exception\ValueObject\Template\InvalidContentException` exception will be thrown.
Each placeholder should be wrapped by `%` character, e.g. `%first_name%`. If content of template is an empty string or
does not contain 1 placeholder at least, an `Meritoo\Common\Exception\ValueObject\Template\InvalidContentException`
exception will be thrown.
Examples of invalid content of template:
@@ -270,7 +281,8 @@ new Template('This is %test'); // With starting tag only (invalid placeholder)
##### Methods
Has 1 public method: `fill(array $values)`. Returns content of the template filled with given values (by replacing placeholders with their proper values).
Has 1 public method: `fill(array $values)`. Returns content of the template filled with given values (by replacing
placeholders with their proper values).
Example of usage:
@@ -282,7 +294,8 @@ $result = $template->fill([
]); // "My name is Jane and I am photographer"
```
Throws an `Meritoo\Common\Exception\ValueObject\Template\NotEnoughValuesException` exception if there is not enough values (iow. more placeholders than values).
Throws an `Meritoo\Common\Exception\ValueObject\Template\NotEnoughValuesException` exception if there is not enough
values (iow. more placeholders than values).
### Version
@@ -293,6 +306,7 @@ Throws an `Meritoo\Common\Exception\ValueObject\Template\NotEnoughValuesExceptio
##### Info
Represents version of software. Contains properties:
1. `$majorPart` - the "major" part of version
2. `$minorPart` - the "minor" part of version
3. `$patchPart` - the "patch" part of version
@@ -303,22 +317,22 @@ New instance can be created using:
1. Constructor:
```php
new Version(1, 0, 2);
```
```php
new Version(1, 0, 2);
```
2. Static methods:
1. `fromArray(array $version)` - creates new instance using given version as array
1. `fromArray(array $version)` - creates new instance using given version as array
```php
Version::fromArray([1, 0, 2]);
```
```php
Version::fromArray([1, 0, 2]);
```
2. `fromString(string $version)` - creates new instance using given version as string:
2. `fromString(string $version)` - creates new instance using given version as string:
```php
Version::fromString('1.0.2');
```
```php
Version::fromString('1.0.2');
```
##### Methods
@@ -326,7 +340,8 @@ Has getters for each property: `getMajorPart()`, `getMinorPart()`, `getPatchPart
##### Conversion to string (using `__toString()` method)
Instance of `Version` may be represented as string that contains all properties separated by `.` (`$majorPart`.`$minorPart`.`$patchPart`).
Instance of `Version` may be represented as string that contains all properties separated by `.` (`$majorPart`
.`$minorPart`.`$patchPart`).
Example:
@@ -342,9 +357,9 @@ $asString = (string)$version; // "1.0.2"
3. [Templates](Collection/Templates.md)
4. [Exceptions](Exceptions.md)
5. [Static methods](Static-methods.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
1. [Arrays](Static-methods/Arrays.md)
2. [Regex](Static-methods/Regex.md)
3. [Uri](Static-methods/Uri.md)
6. [**Value Objects**](Value-Objects.md)
[&lsaquo; Back to `Readme`](../README.md)

View File

@@ -3,17 +3,17 @@
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
<!-- Properties -->
<if>
<available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<available file="${project.basedir}/phing/properties" property="custom.properties.available" />
<then>
<property file="${project.basedir}/phing/properties"/>
<property file="${project.basedir}/phing/properties" />
</then>
<else>
<property file="${project.basedir}/phing/properties.dist"/>
<property file="${project.basedir}/phing/properties.dist" />
</else>
</if>
<!-- Filesets -->
<import file="${project.basedir}/phing/filesets.xml"/>
<import file="${project.basedir}/phing/filesets.xml" />
<!-- Default / main target -->
<target name="build:main"
@@ -33,16 +33,16 @@
<target name="app:composer:self-update">
<if>
<not>
<available file="${composer.path}" property="composer.local.unavailable"/>
<available file="${composer.path}" property="composer.local.unavailable" />
</not>
<then>
<if>
<os family="windows"/>
<os family="windows" />
<then>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer."/>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer." />
</then>
<else>
<exec command="${composer.download_command}" checkreturn="true" passthru="true"/>
<exec command="${composer.download_command}" checkreturn="true" passthru="true" />
</else>
</if>
</then>
@@ -50,41 +50,41 @@
<!-- Update Composer -->
<composer php="${composer.php}" composer="${composer.path}" command="selfupdate">
<arg value="--ansi"/>
<arg value="--ansi" />
</composer>
</target>
<!-- Validates composer.* files -->
<target name="app:composer:validate" depends="app:composer:install">
<composer php="${composer.php}" composer="${composer.path}" command="validate">
<arg value="--no-check-all"/>
<arg value="--strict"/>
<arg value="--ansi"/>
<arg value="--no-check-all" />
<arg value="--strict" />
<arg value="--ansi" />
</composer>
</target>
<!-- Project clean -->
<target name="app:clean">
<if>
<equals arg1="${env}" arg2="prod"/>
<equals arg1="${env}" arg2="prod" />
<then>
<echo message="[Skipped] Cleaning project (and directories cleanup) -> 'prod' environment"/>
<echo message="[Skipped] Cleaning project (and directories cleanup) -> 'prod' environment" />
</then>
<else>
<foreach list="${directoriesToEmpty}" param="directory" target="app:clean:empty"/>
<foreach list="${directoriesToEmpty}" param="directory" target="app:clean:empty" />
</else>
</if>
<foreach list="${directoriesToCheck}" param="directory" target="app:clean:check"/>
<foreach list="${directoriesToEmpty}" param="directory" target="app:permissions"/>
<foreach list="${directoriesToCheck}" param="directory" target="app:clean:check" />
<foreach list="${directoriesToEmpty}" param="directory" target="app:permissions" />
</target>
<!-- Cleaning directory (making empty) directory -->
<target name="app:clean:empty">
<if>
<available file="${directory}" type="dir" property="dir_is_available"/>
<available file="${directory}" type="dir" property="dir_is_available" />
<then>
<delete includeemptydirs="true" dir="${directory}"/>
<delete includeemptydirs="true" dir="${directory}" />
</then>
</if>
</target>
@@ -93,20 +93,20 @@
<target name="app:clean:check">
<if>
<not>
<available file="${directory}" type="dir" property="dir_is_available"/>
<available file="${directory}" type="dir" property="dir_is_available" />
</not>
<then>
<if>
<or>
<contains string="${directory}" substring="cache"/>
<contains string="${directory}" substring="logs"/>
<contains string="${directory}" substring="sessions"/>
<contains string="${directory}" substring="cache" />
<contains string="${directory}" substring="logs" />
<contains string="${directory}" substring="sessions" />
</or>
<then>
<mkdir dir="${directory}" mode="0777"/>
<mkdir dir="${directory}" mode="0777" />
</then>
<else>
<mkdir dir="${directory}" mode="0775"/>
<mkdir dir="${directory}" mode="0775" />
</else>
</if>
</then>
@@ -116,24 +116,24 @@
<!-- Installs vendors -->
<target name="app:composer:install" depends="app:composer:self-update">
<composer php="${composer.php}" composer="${composer.path}" command="install">
<arg value="--optimize-autoloader"/>
<arg value="--ansi"/>
<arg value="--optimize-autoloader" />
<arg value="--ansi" />
</composer>
</target>
<!-- Clearing cache -->
<target name="app:cache">
<if>
<istrue value="${cache.clearWithWarmup}"/>
<istrue value="${cache.clearWithWarmup}" />
<then>
<SymfonyConsole console="bin/console" command="cache:clear">
<arg name="env" value="${env}"/>
<arg name="env" value="${env}" />
</SymfonyConsole>
</then>
<else>
<SymfonyConsole console="bin/console" command="cache:clear">
<arg name="env" value="${env}"/>
<arg name="no-warmup"/>
<arg name="env" value="${env}" />
<arg name="no-warmup" />
</SymfonyConsole>
</else>
</if>
@@ -142,15 +142,15 @@
<!-- Clearing cache (faster) -->
<target name="app:cache:faster">
<SymfonyConsole console="bin/console" command="cache:clear">
<arg name="env" value="${env}"/>
<arg name="no-optional-warmers"/>
<arg name="env" value="${env}" />
<arg name="no-optional-warmers" />
</SymfonyConsole>
</target>
<!-- Warming up cache -->
<target name="app:cache:warmup">
<SymfonyConsole console="bin/console" command="cache:warmup">
<arg name="env" value="${env}"/>
<arg name="env" value="${env}" />
</SymfonyConsole>
</target>
@@ -158,10 +158,10 @@
<target name="app:permissions">
<if>
<not>
<os family="windows"/>
<os family="windows" />
</not>
<then>
<exec command="chmod -R 777 ${directory}/*"/>
<exec command="chmod -R 777 ${directory}/*" />
</then>
</if>
</target>
@@ -169,11 +169,11 @@
<!-- Checkout and finalization -->
<target name="app:checkout">
<tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M"/>
<format property="date_end" pattern="%Y-%m-%d %H:%M" />
</tstamp>
<echo msg="------------------------------------"/>
<echo msg="Build finished at: ${date_end}"/>
<echo msg="------------------------------------"/>
<echo msg="------------------------------------" />
<echo msg="Build finished at: ${date_end}" />
<echo msg="------------------------------------" />
</target>
</project>

View File

@@ -1,30 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
<autoloader/>
<autoloader />
<!-- Properties -->
<if>
<available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<available file="${project.basedir}/phing/properties" property="custom.properties.available" />
<then>
<property file="${project.basedir}/phing/properties"/>
<property file="${project.basedir}/phing/properties" />
</then>
<else>
<property file="${project.basedir}/phing/properties.dist"/>
<property file="${project.basedir}/phing/properties.dist" />
</else>
</if>
<!-- Filesets -->
<fileset id="sourcecode" dir="${dir.src}">
<include name="**/*.php"/>
<exclude name="*Test.php"/>
<exclude name="**/*Test.php"/>
<exclude name="**/Resources/**"/>
<exclude name="**/DataFixtures/**"/>
<exclude name="**/Tests/**"/>
<include name="**/*.php" />
<exclude name="*Test.php" />
<exclude name="**/*Test.php" />
<exclude name="**/Resources/**" />
<exclude name="**/DataFixtures/**" />
<exclude name="**/Tests/**" />
</fileset>
<fileset id="tests" dir="${dir.tests}">
<include name="**/*Test*.php"/>
<include name="**/*Test*.php" />
</fileset>
<!-- Default / main target -->
@@ -37,7 +37,7 @@
<!-- Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org) -->
<target name="build:fix-coding-standards">
<exec command="${tests.cs_fixer.command}" passthru="true"/>
<exec command="${tests.cs_fixer.command}" passthru="true" />
</target>
<!-- Check target -->
@@ -57,67 +57,67 @@
<!-- PHP_CodeSniffer -->
<target name="check:cs" depends="build:prepare">
<exec command="${tests.code_sniffer.command}" passthru="true"/>
<exec command="${tests.code_sniffer.command}" passthru="true" />
</target>
<!-- copy/paste detector -->
<target name="check:cpd" depends="build:prepare">
<phpcpd>
<fileset refid="sourcecode"/>
<formatter type="pmd" outfile="${dir.reports}/copy-paste-detector.xml"/>
<fileset refid="sourcecode" />
<formatter type="pmd" outfile="${dir.reports}/copy-paste-detector.xml" />
</phpcpd>
</target>
<!-- Run static analysis -->
<target name="check:phpstan" depends="build:prepare">
<exec command="${check.phpstan.command}" passthru="true"/>
<exec command="${check.phpstan.command}" passthru="true" />
</target>
<!-- Run static analysis -->
<target name="check:psalm" depends="build:prepare">
<exec command="${check.psalm.command}" passthru="true"/>
<exec command="${check.psalm.command}" passthru="true" />
</target>
<!-- Run analysis of code coverage -->
<target name="check:coveralls" depends="test:phpunit">
<exec command="${check.php_coveralls.command}" passthru="true"/>
<exec command="${check.php_coveralls.command}" passthru="true" />
</target>
<!-- PHPUnit tests -->
<target name="test:phpunit" depends="build:prepare">
<exec command="${tests.phpunit.command}" passthru="true"/>
<exec command="${tests.phpunit.command}" passthru="true" />
</target>
<!-- Run mutation testing -->
<target name="test:infection" depends="test:phpunit">
<exec command="${tests.mutation.command}" passthru="true"/>
<exec command="${tests.mutation.command}" passthru="true" />
</target>
<!-- Project build clean -->
<target name="build:clean">
<if>
<available file="${dir.reports}" type="dir" property="dir_is_available"/>
<available file="${dir.reports}" type="dir" property="dir_is_available" />
<then>
<delete dir="${dir.reports}"/>
<delete dir="${dir.reports}" />
</then>
</if>
</target>
<!-- Project build prepare -->
<target name="build:prepare" depends="build:clean">
<mkdir dir="${dir.reports}"/>
<mkdir dir="${dir.reports.coverage}"/>
<mkdir dir="${dir.reports.code_sniffer}"/>
<mkdir dir="${dir.reports}" />
<mkdir dir="${dir.reports.coverage}" />
<mkdir dir="${dir.reports.code_sniffer}" />
</target>
<!-- Checkout and finalization -->
<target name="app:checkout">
<tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M"/>
<format property="date_end" pattern="%Y-%m-%d %H:%M" />
</tstamp>
<echo msg="--------------------------------------------"/>
<echo msg="Build tests finished at: ${date_end}"/>
<echo msg="--------------------------------------------"/>
<echo msg="--------------------------------------------" />
<echo msg="Build tests finished at: ${date_end}" />
<echo msg="--------------------------------------------" />
</target>
</project>

View File

@@ -11,7 +11,7 @@
verbose="true"
>
<php>
<ini name="error_reporting" value="-1"/>
<ini name="error_reporting" value="-1" />
</php>
<testsuites>
@@ -30,9 +30,9 @@
</filter>
<logging>
<log type="coverage-html" target="build/reports/phpunit-coverage/html"/>
<log type="coverage-xml" target="build/reports/infection/coverage-xml"/>
<log type="junit" target="build/reports/infection/phpunit.junit.xml"/>
<log type="coverage-clover" target="build/reports/coveralls/clover.xml"/>
<log type="coverage-html" target="build/reports/phpunit-coverage/html" />
<log type="coverage-xml" target="build/reports/infection/coverage-xml" />
<log type="junit" target="build/reports/infection/phpunit.junit.xml" />
<log type="coverage-clover" target="build/reports/coveralls/clover.xml" />
</logging>
</phpunit>

View File

@@ -1,9 +1,9 @@
<?xml version="1.0"?>
<psalm
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
totallyTyped="false"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config file:///project/vendor/vimeo/psalm/config.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
totallyTyped="false"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config file:///project/vendor/vimeo/psalm/config.xsd"
>
<projectFiles>
<directory name="src" />

View File

@@ -40,16 +40,6 @@ abstract class BaseCollection implements CollectionInterface
$this->elements = $this->prepareElements($validated);
}
/**
* Returns representation of object as array
*
* @return array
*/
public function toArray(): array
{
return $this->elements;
}
/**
* Adds given element (at the end of collection)
*
@@ -97,45 +87,50 @@ abstract class BaseCollection implements CollectionInterface
}
}
/**
* Prepends given element (adds given element at the beginning of collection)
*
* @param mixed $element The element to prepend
*/
public function prepend($element): void
public function clear(): void
{
array_unshift($this->elements, $element);
$this->elements = [];
}
public function count(): int
{
return count($this->elements);
}
/**
* Removes given element
* Returns element with given index
*
* @param mixed $element The element to remove
*/
public function remove($element): void
{
if (0 === $this->count()) {
return;
}
foreach ($this->elements as $index => $existing) {
if ($element === $existing) {
unset($this->elements[$index]);
break;
}
}
}
/**
* Returns previous element for given element
*
* @param mixed $element The element to verify
* @param mixed $index Index / key of the element
* @return null|mixed
*/
public function getPrevious($element)
public function getByIndex($index)
{
return Arrays::getPreviousElement($this->elements, $element);
return $this->elements[$index] ?? null;
}
/**
* Returns the first element in the collection
*
* @return mixed
*/
public function getFirst()
{
return Arrays::getFirstElement($this->elements);
}
public function getIterator(): ArrayIterator
{
return new ArrayIterator($this->elements);
}
/**
* Returns the last element in the collection
*
* @return mixed
*/
public function getLast()
{
return Arrays::getLastElement($this->elements);
}
/**
@@ -150,34 +145,27 @@ abstract class BaseCollection implements CollectionInterface
}
/**
* Returns the first element in the collection
* Returns previous element for given element
*
* @return mixed
*/
public function getFirst()
{
return Arrays::getFirstElement($this->elements);
}
/**
* Returns the last element in the collection
*
* @return mixed
*/
public function getLast()
{
return Arrays::getLastElement($this->elements);
}
/**
* Returns element with given index
*
* @param mixed $index Index / key of the element
* @param mixed $element The element to verify
* @return null|mixed
*/
public function getByIndex($index)
public function getPrevious($element)
{
return $this->elements[$index] ?? null;
return Arrays::getPreviousElement($this->elements, $element);
}
/**
* Returns information if the collection has given element, iow. if given element exists in the collection
*
* @param mixed $element The element to verify
* @return bool
*/
public function has($element): bool
{
$index = Arrays::getIndexOf($this->elements, $element);
return null !== $index && false !== $index;
}
/**
@@ -212,24 +200,6 @@ abstract class BaseCollection implements CollectionInterface
return end($this->elements) === $element;
}
/**
* Returns information if the collection has given element, iow. if given element exists in the collection
*
* @param mixed $element The element to verify
* @return bool
*/
public function has($element): bool
{
$index = Arrays::getIndexOf($this->elements, $element);
return null !== $index && false !== $index;
}
public function clear(): void
{
$this->elements = [];
}
public function limit(int $max, int $offset = 0): CollectionInterface
{
$result = clone $this;
@@ -260,11 +230,6 @@ abstract class BaseCollection implements CollectionInterface
return $result;
}
public function count(): int
{
return count($this->elements);
}
public function offsetExists($offset): bool
{
return $this->exists($offset);
@@ -291,11 +256,54 @@ abstract class BaseCollection implements CollectionInterface
}
}
public function getIterator(): ArrayIterator
/**
* Prepends given element (adds given element at the beginning of collection)
*
* @param mixed $element The element to prepend
*/
public function prepend($element): void
{
return new ArrayIterator($this->elements);
array_unshift($this->elements, $element);
}
/**
* Removes given element
*
* @param mixed $element The element to remove
*/
public function remove($element): void
{
if (0 === $this->count()) {
return;
}
foreach ($this->elements as $index => $existing) {
if ($element === $existing) {
unset($this->elements[$index]);
break;
}
}
}
/**
* Returns representation of object as array
*
* @return array
*/
public function toArray(): array
{
return $this->elements;
}
/**
* Returns information if given element has valid type
*
* @param mixed $element Element of collection
* @return bool
*/
abstract protected function isValidType($element): bool;
/**
* Prepares elements to initialize the collection.
* Feel free to override and prepare elements in your way.
@@ -309,12 +317,15 @@ abstract class BaseCollection implements CollectionInterface
}
/**
* Returns information if given element has valid type
* Returns information if element with given index/key exists
*
* @param mixed $element Element of collection
* @param int|string $index The index/key of element
* @return bool
*/
abstract protected function isValidType($element): bool;
private function exists($index): bool
{
return isset($this->elements[$index]) || array_key_exists($index, $this->elements);
}
/**
* Returns elements of collection with valid types
@@ -340,15 +351,4 @@ abstract class BaseCollection implements CollectionInterface
return $result;
}
/**
* Returns information if element with given index/key exists
*
* @param int|string $index The index/key of element
* @return bool
*/
private function exists($index): bool
{
return isset($this->elements[$index]) || array_key_exists($index, $this->elements);
}
}

View File

@@ -25,8 +25,8 @@ class Templates extends BaseCollection
* Finds and returns template with given index
*
* @param string $index Index that contains required template
* @throws TemplateNotFoundException
* @return Template
* @throws TemplateNotFoundException
*/
public function findTemplate(string $index): Template
{

View File

@@ -22,25 +22,23 @@ use IteratorAggregate;
*/
interface CollectionInterface extends Countable, ArrayAccess, IteratorAggregate
{
public function toArray(): array;
public function add($element, $index = null): void;
public function addMultiple($elements, bool $useIndexes = false): void;
public function prepend($element): void;
public function clear(): void;
public function remove($element): void;
public function getPrevious($element);
public function getNext($element);
public function getByIndex($index);
public function getFirst();
public function getLast();
public function getByIndex($index);
public function getNext($element);
public function getPrevious($element);
public function has($element): bool;
public function isEmpty(): bool;
@@ -48,9 +46,11 @@ interface CollectionInterface extends Countable, ArrayAccess, IteratorAggregate
public function isLast($element): bool;
public function has($element): bool;
public function clear(): void;
public function limit(int $max, int $offset = 0): self;
public function prepend($element): void;
public function remove($element): void;
public function toArray(): array;
}

View File

@@ -31,7 +31,7 @@ abstract class UnknownTypeException extends Exception
public static function create($unknownType, BaseType $typeInstance, string $typeName): UnknownTypeException
{
$template = 'The \'%s\' type of %s is unknown. Probably doesn\'t exist or there is a typo. You should use one'
. ' of these types: %s.';
.' of these types: %s.';
$allTypes = $typeInstance->getAll();
$types = Arrays::values2string($allTypes, '', ', ') ?? '[types not found]';

View File

@@ -27,7 +27,7 @@ class IncorrectBundleNameException extends Exception
public static function create($bundleName)
{
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
. ' there everything ok?';
.' there everything ok?';
$message = sprintf($template, $bundleName);

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\File;
use Exception;
/**
* An exception used while file with given path is empty (has no content)
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class EmptyFileException extends \Exception
class EmptyFileException extends Exception
{
/**
* Creates exception

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\File;
use Exception;
/**
* An exception used while path of given file is empty
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class EmptyFilePathException extends \Exception
class EmptyFilePathException extends Exception
{
/**
* Creates exception

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\File;
use Exception;
/**
* An exception used while file with given path does not exist
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class NotExistingFileException extends \Exception
class NotExistingFileException extends Exception
{
/**
* Creates exception

View File

@@ -29,7 +29,7 @@ class MissingChildClassesException extends Exception
public static function create($parentClass): MissingChildClassesException
{
$template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract'
. ' class), but the child classes are missing. Did you forget to extend this class?';
.' class), but the child classes are missing. Did you forget to extend this class?';
$parentClassName = Reflection::getClassName($parentClass) ?? '[unknown class]';
$message = sprintf($template, $parentClassName);

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\Reflection;
use Exception;
/**
* An exception used while property does not exist in instance of class
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class NotExistingPropertyException extends \Exception
class NotExistingPropertyException extends Exception
{
/**
* Creates exception

View File

@@ -30,7 +30,7 @@ class TooManyChildClassesException extends Exception
public static function create($parentClass, array $childClasses): TooManyChildClassesException
{
$template = "The '%s' class requires one child class at most who will extend her, but more than one child"
. " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";
." class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";
$parentClassName = Reflection::getClassName($parentClass) ?? '[unknown class]';
$message = sprintf($template, $parentClassName, implode("\n- ", $childClasses), $parentClassName);

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\Regex;
use Exception;
/**
* An exception used while length of given hexadecimal value of color is incorrect
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class IncorrectColorHexLengthException extends \Exception
class IncorrectColorHexLengthException extends Exception
{
/**
* Creates exception
@@ -25,7 +27,7 @@ class IncorrectColorHexLengthException extends \Exception
public static function create($color)
{
$template = 'Length of hexadecimal value of color \'%s\' is incorrect. It\'s %d, but it should be 3 or 6.'
. ' Is there everything ok?';
.' Is there everything ok?';
$message = sprintf($template, $color, strlen($color));

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\Regex;
use Exception;
/**
* An exception used while given hexadecimal value of color is invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidColorHexValueException extends \Exception
class InvalidColorHexValueException extends Exception
{
/**
* Creates exception

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\Regex;
use Exception;
/**
* An exception used while html attributes are invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidHtmlAttributesException extends \Exception
class InvalidHtmlAttributesException extends Exception
{
/**
* Creates exception

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\Regex;
use Exception;
/**
* An exception used while url is invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidUrlException extends \Exception
class InvalidUrlException extends Exception
{
/**
* Creates exception

View File

@@ -8,13 +8,15 @@
namespace Meritoo\Common\Exception\ValueObject;
use Exception;
/**
* An exception used while dimensions of size, passed to the instance of Size class, are invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidSizeDimensionsException extends \Exception
class InvalidSizeDimensionsException extends Exception
{
/**
* Creates exception

View File

@@ -28,7 +28,7 @@ class MissingPlaceholdersInValuesException extends Exception
public static function create(string $content, array $missingPlaceholders): MissingPlaceholdersInValuesException
{
$template = 'Cannot fill template \'%s\', because of missing values for placeholder(s): %s. Did you provide all'
. ' required values?';
.' required values?';
$message = sprintf($template, $content, implode(', ', $missingPlaceholders));
return new static($message);

View File

@@ -16,6 +16,24 @@ namespace Meritoo\Common\Traits\CssSelector;
*/
trait FormCssSelector
{
/**
* Returns selector of field-set using index/position of the field-set
*
* @param string $formName Name of form (value of the "name" attribute)
* @param int $fieldSetIndex Index/Position of the field-set
* @return string
*/
public static function getFieldSetByIndexSelector($formName, $fieldSetIndex)
{
$formSelector = static::getFormByNameSelector($formName);
if (empty($formSelector) || 0 > $fieldSetIndex) {
return '';
}
return sprintf('%s fieldset:nth-of-type(%d)', $formSelector, $fieldSetIndex);
}
/**
* Returns selector of form based on its name
*
@@ -33,25 +51,6 @@ trait FormCssSelector
return sprintf('form[name="%s"]', $formName);
}
/**
* Returns selector of the input field based on its name
*
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldName Name of field (value of the "name" attribute)
* @return string
*/
public static function getInputByNameSelector($formName, $fieldName)
{
$formSelector = static::getFormByNameSelector($formName);
$fieldName = trim($fieldName);
if (empty($formSelector) || empty($fieldName)) {
return '';
}
return sprintf('%s input[name="%s"]', $formSelector, $fieldName);
}
/**
* Returns selector of the input field based on its ID
*
@@ -71,6 +70,25 @@ trait FormCssSelector
return sprintf('%s input#%s', $formSelector, $fieldId);
}
/**
* Returns selector of the input field based on its name
*
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldName Name of field (value of the "name" attribute)
* @return string
*/
public static function getInputByNameSelector($formName, $fieldName)
{
$formSelector = static::getFormByNameSelector($formName);
$fieldName = trim($fieldName);
if (empty($formSelector) || empty($fieldName)) {
return '';
}
return sprintf('%s input[name="%s"]', $formSelector, $fieldName);
}
/**
* Returns selector of label
*
@@ -89,22 +107,4 @@ trait FormCssSelector
return sprintf('%s label[for="%s"]', $formSelector, $fieldId);
}
/**
* Returns selector of field-set using index/position of the field-set
*
* @param string $formName Name of form (value of the "name" attribute)
* @param int $fieldSetIndex Index/Position of the field-set
* @return string
*/
public static function getFieldSetByIndexSelector($formName, $fieldSetIndex)
{
$formSelector = static::getFormByNameSelector($formName);
if (empty($formSelector) || 0 > $fieldSetIndex) {
return '';
}
return sprintf('%s fieldset:nth-of-type(%d)', $formSelector, $fieldSetIndex);
}
}

View File

@@ -36,35 +36,6 @@ trait BaseTestCaseTrait
*/
private static $testsDataDirPath = 'data/tests';
/**
* Provides an empty value
*
* @return Generator
*/
public function provideEmptyValue(): ?Generator
{
yield[''];
yield[' '];
yield[null];
yield[0];
yield[false];
yield[[]];
}
/**
* Provides an empty scalar value
*
* @return Generator
*/
public function provideEmptyScalarValue(): ?Generator
{
yield[''];
yield[' '];
yield[null];
yield[0];
yield[false];
}
/**
* Provides boolean value
*
@@ -72,8 +43,8 @@ trait BaseTestCaseTrait
*/
public function provideBooleanValue(): ?Generator
{
yield[false];
yield[true];
yield [false];
yield [true];
}
/**
@@ -83,10 +54,10 @@ trait BaseTestCaseTrait
*/
public function provideDateTimeInstance(): ?Generator
{
yield[new DateTime()];
yield[new DateTime('yesterday')];
yield[new DateTime('now')];
yield[new DateTime('tomorrow')];
yield [new DateTime()];
yield [new DateTime('yesterday')];
yield [new DateTime('now')];
yield [new DateTime('tomorrow')];
}
/**
@@ -96,29 +67,46 @@ trait BaseTestCaseTrait
*/
public function provideDateTimeRelativeFormat(): ?Generator
{
yield['now'];
yield['yesterday'];
yield['tomorrow'];
yield['back of 10'];
yield['front of 10'];
yield['last day of February'];
yield['first day of next month'];
yield['last day of previous month'];
yield['last day of next month'];
yield['Y-m-d'];
yield['Y-m-d 10:00'];
yield ['now'];
yield ['yesterday'];
yield ['tomorrow'];
yield ['back of 10'];
yield ['front of 10'];
yield ['last day of February'];
yield ['first day of next month'];
yield ['last day of previous month'];
yield ['last day of next month'];
yield ['Y-m-d'];
yield ['Y-m-d 10:00'];
}
/**
* Provides path of not existing file, e.g. "lorem/ipsum.jpg"
* Provides an empty scalar value
*
* @return Generator
*/
public function provideNotExistingFilePath(): ?Generator
public function provideEmptyScalarValue(): ?Generator
{
yield['lets-test.doc'];
yield['lorem/ipsum.jpg'];
yield['surprise/me/one/more/time.txt'];
yield [''];
yield [' '];
yield [null];
yield [0];
yield [false];
}
/**
* Provides an empty value
*
* @return Generator
*/
public function provideEmptyValue(): ?Generator
{
yield [''];
yield [' '];
yield [null];
yield [0];
yield [false];
yield [[]];
}
/**
@@ -128,81 +116,21 @@ trait BaseTestCaseTrait
*/
public function provideNonScalarValue(): ?Generator
{
yield[[]];
yield[null];
yield[new stdClass()];
yield [[]];
yield [null];
yield [new stdClass()];
}
/**
* Returns path of file used by tests.
* It should be placed in /data/tests directory of this project.
* Provides path of not existing file, e.g. "lorem/ipsum.jpg"
*
* @param string $fileName Name of file
* @param string $directoryPath (optional) Path of directory containing the file
* @return string
* @return Generator
*/
protected function getFilePathForTesting(string $fileName, string $directoryPath = ''): string
public function provideNotExistingFilePath(): ?Generator
{
$rootPath = Miscellaneous::getProjectRootPath();
$paths = [
$rootPath,
self::$testsDataDirPath,
$directoryPath,
$fileName,
];
return Miscellaneous::concatenatePaths($paths);
}
/**
* Verifies visibility of method
*
* @param ReflectionMethod $method Name of method or just the method to verify
* @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType
* class constants.
* @throws UnknownOopVisibilityTypeException
* @throws RuntimeException
*/
protected static function assertMethodVisibility(ReflectionMethod $method, string $visibilityType): void
{
// Type of visibility is not correct?
if (!OopVisibilityType::isCorrectType($visibilityType)) {
throw UnknownOopVisibilityTypeException::createException($visibilityType);
}
switch ($visibilityType) {
case OopVisibilityType::IS_PUBLIC:
static::assertTrue($method->isPublic());
break;
case OopVisibilityType::IS_PROTECTED:
static::assertTrue($method->isProtected());
break;
case OopVisibilityType::IS_PRIVATE:
static::assertTrue($method->isPrivate());
break;
}
}
/**
* Verifies count of method's arguments
*
* @param ReflectionMethod $method Name of method or just the method to verify
* @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method
* @param int $requiredCount (optional) Expected count/amount of required arguments of the verified
* method
* @throws RuntimeException
*/
protected static function assertMethodArgumentsCount(
ReflectionMethod $method,
int $argumentsCount = 0,
int $requiredCount = 0
): void {
static::assertSame($argumentsCount, $method->getNumberOfParameters());
static::assertSame($requiredCount, $method->getNumberOfRequiredParameters());
yield ['lets-test.doc'];
yield ['lorem/ipsum.jpg'];
yield ['surprise/me/one/more/time.txt'];
}
/**
@@ -246,6 +174,78 @@ trait BaseTestCaseTrait
static::assertNull($constructor);
}
/**
* Verifies count of method's arguments
*
* @param ReflectionMethod $method Name of method or just the method to verify
* @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method
* @param int $requiredCount (optional) Expected count/amount of required arguments of the verified
* method
* @throws RuntimeException
*/
protected static function assertMethodArgumentsCount(
ReflectionMethod $method,
int $argumentsCount = 0,
int $requiredCount = 0
): void {
static::assertSame($argumentsCount, $method->getNumberOfParameters());
static::assertSame($requiredCount, $method->getNumberOfRequiredParameters());
}
/**
* Verifies visibility of method
*
* @param ReflectionMethod $method Name of method or just the method to verify
* @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType
* class constants.
* @throws UnknownOopVisibilityTypeException
* @throws RuntimeException
*/
protected static function assertMethodVisibility(ReflectionMethod $method, string $visibilityType): void
{
// Type of visibility is not correct?
if (!OopVisibilityType::isCorrectType($visibilityType)) {
throw UnknownOopVisibilityTypeException::createException($visibilityType);
}
switch ($visibilityType) {
case OopVisibilityType::IS_PUBLIC:
static::assertTrue($method->isPublic());
break;
case OopVisibilityType::IS_PROTECTED:
static::assertTrue($method->isProtected());
break;
case OopVisibilityType::IS_PRIVATE:
static::assertTrue($method->isPrivate());
break;
}
}
/**
* Returns path of file used by tests.
* It should be placed in /data/tests directory of this project.
*
* @param string $fileName Name of file
* @param string $directoryPath (optional) Path of directory containing the file
* @return string
*/
protected function getFilePathForTesting(string $fileName, string $directoryPath = ''): string
{
$rootPath = Miscellaneous::getProjectRootPath();
$paths = [
$rootPath,
self::$testsDataDirPath,
$directoryPath,
$fileName,
];
return Miscellaneous::concatenatePaths($paths);
}
/**
* Sets path of directory with data used by test cases
*

View File

@@ -21,6 +21,13 @@ use Meritoo\Common\Type\Base\BaseType;
*/
trait BaseTypeTestCaseTrait
{
/**
* Provides type to verify and information if it's correct
*
* @return Generator
*/
abstract public function provideTypeToVerify(): Generator;
/**
* Verifies availability of all types
*/
@@ -46,11 +53,11 @@ trait BaseTypeTestCaseTrait
}
/**
* Provides type to verify and information if it's correct
* Returns all expected types of the tested type
*
* @return Generator
* @return array
*/
abstract public function provideTypeToVerify(): Generator;
abstract protected function getAllExpectedTypes(): array;
/**
* Returns instance of the tested type
@@ -58,11 +65,4 @@ trait BaseTypeTestCaseTrait
* @return BaseType
*/
abstract protected function getTestedTypeInstance(): BaseType;
/**
* Returns all expected types of the tested type
*
* @return array
*/
abstract protected function getAllExpectedTypes(): array;
}

View File

@@ -83,23 +83,13 @@ trait HumanTrait
}
/**
* Returns first name
* Returns birth date
*
* @return string
* @return null|DateTime
*/
public function getFirstName(): string
public function getBirthDate(): ?DateTime
{
return $this->firstName;
}
/**
* Returns last name
*
* @return string
*/
public function getLastName(): string
{
return $this->lastName;
return $this->birthDate;
}
/**
@@ -113,13 +103,13 @@ trait HumanTrait
}
/**
* Returns birth date
* Returns first name
*
* @return null|DateTime
* @return string
*/
public function getBirthDate(): ?DateTime
public function getFirstName(): string
{
return $this->birthDate;
return $this->firstName;
}
/**
@@ -141,4 +131,14 @@ trait HumanTrait
return trim(sprintf('%s %s', $beginning, $finish));
}
/**
* Returns last name
*
* @return string
*/
public function getLastName(): string
{
return $this->lastName;
}
}

View File

@@ -26,17 +26,6 @@ abstract class BaseType
*/
private $all;
/**
* Returns information if given type is correct
*
* @param null|string $type The type to check
* @return bool
*/
public static function isCorrectType(?string $type): bool
{
return in_array($type, (new static())->getAll());
}
/**
* Returns all types
*
@@ -50,4 +39,15 @@ abstract class BaseType
return $this->all;
}
/**
* Returns information if given type is correct
*
* @param null|string $type The type to check
* @return bool
*/
public static function isCorrectType(?string $type): bool
{
return in_array($type, (new static())->getAll());
}
}

View File

@@ -110,6 +110,29 @@ class DatePeriod extends BaseType
$this->endDate = $endDate;
}
/**
* Returns the end date of period
*
* @return null|DateTime
*/
public function getEndDate(): ?DateTime
{
return $this->endDate;
}
/**
* Sets the end date of period
*
* @param null|DateTime $endDate (optional) The end date of period. Default: null.
* @return $this
*/
public function setEndDate(?DateTime $endDate = null): self
{
$this->endDate = $endDate;
return $this;
}
/**
* Returns formatted one of the period's date: start date or end date
*
@@ -136,29 +159,6 @@ class DatePeriod extends BaseType
return $date->format($format);
}
/**
* Returns the end date of period
*
* @return null|DateTime
*/
public function getEndDate(): ?DateTime
{
return $this->endDate;
}
/**
* Sets the end date of period
*
* @param null|DateTime $endDate (optional) The end date of period. Default: null.
* @return $this
*/
public function setEndDate(?DateTime $endDate = null): self
{
$this->endDate = $endDate;
return $this;
}
/**
* Returns the start date of period
*

File diff suppressed because it is too large Load Diff

View File

@@ -46,6 +46,23 @@ class Bootstrap4CssSelector
return sprintf('%s %s', $labelSelector, $errorContainerSelector);
}
/**
* Returns selector of field's group
*
* @param string $formName Name of form (value of the "name" attribute)
* @return string
*/
public static function getFieldGroupSelector($formName)
{
$formSelector = CssSelector::getFormByNameSelector($formName);
if (empty($formSelector)) {
return '';
}
return sprintf('%s .form-group', $formSelector);
}
/**
* Returns selector of radio-button's validation error
*
@@ -65,21 +82,4 @@ class Bootstrap4CssSelector
return sprintf('%s legend.col-form-label %s', $fieldSetSelector, $errorContainerSelector);
}
/**
* Returns selector of field's group
*
* @param string $formName Name of form (value of the "name" attribute)
* @return string
*/
public static function getFieldGroupSelector($formName)
{
$formSelector = CssSelector::getFormByNameSelector($formName);
if (empty($formSelector)) {
return '';
}
return sprintf('%s .form-group', $formSelector);
}
}

View File

@@ -24,8 +24,8 @@ class Bundle
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template". Extension is not required.
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template (default: "html.twig")
* @throws IncorrectBundleNameException
* @return null|string
* @throws IncorrectBundleNameException
*/
public static function getBundleViewPath(
string $viewPath,
@@ -58,8 +58,8 @@ class Bundle
* Returns short name of bundle (without "Bundle")
*
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @throws IncorrectBundleNameException
* @return null|string
* @throws IncorrectBundleNameException
*/
public static function getShortBundleName(string $fullBundleName): ?string
{

View File

@@ -63,127 +63,6 @@ class Date
*/
public const DATE_DIFFERENCE_UNIT_YEARS = 'years';
/**
* Returns date's period (that contains start and end date) for given period
*
* @param string $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK.
* @throws Exception
* @return null|DatePeriod
*/
public static function getDatesForPeriod(string $period): ?DatePeriod
{
/*
* Type of period is incorrect?
* Nothing to do
*/
if (!DatePeriod::isCorrectType($period)) {
return null;
}
$dateStart = null;
$dateEnd = null;
switch ($period) {
case DatePeriod::LAST_WEEK:
$thisWeekStart = new DateTime('this week');
$dateStart = clone $thisWeekStart;
$dateEnd = clone $thisWeekStart;
$dateStart->sub(new DateInterval('P7D'));
$dateEnd->sub(new DateInterval('P1D'));
break;
case DatePeriod::THIS_WEEK:
$dateStart = new DateTime('this week');
$dateEnd = clone $dateStart;
$dateEnd->add(new DateInterval('P6D'));
break;
case DatePeriod::NEXT_WEEK:
$dateStart = new DateTime('this week');
$dateStart->add(new DateInterval('P7D'));
$dateEnd = clone $dateStart;
$dateEnd->add(new DateInterval('P6D'));
break;
case DatePeriod::LAST_MONTH:
$dateStart = new DateTime('first day of last month');
$dateEnd = new DateTime('last day of last month');
break;
case DatePeriod::THIS_MONTH:
$lastMonth = self::getDatesForPeriod(DatePeriod::LAST_MONTH);
$nextMonth = self::getDatesForPeriod(DatePeriod::NEXT_MONTH);
if (null !== $lastMonth) {
$dateStart = $lastMonth->getEndDate();
if (null !== $dateStart) {
$dateStart->add(new DateInterval('P1D'));
}
}
if (null !== $nextMonth) {
$dateEnd = $nextMonth->getStartDate();
if (null !== $dateEnd) {
$dateEnd->sub(new DateInterval('P1D'));
}
}
break;
case DatePeriod::NEXT_MONTH:
$dateStart = new DateTime('first day of next month');
$dateEnd = new DateTime('last day of next month');
break;
case DatePeriod::LAST_YEAR:
case DatePeriod::THIS_YEAR:
case DatePeriod::NEXT_YEAR:
$dateStart = new DateTime();
$dateEnd = new DateTime();
$yearPeriod = [
DatePeriod::LAST_YEAR,
DatePeriod::NEXT_YEAR,
];
if (in_array($period, $yearPeriod, true)) {
$yearDifference = 1;
if (DatePeriod::LAST_YEAR === $period) {
$yearDifference *= -1;
}
$modifyString = sprintf('%s year', $yearDifference);
$dateStart->modify($modifyString);
$dateEnd->modify($modifyString);
}
$year = (int)$dateStart->format('Y');
$dateStart->setDate($year, 1, 1);
$dateEnd->setDate($year, 12, 31);
break;
}
/*
* Start or end date is unknown?
* Nothing to do
*/
if (null === $dateStart || null === $dateEnd) {
return null;
}
$dateStart->setTime(0, 0);
$dateEnd->setTime(23, 59, 59);
return new DatePeriod($dateStart, $dateEnd);
}
/**
* Generates and returns random time (the hour, minute and second values)
*
@@ -227,7 +106,7 @@ class Date
return $dateTime
->setTime($hour, $minute, $second)
->format($format)
;
;
}
/**
@@ -239,46 +118,13 @@ class Date
{
$now = new DateTime();
$year = (int)$now->format('Y');
$month = (int)$now->format('m');
$day = (int)$now->format('d');
$year = (int) $now->format('Y');
$month = (int) $now->format('m');
$day = (int) $now->format('d');
return self::getDayOfWeek($year, $month, $day);
}
/**
* Returns day of week (number 0 to 6, 0 - sunday, 6 - saturday).
* Based on the Zeller's algorithm (https://en.wikipedia.org/wiki/Perpetual_calendar).
*
* @param int $year The year value
* @param int $month The month value
* @param int $day The day value
*
* @throws UnknownDatePartTypeException
* @return int
*/
public static function getDayOfWeek(int $year, int $month, int $day): int
{
static::validateYear($year);
static::validateMonth($month);
static::validateDay($day);
if ($month < 3) {
$count = 0;
$yearValue = $year - 1;
} else {
$count = 2;
$yearValue = $year;
}
$firstPart = floor(23 * $month / 9);
$secondPart = floor($yearValue / 4);
$thirdPart = floor($yearValue / 100);
$fourthPart = floor($yearValue / 400);
return ($firstPart + $day + 4 + $year + $secondPart - $thirdPart + $fourthPart - $count) % 7;
}
/**
* Returns based on locale name of current weekday
*
@@ -288,39 +134,13 @@ class Date
{
$now = new DateTime();
$year = (int)$now->format('Y');
$month = (int)$now->format('m');
$day = (int)$now->format('d');
$year = (int) $now->format('Y');
$month = (int) $now->format('m');
$day = (int) $now->format('d');
return self::getDayOfWeekName($year, $month, $day);
}
/**
* Returns name of weekday based on locale
*
* @param int $year The year value
* @param int $month The month value
* @param int $day The day value
* @return string
*/
public static function getDayOfWeekName($year, $month, $day): string
{
$hour = 0;
$minute = 0;
$second = 0;
$time = mktime($hour, $minute, $second, $month, $day, $year);
$name = strftime('%A', $time);
$encoding = mb_detect_encoding($name);
if (false === $encoding) {
$name = mb_convert_encoding($name, 'UTF-8', 'ISO-8859-2');
}
return $name;
}
/**
* Returns difference between given dates.
*
@@ -408,7 +228,7 @@ class Date
}
if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits, true)) {
$days = (int)floor($dateDiff / $daySeconds);
$days = (int) floor($dateDiff / $daySeconds);
// Difference between dates in days should be returned only?
if (self::DATE_DIFFERENCE_UNIT_DAYS === $differenceUnit) {
@@ -425,7 +245,7 @@ class Date
}
if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits, true)) {
$hours = (int)floor(($dateDiff - $daysInSeconds) / $hourSeconds);
$hours = (int) floor(($dateDiff - $daysInSeconds) / $hourSeconds);
// Difference between dates in hours should be returned only?
if (self::DATE_DIFFERENCE_UNIT_HOURS === $differenceUnit) {
@@ -442,7 +262,7 @@ class Date
}
if (null === $differenceUnit || $differenceMinutes) {
$minutes = (int)floor(($dateDiff - $daysInSeconds - $hoursInSeconds) / 60);
$minutes = (int) floor(($dateDiff - $daysInSeconds - $hoursInSeconds) / 60);
// Difference between dates in minutes should be returned only?
if ($differenceMinutes) {
@@ -455,95 +275,6 @@ class Date
return $difference;
}
/**
* Returns collection / set of dates for given start date and count of dates.
* Start from given date, add next, iterated value to given date interval and returns requested count of dates.
*
* @param DateTime $startDate The start date. Start of the collection / set.
* @param int $datesCount Count of dates in resulting collection / set
* @param string $intervalTemplate (optional) Template used to build date interval. It should contain "%d" as the
* placeholder which is replaced with a number that represents each iteration.
* Default: interval for days.
* @throws Exception
* @return array
*/
public static function getDatesCollection(DateTime $startDate, $datesCount, $intervalTemplate = 'P%dD'): array
{
$dates = [];
/*
* The template used to build date interval have to be string.
* Otherwise cannot run preg_match() function and an error occurs.
*/
if (is_string($intervalTemplate)) {
/*
* Let's verify the interval template. It should contains the "%d" placeholder and something before and
* after it.
*
* Examples:
* - P%dD
* - P%dM
* - P1Y%dMT1H
*/
$intervalPattern = '/^(\w*)\%d(\w*)$/';
$matches = [];
$matchCount = preg_match($intervalPattern, $intervalTemplate, $matches);
if ($matchCount > 0 && (!empty($matches[1]) || !empty($matches[2]))) {
$datesCount = (int)$datesCount;
for ($index = 1; $index <= $datesCount; ++$index) {
$date = clone $startDate;
$dates[$index] = $date->add(new DateInterval(sprintf($intervalTemplate, $index)));
}
}
}
return $dates;
}
/**
* Returns random date based on given start date
*
* @param DateTime $startDate (optional) Beginning of the random date. If not provided, current date will
* be used (default behaviour).
* @param int $start (optional) Start of random partition. If not provided, 1 will be used
* (default behaviour).
* @param int $end (optional) End of random partition. If not provided, 100 will be used
* (default behaviour).
* @param string $intervalTemplate (optional) Template used to build date interval. The placeholder is replaced
* with next, iterated value. If not provided, "P%sD" will be used (default
* behaviour).
* @throws Exception
* @return DateTime
*/
public static function getRandomDate(
DateTime $startDate = null,
$start = 1,
$end = 100,
$intervalTemplate = 'P%sD'
): DateTime {
if (null === $startDate) {
$startDate = new DateTime();
}
$start = (int)$start;
$end = (int)$end;
/*
* Incorrect end of random partition?
* Use start as the end of random partition
*/
if ($end < $start) {
$end = $start;
}
$randomDate = clone $startDate;
$randomInterval = new DateInterval(sprintf($intervalTemplate, random_int($start, $end)));
return $randomDate->add($randomInterval);
}
/**
* Returns the DateTime object for given value.
* If the DateTime object cannot be created, false is returned.
@@ -646,7 +377,7 @@ class Date
*/
$dateString = (new DateTime())->format($value);
if ($dateString !== (string)$value) {
if ($dateString !== (string) $value) {
return new DateTime($dateString);
}
} catch (Exception $exception) {
@@ -655,6 +386,275 @@ class Date
return false;
}
/**
* Returns collection / set of dates for given start date and count of dates.
* Start from given date, add next, iterated value to given date interval and returns requested count of dates.
*
* @param DateTime $startDate The start date. Start of the collection / set.
* @param int $datesCount Count of dates in resulting collection / set
* @param string $intervalTemplate (optional) Template used to build date interval. It should contain "%d" as the
* placeholder which is replaced with a number that represents each iteration.
* Default: interval for days.
* @return array
* @throws Exception
*/
public static function getDatesCollection(DateTime $startDate, $datesCount, $intervalTemplate = 'P%dD'): array
{
$dates = [];
/*
* The template used to build date interval have to be string.
* Otherwise cannot run preg_match() function and an error occurs.
*/
if (is_string($intervalTemplate)) {
/*
* Let's verify the interval template. It should contains the "%d" placeholder and something before and
* after it.
*
* Examples:
* - P%dD
* - P%dM
* - P1Y%dMT1H
*/
$intervalPattern = '/^(\w*)\%d(\w*)$/';
$matches = [];
$matchCount = preg_match($intervalPattern, $intervalTemplate, $matches);
if ($matchCount > 0 && (!empty($matches[1]) || !empty($matches[2]))) {
$datesCount = (int) $datesCount;
for ($index = 1; $index <= $datesCount; ++$index) {
$date = clone $startDate;
$dates[$index] = $date->add(new DateInterval(sprintf($intervalTemplate, $index)));
}
}
}
return $dates;
}
/**
* Returns date's period (that contains start and end date) for given period
*
* @param string $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK.
* @return null|DatePeriod
* @throws Exception
*/
public static function getDatesForPeriod(string $period): ?DatePeriod
{
/*
* Type of period is incorrect?
* Nothing to do
*/
if (!DatePeriod::isCorrectType($period)) {
return null;
}
$dateStart = null;
$dateEnd = null;
switch ($period) {
case DatePeriod::LAST_WEEK:
$thisWeekStart = new DateTime('this week');
$dateStart = clone $thisWeekStart;
$dateEnd = clone $thisWeekStart;
$dateStart->sub(new DateInterval('P7D'));
$dateEnd->sub(new DateInterval('P1D'));
break;
case DatePeriod::THIS_WEEK:
$dateStart = new DateTime('this week');
$dateEnd = clone $dateStart;
$dateEnd->add(new DateInterval('P6D'));
break;
case DatePeriod::NEXT_WEEK:
$dateStart = new DateTime('this week');
$dateStart->add(new DateInterval('P7D'));
$dateEnd = clone $dateStart;
$dateEnd->add(new DateInterval('P6D'));
break;
case DatePeriod::LAST_MONTH:
$dateStart = new DateTime('first day of last month');
$dateEnd = new DateTime('last day of last month');
break;
case DatePeriod::THIS_MONTH:
$lastMonth = self::getDatesForPeriod(DatePeriod::LAST_MONTH);
$nextMonth = self::getDatesForPeriod(DatePeriod::NEXT_MONTH);
if (null !== $lastMonth) {
$dateStart = $lastMonth->getEndDate();
if (null !== $dateStart) {
$dateStart->add(new DateInterval('P1D'));
}
}
if (null !== $nextMonth) {
$dateEnd = $nextMonth->getStartDate();
if (null !== $dateEnd) {
$dateEnd->sub(new DateInterval('P1D'));
}
}
break;
case DatePeriod::NEXT_MONTH:
$dateStart = new DateTime('first day of next month');
$dateEnd = new DateTime('last day of next month');
break;
case DatePeriod::LAST_YEAR:
case DatePeriod::THIS_YEAR:
case DatePeriod::NEXT_YEAR:
$dateStart = new DateTime();
$dateEnd = new DateTime();
$yearPeriod = [
DatePeriod::LAST_YEAR,
DatePeriod::NEXT_YEAR,
];
if (in_array($period, $yearPeriod, true)) {
$yearDifference = 1;
if (DatePeriod::LAST_YEAR === $period) {
$yearDifference *= -1;
}
$modifyString = sprintf('%s year', $yearDifference);
$dateStart->modify($modifyString);
$dateEnd->modify($modifyString);
}
$year = (int) $dateStart->format('Y');
$dateStart->setDate($year, 1, 1);
$dateEnd->setDate($year, 12, 31);
break;
}
/*
* Start or end date is unknown?
* Nothing to do
*/
if (null === $dateStart || null === $dateEnd) {
return null;
}
$dateStart->setTime(0, 0);
$dateEnd->setTime(23, 59, 59);
return new DatePeriod($dateStart, $dateEnd);
}
/**
* Returns day of week (number 0 to 6, 0 - sunday, 6 - saturday).
* Based on the Zeller's algorithm (https://en.wikipedia.org/wiki/Perpetual_calendar).
*
* @param int $year The year value
* @param int $month The month value
* @param int $day The day value
*
* @return int
* @throws UnknownDatePartTypeException
*/
public static function getDayOfWeek(int $year, int $month, int $day): int
{
static::validateYear($year);
static::validateMonth($month);
static::validateDay($day);
if ($month < 3) {
$count = 0;
$yearValue = $year - 1;
} else {
$count = 2;
$yearValue = $year;
}
$firstPart = floor(23 * $month / 9);
$secondPart = floor($yearValue / 4);
$thirdPart = floor($yearValue / 100);
$fourthPart = floor($yearValue / 400);
return ($firstPart + $day + 4 + $year + $secondPart - $thirdPart + $fourthPart - $count) % 7;
}
/**
* Returns name of weekday based on locale
*
* @param int $year The year value
* @param int $month The month value
* @param int $day The day value
* @return string
*/
public static function getDayOfWeekName($year, $month, $day): string
{
$hour = 0;
$minute = 0;
$second = 0;
$time = mktime($hour, $minute, $second, $month, $day, $year);
$name = strftime('%A', $time);
$encoding = mb_detect_encoding($name);
if (false === $encoding) {
$name = mb_convert_encoding($name, 'UTF-8', 'ISO-8859-2');
}
return $name;
}
/**
* Returns random date based on given start date
*
* @param DateTime $startDate (optional) Beginning of the random date. If not provided, current date will
* be used (default behaviour).
* @param int $start (optional) Start of random partition. If not provided, 1 will be used
* (default behaviour).
* @param int $end (optional) End of random partition. If not provided, 100 will be used
* (default behaviour).
* @param string $intervalTemplate (optional) Template used to build date interval. The placeholder is replaced
* with next, iterated value. If not provided, "P%sD" will be used (default
* behaviour).
* @return DateTime
* @throws Exception
*/
public static function getRandomDate(
DateTime $startDate = null,
$start = 1,
$end = 100,
$intervalTemplate = 'P%sD'
): DateTime {
if (null === $startDate) {
$startDate = new DateTime();
}
$start = (int) $start;
$end = (int) $end;
/*
* Incorrect end of random partition?
* Use start as the end of random partition
*/
if ($end < $start) {
$end = $start;
}
$randomDate = clone $startDate;
$randomInterval = new DateInterval(sprintf($intervalTemplate, random_int($start, $end)));
return $randomDate->add($randomInterval);
}
/**
* Returns information if given value is valid date
*
@@ -702,19 +702,19 @@ class Date
}
/**
* Verifies/validates given year
* Verifies/validates given day
*
* @param int $year Year to verify/validate
* @param int $day Day to verify/validate
* @throws UnknownDatePartTypeException
*/
private static function validateYear(int $year): void
private static function validateDay(int $day): void
{
// Oops, given year is incorrect
if ($year >= 0) {
// Oops, given day is incorrect
if ($day >= 1 && $day <= 31) {
return;
}
throw UnknownDatePartTypeException::createException(DatePartType::YEAR, $year);
throw UnknownDatePartTypeException::createException(DatePartType::DAY, $day);
}
/**
@@ -734,18 +734,18 @@ class Date
}
/**
* Verifies/validates given day
* Verifies/validates given year
*
* @param int $day Day to verify/validate
* @param int $year Year to verify/validate
* @throws UnknownDatePartTypeException
*/
private static function validateDay(int $day): void
private static function validateYear(int $year): void
{
// Oops, given day is incorrect
if ($day >= 1 && $day <= 31) {
// Oops, given year is incorrect
if ($year >= 0) {
return;
}
throw UnknownDatePartTypeException::createException(DatePartType::DAY, $day);
throw UnknownDatePartTypeException::createException(DatePartType::YEAR, $year);
}
}

View File

@@ -16,51 +16,6 @@ namespace Meritoo\Common\Utilities;
*/
class Locale
{
/**
* Sets locale for given category using given language and country code
*
* @param int $category Named constant specifying the category of the functions affected by the locale
* setting. It's the same constant as required by setlocale() function.
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode (optional) Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @return false|string
*
* Available categories (values of $category argument):
* - LC_ALL for all of the below
* - LC_COLLATE for string comparison, see strcoll()
* - LC_CTYPE for character classification and conversion, for example strtoupper()
* - LC_MONETARY for localeconv()
* - LC_NUMERIC for decimal separator (See also localeconv())
* - LC_TIME for date and time formatting with strftime()
* - LC_MESSAGES for system responses (available if PHP was compiled with libintl)
*/
public static function setLocale($category, $languageCode, $countryCode = '')
{
$category = (int)$category;
if (is_string($languageCode)) {
$languageCode = trim($languageCode);
}
$availableCategories = [
LC_ALL,
LC_COLLATE,
LC_CTYPE,
LC_MONETARY,
LC_NUMERIC,
LC_TIME,
LC_MESSAGES,
];
if (empty($languageCode) || !in_array($category, $availableCategories, true)) {
return false;
}
$localeLongForm = self::getLongForm($languageCode, $countryCode);
return setlocale($category, $localeLongForm);
}
/**
* Returns locale for given category
*
@@ -123,4 +78,49 @@ class Locale
return sprintf('%s_%s%s', $languageCode, strtoupper($countryCode), $encoding);
}
/**
* Sets locale for given category using given language and country code
*
* @param int $category Named constant specifying the category of the functions affected by the locale
* setting. It's the same constant as required by setlocale() function.
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode (optional) Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @return false|string
*
* Available categories (values of $category argument):
* - LC_ALL for all of the below
* - LC_COLLATE for string comparison, see strcoll()
* - LC_CTYPE for character classification and conversion, for example strtoupper()
* - LC_MONETARY for localeconv()
* - LC_NUMERIC for decimal separator (See also localeconv())
* - LC_TIME for date and time formatting with strftime()
* - LC_MESSAGES for system responses (available if PHP was compiled with libintl)
*/
public static function setLocale($category, $languageCode, $countryCode = '')
{
$category = (int) $category;
if (is_string($languageCode)) {
$languageCode = trim($languageCode);
}
$availableCategories = [
LC_ALL,
LC_COLLATE,
LC_CTYPE,
LC_MONETARY,
LC_NUMERIC,
LC_TIME,
LC_MESSAGES,
];
if (empty($languageCode) || !in_array($category, $availableCategories, true)) {
return false;
}
$localeLongForm = self::getLongForm($languageCode, $countryCode);
return setlocale($category, $localeLongForm);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -23,25 +23,68 @@ use Doctrine\ORM\QueryBuilder;
class QueryBuilderUtility
{
/**
* Returns root alias of given query builder.
* If null is returned, alias was not found.
* Adds given parameters to given query builder.
* Attention. Existing parameters will be overridden.
*
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias
* @return null|string
* @param QueryBuilder $queryBuilder The query builder
* @param array|ArrayCollection $parameters Parameters to add. Collection of Doctrine\ORM\Query\Parameter
* instances or an array with key-value pairs.
* @return QueryBuilder
*/
public static function getRootAlias(QueryBuilder $queryBuilder)
public static function addParameters(QueryBuilder $queryBuilder, $parameters)
{
$aliases = $queryBuilder->getRootAliases();
/*
* No aliases?
* No parameters?
* Nothing to do
*/
if (empty($aliases)) {
return null;
if (empty($parameters)) {
return $queryBuilder;
}
return Arrays::getFirstElement($aliases);
foreach ($parameters as $key => $parameter) {
$name = $key;
$value = $parameter;
if ($parameter instanceof Parameter) {
$name = $parameter->getName();
$value = $parameter->getValue();
}
$queryBuilder->setParameter($name, $value);
}
return $queryBuilder;
}
/**
* Deletes given entities
*
* @param EntityManager $entityManager The entity manager
* @param array|ArrayCollection $entities The entities to delete
* @param bool $flushDeleted (optional) If is set to true, flushes the deleted objects (default
* behaviour). Otherwise - not.
* @return bool
*/
public static function deleteEntities(EntityManager $entityManager, $entities, $flushDeleted = true)
{
/*
* No entities provided?
* Nothing to do
*/
if (empty($entities)) {
return false;
}
foreach ($entities as $entity) {
$entityManager->remove($entity);
}
// The deleted objects should be flushed?
if ($flushDeleted) {
$entityManager->flush();
}
return true;
}
/**
@@ -83,6 +126,28 @@ class QueryBuilderUtility
return null;
}
/**
* Returns root alias of given query builder.
* If null is returned, alias was not found.
*
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias
* @return null|string
*/
public static function getRootAlias(QueryBuilder $queryBuilder)
{
$aliases = $queryBuilder->getRootAliases();
/*
* No aliases?
* Nothing to do
*/
if (empty($aliases)) {
return null;
}
return Arrays::getFirstElement($aliases);
}
/**
* Sets the WHERE criteria in given query builder
*
@@ -149,69 +214,4 @@ class QueryBuilderUtility
return $queryBuilder;
}
/**
* Deletes given entities
*
* @param EntityManager $entityManager The entity manager
* @param array|ArrayCollection $entities The entities to delete
* @param bool $flushDeleted (optional) If is set to true, flushes the deleted objects (default
* behaviour). Otherwise - not.
* @return bool
*/
public static function deleteEntities(EntityManager $entityManager, $entities, $flushDeleted = true)
{
/*
* No entities provided?
* Nothing to do
*/
if (empty($entities)) {
return false;
}
foreach ($entities as $entity) {
$entityManager->remove($entity);
}
// The deleted objects should be flushed?
if ($flushDeleted) {
$entityManager->flush();
}
return true;
}
/**
* Adds given parameters to given query builder.
* Attention. Existing parameters will be overridden.
*
* @param QueryBuilder $queryBuilder The query builder
* @param array|ArrayCollection $parameters Parameters to add. Collection of Doctrine\ORM\Query\Parameter
* instances or an array with key-value pairs.
* @return QueryBuilder
*/
public static function addParameters(QueryBuilder $queryBuilder, $parameters)
{
/*
* No parameters?
* Nothing to do
*/
if (empty($parameters)) {
return $queryBuilder;
}
foreach ($parameters as $key => $parameter) {
$name = $key;
$value = $parameter;
if ($parameter instanceof Parameter) {
$name = $parameter->getName();
$value = $parameter->getValue();
}
$queryBuilder->setParameter($name, $value);
}
return $queryBuilder;
}
}

View File

@@ -30,35 +30,157 @@ use ReflectionProperty;
class Reflection
{
/**
* Returns names of methods for given class / object
* Returns child classes of given class.
* It's an array of namespaces of the child classes or null (if given class has not child classes).
*
* @param object|string $class The object or name of object's class
* @param bool $withoutInheritance (optional) If is set to true, only methods for given class are returned.
* Otherwise - all methods, with inherited methods too.
* @return array
* @param array|object|string $class Class who child classes should be returned. An array of objects, strings,
* object or string.
* @return null|array
* @throws CannotResolveClassNameException
*/
public static function getMethods($class, bool $withoutInheritance = false): array
public static function getChildClasses($class): ?array
{
$effect = [];
$allClasses = get_declared_classes();
$reflection = new ReflectionClass($class);
$methods = $reflection->getMethods();
/*
* No classes?
* Nothing to do
*/
if (empty($allClasses)) {
return null;
}
if (!empty($methods)) {
$className = self::getClassName($class);
$className = self::getClassName($class);
foreach ($methods as $method) {
if ($method instanceof ReflectionMethod) {
if ($withoutInheritance && $className !== $method->class) {
continue;
}
// Oops, cannot resolve class
if (null === $className) {
throw CannotResolveClassNameException::create('');
}
$effect[] = $method->name;
$childClasses = [];
foreach ($allClasses as $oneClass) {
if (self::isChildOfClass($oneClass, $className)) {
/*
* Attention. I have to use static::getRealClass() method to avoid problem with the proxy / cache
* classes. Example:
* - My\ExtraBundle\Entity\MyEntity
* - Proxies\__CG__\My\ExtraBundle\Entity\MyEntity
*
* It's actually the same class, so I have to skip it.
*/
$realClass = static::getRealClass($oneClass);
if (in_array($realClass, $childClasses, true)) {
continue;
}
$childClasses[] = $realClass;
}
}
return $effect;
return $childClasses;
}
/**
* Returns a class name for given source
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise -
* not, full name of class is returned, with namespace.
* @return null|string
*/
public static function getClassName($source, bool $withoutNamespace = false): ?string
{
/*
* First argument is not proper source of class?
* Nothing to do
*/
if (empty($source) || (!is_array($source) && !is_object($source) && !is_string($source))) {
return null;
}
$name = '';
/*
* An array of objects was provided?
* Let's use first of them
*/
if (is_array($source)) {
$source = Arrays::getFirstElement($source);
}
// Let's prepare name of class
if (is_object($source)) {
$name = get_class($source);
} elseif (is_string($source) && (class_exists($source) || trait_exists($source))) {
$name = $source;
}
/*
* Name of class is still unknown?
* Nothing to do
*/
if (empty($name)) {
return null;
}
/*
* Namespace is not required?
* Let's return name of class only
*/
if ($withoutNamespace) {
$classOnly = Miscellaneous::getLastElementOfString($name, '\\');
if (null !== $classOnly) {
$name = $classOnly;
}
return $name;
}
return static::getRealClass($name);
}
/**
* Returns namespace of class for given source
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @return string
*/
public static function getClassNamespace($source): string
{
$fullClassName = self::getClassName($source);
if (null === $fullClassName || '' === $fullClassName) {
return '';
}
$className = self::getClassName($source, true);
if ($className === $fullClassName) {
return $className;
}
return Miscellaneous::getStringWithoutLastElement($fullClassName, '\\');
}
/**
* Returns value of given constant
*
* @param object|string $class The object or name of object's class
* @param string $constant Name of the constant that contains a value
* @return mixed
*/
public static function getConstantValue($class, string $constant)
{
$reflection = new ReflectionClass($class);
if (self::hasConstant($class, $constant)) {
return $reflection->getConstant($constant);
}
return null;
}
/**
@@ -101,60 +223,160 @@ class Reflection
}
/**
* Returns information if given class / object has given method
* Returns names of methods for given class / object
*
* @param object|string $class The object or name of object's class
* @param string $method Name of the method to find
* @return bool
* @param object|string $class The object or name of object's class
* @param bool $withoutInheritance (optional) If is set to true, only methods for given class are returned.
* Otherwise - all methods, with inherited methods too.
* @return array
*/
public static function hasMethod($class, string $method): bool
public static function getMethods($class, bool $withoutInheritance = false): array
{
$reflection = new ReflectionClass($class);
$effect = [];
return $reflection->hasMethod($method);
$reflection = new ReflectionClass($class);
$methods = $reflection->getMethods();
if (!empty($methods)) {
$className = self::getClassName($class);
foreach ($methods as $method) {
if ($method instanceof ReflectionMethod) {
if ($withoutInheritance && $className !== $method->class) {
continue;
}
$effect[] = $method->name;
}
}
}
return $effect;
}
/**
* Returns information if given class / object has given property
* Returns namespace of one child class which extends given class.
* Extended class should has only one child class.
*
* @param object|string $class The object or name of object's class
* @param string $property Name of the property to find
* @return bool
*/
public static function hasProperty($class, string $property): bool
{
$reflection = new ReflectionClass($class);
return $reflection->hasProperty($property);
}
/**
* Returns information if given class / object has given constant
*
* @param object|string $class The object or name of object's class
* @param string $constant Name of the constant to find
* @return bool
*/
public static function hasConstant($class, string $constant): bool
{
$reflection = new ReflectionClass($class);
return $reflection->hasConstant($constant);
}
/**
* Returns value of given constant
*
* @param object|string $class The object or name of object's class
* @param string $constant Name of the constant that contains a value
* @param array|object|string $parentClass Class who child class should be returned. An array of objects,
* namespaces, object or namespace.
* @return mixed
* @throws TooManyChildClassesException|MissingChildClassesException|CannotResolveClassNameException
*/
public static function getConstantValue($class, string $constant)
public static function getOneChildClass($parentClass)
{
$reflection = new ReflectionClass($class);
$childClasses = self::getChildClasses($parentClass);
if (self::hasConstant($class, $constant)) {
return $reflection->getConstant($constant);
/*
* No child classes?
* Oops, the base / parent class hasn't child class
*/
if (empty($childClasses)) {
throw MissingChildClassesException::create($parentClass);
}
/*
* More than 1 child class?
* Oops, the base / parent class has too many child classes
*/
if (count($childClasses) > 1) {
throw TooManyChildClassesException::create($parentClass, $childClasses);
}
return trim($childClasses[0]);
}
/**
* Returns a parent class or false if there is no parent class
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @return false|ReflectionClass
*/
public static function getParentClass($source)
{
$className = self::getClassName($source);
$reflection = new ReflectionClass($className);
return $reflection->getParentClass();
}
/**
* Returns name of the parent class.
* If given class does not extend another, returns null.
*
* @param array|object|string $class An array of objects, namespaces, object or namespace
* @return null|string
*/
public static function getParentClassName($class): ?string
{
$className = self::getClassName($class);
$reflection = new ReflectionClass($className);
$parentClass = $reflection->getParentClass();
if (null === $parentClass || false === $parentClass) {
return null;
}
return $parentClass->getName();
}
/**
* Returns given object properties
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @param int $filter (optional) Filter of properties. Uses \ReflectionProperty class
* constants. By default all properties are returned.
* @param bool $includeParents (optional) If is set to true, properties of parent classes are
* included (recursively). Otherwise - not.
* @return ReflectionProperty[]
*/
public static function getProperties($source, int $filter = null, bool $includeParents = false): array
{
$className = self::getClassName($source);
$reflection = new ReflectionClass($className);
if (null === $filter) {
$filter = ReflectionProperty::IS_PRIVATE
+ ReflectionProperty::IS_PROTECTED
+ ReflectionProperty::IS_PUBLIC
+ ReflectionProperty::IS_STATIC;
}
$properties = $reflection->getProperties($filter);
$parentProperties = [];
if ($includeParents) {
$parent = self::getParentClass($source);
if (false !== $parent) {
$parentClass = $parent->getName();
$parentProperties = self::getProperties($parentClass, $filter, $includeParents);
}
}
return array_merge($properties, $parentProperties);
}
/**
* Returns property, the \ReflectionProperty instance, of given object
*
* @param array|object|string $class An array of objects, namespaces, object or namespace
* @param string $property Name of the property
* @param int|null $filter (optional) Filter of properties. Uses \ReflectionProperty class constants.
* By default all properties are allowed / processed.
* @return null|ReflectionProperty
*/
public static function getProperty($class, string $property, int $filter = null): ?ReflectionProperty
{
$className = self::getClassName($class);
$properties = self::getProperties($className, $filter);
if (!empty($properties)) {
foreach ($properties as $reflectionProperty) {
if ($reflectionProperty->getName() === $property) {
return $reflectionProperty;
}
}
}
return null;
@@ -243,101 +465,45 @@ class Reflection
}
/**
* Returns a class name for given source
* Returns information if given class / object has given constant
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise -
* not, full name of class is returned, with namespace.
* @return null|string
*/
public static function getClassName($source, bool $withoutNamespace = false): ?string
{
/*
* First argument is not proper source of class?
* Nothing to do
*/
if (empty($source) || (!is_array($source) && !is_object($source) && !is_string($source))) {
return null;
}
$name = '';
/*
* An array of objects was provided?
* Let's use first of them
*/
if (is_array($source)) {
$source = Arrays::getFirstElement($source);
}
// Let's prepare name of class
if (is_object($source)) {
$name = get_class($source);
} elseif (is_string($source) && (class_exists($source) || trait_exists($source))) {
$name = $source;
}
/*
* Name of class is still unknown?
* Nothing to do
*/
if (empty($name)) {
return null;
}
/*
* Namespace is not required?
* Let's return name of class only
*/
if ($withoutNamespace) {
$classOnly = Miscellaneous::getLastElementOfString($name, '\\');
if (null !== $classOnly) {
$name = $classOnly;
}
return $name;
}
return static::getRealClass($name);
}
/**
* Returns namespace of class for given source
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @return string
*/
public static function getClassNamespace($source): string
{
$fullClassName = self::getClassName($source);
if (null === $fullClassName || '' === $fullClassName) {
return '';
}
$className = self::getClassName($source, true);
if ($className === $fullClassName) {
return $className;
}
return Miscellaneous::getStringWithoutLastElement($fullClassName, '\\');
}
/**
* Returns information if given interface is implemented by given class / object
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @param string $interface The interface that should be implemented
* @param object|string $class The object or name of object's class
* @param string $constant Name of the constant to find
* @return bool
*/
public static function isInterfaceImplemented($source, string $interface): bool
public static function hasConstant($class, string $constant): bool
{
$className = self::getClassName($source);
$interfaces = class_implements($className);
$reflection = new ReflectionClass($class);
return in_array($interface, $interfaces, true);
return $reflection->hasConstant($constant);
}
/**
* Returns information if given class / object has given method
*
* @param object|string $class The object or name of object's class
* @param string $method Name of the method to find
* @return bool
*/
public static function hasMethod($class, string $method): bool
{
$reflection = new ReflectionClass($class);
return $reflection->hasMethod($method);
}
/**
* Returns information if given class / object has given property
*
* @param object|string $class The object or name of object's class
* @param string $property Name of the property to find
* @return bool
*/
public static function hasProperty($class, string $property): bool
{
$reflection = new ReflectionClass($class);
return $reflection->hasProperty($property);
}
/**
@@ -362,164 +528,69 @@ class Reflection
}
/**
* Returns given object properties
* Returns information if given interface is implemented by given class / object
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @param int $filter (optional) Filter of properties. Uses \ReflectionProperty class
* constants. By default all properties are returned.
* @param bool $includeParents (optional) If is set to true, properties of parent classes are
* included (recursively). Otherwise - not.
* @return ReflectionProperty[]
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @param string $interface The interface that should be implemented
* @return bool
*/
public static function getProperties($source, int $filter = null, bool $includeParents = false): array
public static function isInterfaceImplemented($source, string $interface): bool
{
$className = self::getClassName($source);
$reflection = new ReflectionClass($className);
$interfaces = class_implements($className);
if (null === $filter) {
$filter = ReflectionProperty::IS_PRIVATE
+ ReflectionProperty::IS_PROTECTED
+ ReflectionProperty::IS_PUBLIC
+ ReflectionProperty::IS_STATIC;
}
$properties = $reflection->getProperties($filter);
$parentProperties = [];
if ($includeParents) {
$parent = self::getParentClass($source);
if (false !== $parent) {
$parentClass = $parent->getName();
$parentProperties = self::getProperties($parentClass, $filter, $includeParents);
}
}
return array_merge($properties, $parentProperties);
return in_array($interface, $interfaces, true);
}
/**
* Returns a parent class or false if there is no parent class
* Sets values of properties in given object
*
* @param array|object|string $source An array of objects, namespaces, object or namespace
* @return false|ReflectionClass
* @param mixed $object Object that should contains given property
* @param array $propertiesValues Key-value pairs, where key - name of the property, value - value of the property
*/
public static function getParentClass($source)
public static function setPropertiesValues($object, array $propertiesValues): void
{
$className = self::getClassName($source);
$reflection = new ReflectionClass($className);
return $reflection->getParentClass();
}
/**
* Returns child classes of given class.
* It's an array of namespaces of the child classes or null (if given class has not child classes).
*
* @param array|object|string $class Class who child classes should be returned. An array of objects, strings,
* object or string.
* @return null|array
* @throws CannotResolveClassNameException
*/
public static function getChildClasses($class): ?array
{
$allClasses = get_declared_classes();
/*
* No classes?
* No properties?
* Nothing to do
*/
if (empty($allClasses)) {
return null;
if (empty($propertiesValues)) {
return;
}
$className = self::getClassName($class);
// Oops, cannot resolve class
if (null === $className) {
throw CannotResolveClassNameException::create('');
foreach ($propertiesValues as $property => $value) {
static::setPropertyValue($object, $property, $value);
}
$childClasses = [];
foreach ($allClasses as $oneClass) {
if (self::isChildOfClass($oneClass, $className)) {
/*
* Attention. I have to use static::getRealClass() method to avoid problem with the proxy / cache
* classes. Example:
* - My\ExtraBundle\Entity\MyEntity
* - Proxies\__CG__\My\ExtraBundle\Entity\MyEntity
*
* It's actually the same class, so I have to skip it.
*/
$realClass = static::getRealClass($oneClass);
if (in_array($realClass, $childClasses, true)) {
continue;
}
$childClasses[] = $realClass;
}
}
return $childClasses;
}
/**
* Returns namespace of one child class which extends given class.
* Extended class should has only one child class.
* Sets value of given property in given object
*
* @param array|object|string $parentClass Class who child class should be returned. An array of objects,
* namespaces, object or namespace.
* @return mixed
* @throws TooManyChildClassesException|MissingChildClassesException|CannotResolveClassNameException
* @param mixed $object Object that should contains given property
* @param string $property Name of the property
* @param mixed $value Value of the property
* @throws NotExistingPropertyException
*/
public static function getOneChildClass($parentClass)
public static function setPropertyValue($object, string $property, $value): void
{
$childClasses = self::getChildClasses($parentClass);
$reflectionProperty = self::getProperty($object, $property);
/*
* No child classes?
* Oops, the base / parent class hasn't child class
*/
if (empty($childClasses)) {
throw MissingChildClassesException::create($parentClass);
// Oops, property does not exist
if (null === $reflectionProperty) {
throw NotExistingPropertyException::create($object, $property);
}
/*
* More than 1 child class?
* Oops, the base / parent class has too many child classes
*/
if (count($childClasses) > 1) {
throw TooManyChildClassesException::create($parentClass, $childClasses);
$isPublic = $reflectionProperty->isPublic();
if (!$isPublic) {
$reflectionProperty->setAccessible(true);
}
return trim($childClasses[0]);
}
$reflectionProperty->setValue($object, $value);
/**
* Returns property, the \ReflectionProperty instance, of given object
*
* @param array|object|string $class An array of objects, namespaces, object or namespace
* @param string $property Name of the property
* @param int|null $filter (optional) Filter of properties. Uses \ReflectionProperty class constants.
* By default all properties are allowed / processed.
* @return null|ReflectionProperty
*/
public static function getProperty($class, string $property, int $filter = null): ?ReflectionProperty
{
$className = self::getClassName($class);
$properties = self::getProperties($className, $filter);
if (!empty($properties)) {
foreach ($properties as $reflectionProperty) {
if ($reflectionProperty->getName() === $property) {
return $reflectionProperty;
}
}
if (!$isPublic) {
$reflectionProperty->setAccessible(false);
}
return null;
}
/**
@@ -563,135 +634,6 @@ class Reflection
return $uses;
}
/**
* Returns name of the parent class.
* If given class does not extend another, returns null.
*
* @param array|object|string $class An array of objects, namespaces, object or namespace
* @return null|string
*/
public static function getParentClassName($class): ?string
{
$className = self::getClassName($class);
$reflection = new ReflectionClass($className);
$parentClass = $reflection->getParentClass();
if (null === $parentClass || false === $parentClass) {
return null;
}
return $parentClass->getName();
}
/**
* Sets value of given property in given object
*
* @param mixed $object Object that should contains given property
* @param string $property Name of the property
* @param mixed $value Value of the property
* @throws NotExistingPropertyException
*/
public static function setPropertyValue($object, string $property, $value): void
{
$reflectionProperty = self::getProperty($object, $property);
// Oops, property does not exist
if (null === $reflectionProperty) {
throw NotExistingPropertyException::create($object, $property);
}
$isPublic = $reflectionProperty->isPublic();
if (!$isPublic) {
$reflectionProperty->setAccessible(true);
}
$reflectionProperty->setValue($object, $value);
if (!$isPublic) {
$reflectionProperty->setAccessible(false);
}
}
/**
* Sets values of properties in given object
*
* @param mixed $object Object that should contains given property
* @param array $propertiesValues Key-value pairs, where key - name of the property, value - value of the property
*/
public static function setPropertiesValues($object, array $propertiesValues): void
{
/*
* No properties?
* Nothing to do
*/
if (empty($propertiesValues)) {
return;
}
foreach ($propertiesValues as $property => $value) {
static::setPropertyValue($object, $property, $value);
}
}
/**
* Returns the real class name of a class name that could be a proxy
*
* @param string $class Class to verify
* @return string
*/
private static function getRealClass(string $class): string
{
if (false === $pos = strrpos($class, '\\' . Proxy::MARKER . '\\')) {
return $class;
}
return substr($class, $pos + Proxy::MARKER_LENGTH + 2);
}
/**
* Returns value of given property using the property represented by reflection.
* If value cannot be fetched, makes the property accessible temporarily.
*
* @param mixed $object Object that should contains given property
* @param string $property Name of the property that contains a value
* @param null|ReflectionProperty $reflectionProperty (optional) Property represented by reflection
* @return mixed
*/
private static function getPropertyValueByReflectionProperty(
$object,
string $property,
?ReflectionProperty $reflectionProperty = null
) {
$value = null;
$valueFound = false;
$className = self::getClassName($object);
try {
if (null === $reflectionProperty) {
$reflectionProperty = new ReflectionProperty($className, $property);
}
$value = $reflectionProperty->getValue($object);
$valueFound = true;
} catch (ReflectionException $exception) {
}
if (null !== $reflectionProperty) {
$reflectionProperty->setAccessible(true);
$value = $reflectionProperty->getValue($object);
$valueFound = true;
$reflectionProperty->setAccessible(false);
}
return [
$value,
$valueFound,
];
}
/**
* Returns value of given property using getter of the property
*
@@ -828,4 +770,62 @@ class Reflection
return null;
}
/**
* Returns value of given property using the property represented by reflection.
* If value cannot be fetched, makes the property accessible temporarily.
*
* @param mixed $object Object that should contains given property
* @param string $property Name of the property that contains a value
* @param null|ReflectionProperty $reflectionProperty (optional) Property represented by reflection
* @return mixed
*/
private static function getPropertyValueByReflectionProperty(
$object,
string $property,
?ReflectionProperty $reflectionProperty = null
) {
$value = null;
$valueFound = false;
$className = self::getClassName($object);
try {
if (null === $reflectionProperty) {
$reflectionProperty = new ReflectionProperty($className, $property);
}
$value = $reflectionProperty->getValue($object);
$valueFound = true;
} catch (ReflectionException $exception) {
}
if (null !== $reflectionProperty) {
$reflectionProperty->setAccessible(true);
$value = $reflectionProperty->getValue($object);
$valueFound = true;
$reflectionProperty->setAccessible(false);
}
return [
$value,
$valueFound,
];
}
/**
* Returns the real class name of a class name that could be a proxy
*
* @param string $class Class to verify
* @return string
*/
private static function getRealClass(string $class): string
{
if (false === $pos = strrpos($class, '\\'.Proxy::MARKER.'\\')) {
return $class;
}
return substr($class, $pos + Proxy::MARKER_LENGTH + 2);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -26,6 +26,86 @@ class Repository
*/
public const POSITION_KEY = 'position';
/**
* Returns query builder for given entity's repository.
* The entity should contain given property, e.g. "name".
*
* @param EntityRepository $repository Repository of the entity
* @param string $property (optional) Name of property used by the ORDER BY clause
* @param string $direction (optional) Direction used by the ORDER BY clause ("ASC" or "DESC")
* @return QueryBuilder
*/
public static function getEntityOrderedQueryBuilder(
EntityRepository $repository,
$property = 'name',
$direction = 'ASC'
) {
$alias = 'qb';
$queryBuilder = $repository->createQueryBuilder($alias);
if (empty($property)) {
return $queryBuilder;
}
return $queryBuilder->orderBy(sprintf('%s.%s', $alias, $property), $direction);
}
/**
* Returns extreme position (max or min) of given items
*
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $max (optional) If is set to true, maximum value is returned. Otherwise - minimum.
* @return int
*/
public static function getExtremePosition(array $items, $max = true)
{
/*
* No items?
* Nothing to do
*/
if (empty($items)) {
return null;
}
$extreme = null;
foreach ($items as $item) {
// Not sortable?
if (!self::isSortable($item)) {
continue;
}
$position = null;
// Let's grab the position
if (is_object($item)) {
$position = $item->getPosition();
} elseif (array_key_exists(static::POSITION_KEY, $item)) {
$position = $item[static::POSITION_KEY];
}
// Maximum value is expected?
if ($max) {
// Position was found and it's larger than previously found position (the extreme position)?
if (null === $extreme || (null !== $position && $position > $extreme)) {
$extreme = $position;
}
continue;
}
/*
* Minimum value is expected here.
* Position was found and it's smaller than previously found position (the extreme position)?
*/
if (null === $extreme || (null !== $position && $position < $extreme)) {
$extreme = $position;
}
}
return $extreme;
}
/**
* Replenishes positions of given items
*
@@ -92,86 +172,6 @@ class Repository
}
}
/**
* Returns extreme position (max or min) of given items
*
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $max (optional) If is set to true, maximum value is returned. Otherwise - minimum.
* @return int
*/
public static function getExtremePosition(array $items, $max = true)
{
/*
* No items?
* Nothing to do
*/
if (empty($items)) {
return null;
}
$extreme = null;
foreach ($items as $item) {
// Not sortable?
if (!self::isSortable($item)) {
continue;
}
$position = null;
// Let's grab the position
if (is_object($item)) {
$position = $item->getPosition();
} elseif (array_key_exists(static::POSITION_KEY, $item)) {
$position = $item[static::POSITION_KEY];
}
// Maximum value is expected?
if ($max) {
// Position was found and it's larger than previously found position (the extreme position)?
if (null === $extreme || (null !== $position && $position > $extreme)) {
$extreme = $position;
}
continue;
}
/*
* Minimum value is expected here.
* Position was found and it's smaller than previously found position (the extreme position)?
*/
if (null === $extreme || (null !== $position && $position < $extreme)) {
$extreme = $position;
}
}
return $extreme;
}
/**
* Returns query builder for given entity's repository.
* The entity should contain given property, e.g. "name".
*
* @param EntityRepository $repository Repository of the entity
* @param string $property (optional) Name of property used by the ORDER BY clause
* @param string $direction (optional) Direction used by the ORDER BY clause ("ASC" or "DESC")
* @return QueryBuilder
*/
public static function getEntityOrderedQueryBuilder(
EntityRepository $repository,
$property = 'name',
$direction = 'ASC'
) {
$alias = 'qb';
$queryBuilder = $repository->createQueryBuilder($alias);
if (empty($property)) {
return $queryBuilder;
}
return $queryBuilder->orderBy(sprintf('%s.%s', $alias, $property), $direction);
}
/**
* Returns information if given item is sortable
*

View File

@@ -16,6 +16,45 @@ namespace Meritoo\Common\Utilities;
*/
class Uri
{
/**
* Adds protocol to given url, if the url does not contain given protocol.
* Returns the new url.
*
* @param string $url Url string
* @param string $protocol (optional) Protocol string
* @return string
*/
public static function addProtocolToUrl($url, $protocol = 'http')
{
$pattern = sprintf('/^%s.*/', $protocol);
if ((bool) preg_match($pattern, $url)) {
return $url;
}
return sprintf('%s://%s', $protocol, $url);
}
public static function buildUrl(string $rootUrl, string ...$urlParts): string
{
$rootUrl = Regex::clearEndingSlash($rootUrl);
if (empty($urlParts) || Arrays::containsEmptyStringsOnly($urlParts)) {
return $rootUrl;
}
array_walk($urlParts, static function (&$part) {
$part = Regex::clearBeginningSlash($part);
$part = Regex::clearEndingSlash($part);
});
return sprintf(
'%s/%s',
$rootUrl,
implode('/', $urlParts)
);
}
/**
* Returns full uri string
*
@@ -42,36 +81,7 @@ class Uri
return $requestedUrl;
}
return self::getServerNameOrIp(true) . $requestedUrl;
}
/**
* Returns server name or IP address
*
* @param bool $withProtocol (optional) If is set to true, protocol name is included. Otherwise isn't.
* @return string
*/
public static function getServerNameOrIp($withProtocol = false)
{
$host = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_HOST');
/*
* Unknown host / server?
* Nothing to do
*/
if (empty($host)) {
return '';
}
/*
* With protocol?
* Let's include the protocol
*/
if ($withProtocol) {
return sprintf('%s://%s', self::getProtocolName(), $host);
}
return $host;
return self::getServerNameOrIp(true).$requestedUrl;
}
/**
@@ -108,6 +118,69 @@ class Uri
return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_REFERER');
}
/**
* Returns url to resource secured by given htpasswd login and password
*
* @param string $url A path / url to some resource, e.g. page, image, css file
* @param string $user (optional) User name used to log in
* @param string $password (optional) User password used to log in
* @return string
*/
public static function getSecuredUrl($url, $user = '', $password = '')
{
/*
* Url is not provided?
* Nothing to do
*/
if (empty($url)) {
return '';
}
$protocol = self::getProtocolName();
$host = self::getServerNameOrIp();
if (!Regex::startsWith($url, '/')) {
$url = sprintf('/%s', $url);
}
$url = $host.$url;
if (!empty($user) && !empty($password)) {
$url = sprintf('%s:%s@%s', $user, $password, $url);
}
return sprintf('%s://%s', $protocol, $url);
}
/**
* Returns server name or IP address
*
* @param bool $withProtocol (optional) If is set to true, protocol name is included. Otherwise isn't.
* @return string
*/
public static function getServerNameOrIp($withProtocol = false)
{
$host = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_HOST');
/*
* Unknown host / server?
* Nothing to do
*/
if (empty($host)) {
return '';
}
/*
* With protocol?
* Let's include the protocol
*/
if ($withProtocol) {
return sprintf('%s://%s', self::getProtocolName(), $host);
}
return $host;
}
/**
* Returns user's IP address
*
@@ -119,35 +192,26 @@ class Uri
}
/**
* Returns name and version of user's web browser
* Returns name of user's operating system
*
* @param bool $withVersion (optional) If is set to true, version of the browser is returned too. Otherwise -
* name only.
* @return string
*/
public static function getUserWebBrowserName($withVersion = false)
public static function getUserOperatingSystemName()
{
$info = self::getUserWebBrowserInfo();
$knownBrowsers = [
'Firefox/([\d\.]+)$' => 'Mozilla Firefox',
'OPR/([\d\.]+)$' => 'Opera',
'Chrome/([\d\.]+)$' => 'Google Chrome',
'Safari/([\d\.]+)$' => 'Apple Safari',
$knownSystems = [
'Linux' => 'Linux',
'Win' => 'Windows',
'Mac' => 'Mac OS',
];
foreach ($knownBrowsers as $pattern => $browserName) {
foreach ($knownSystems as $pattern => $systemName) {
$matches = [];
$matchCount = preg_match(sprintf('|%s|', $pattern), $info, $matches);
if ($matchCount > 0) {
if ($withVersion) {
$version = $matches[1];
return sprintf('%s %s', $browserName, $version);
}
return $browserName;
return $systemName;
}
}
@@ -181,48 +245,41 @@ class Uri
}
/**
* Returns name of user's operating system
* Returns name and version of user's web browser
*
* @param bool $withVersion (optional) If is set to true, version of the browser is returned too. Otherwise -
* name only.
* @return string
*/
public static function getUserOperatingSystemName()
public static function getUserWebBrowserName($withVersion = false)
{
$info = self::getUserWebBrowserInfo();
$knownSystems = [
'Linux' => 'Linux',
'Win' => 'Windows',
'Mac' => 'Mac OS',
$knownBrowsers = [
'Firefox/([\d\.]+)$' => 'Mozilla Firefox',
'OPR/([\d\.]+)$' => 'Opera',
'Chrome/([\d\.]+)$' => 'Google Chrome',
'Safari/([\d\.]+)$' => 'Apple Safari',
];
foreach ($knownSystems as $pattern => $systemName) {
foreach ($knownBrowsers as $pattern => $browserName) {
$matches = [];
$matchCount = preg_match(sprintf('|%s|', $pattern), $info, $matches);
if ($matchCount > 0) {
return $systemName;
if ($withVersion) {
$version = $matches[1];
return sprintf('%s %s', $browserName, $version);
}
return $browserName;
}
}
return '';
}
/**
* Returns information if running server is localhost
*
* @return bool
*/
public static function isServerLocalhost()
{
$serverNameOrIp = strtolower(self::getServerNameOrIp());
return in_array($serverNameOrIp, [
'localhost',
'127.0.0.1',
'127.0.1.1',
]);
}
/**
* Returns information if given url is external, from another server / domain
*
@@ -260,6 +317,22 @@ class Uri
return !Regex::contains($url, $currentUrlPattern);
}
/**
* Returns information if running server is localhost
*
* @return bool
*/
public static function isServerLocalhost()
{
$serverNameOrIp = strtolower(self::getServerNameOrIp());
return in_array($serverNameOrIp, [
'localhost',
'127.0.0.1',
'127.0.1.1',
]);
}
/**
* Replenishes protocol in the given url
*
@@ -298,77 +371,4 @@ class Uri
return sprintf('%s://%s', $protocol, $url);
}
/**
* Returns url to resource secured by given htpasswd login and password
*
* @param string $url A path / url to some resource, e.g. page, image, css file
* @param string $user (optional) User name used to log in
* @param string $password (optional) User password used to log in
* @return string
*/
public static function getSecuredUrl($url, $user = '', $password = '')
{
/*
* Url is not provided?
* Nothing to do
*/
if (empty($url)) {
return '';
}
$protocol = self::getProtocolName();
$host = self::getServerNameOrIp();
if (!Regex::startsWith($url, '/')) {
$url = sprintf('/%s', $url);
}
$url = $host . $url;
if (!empty($user) && !empty($password)) {
$url = sprintf('%s:%s@%s', $user, $password, $url);
}
return sprintf('%s://%s', $protocol, $url);
}
/**
* Adds protocol to given url, if the url does not contain given protocol.
* Returns the new url.
*
* @param string $url Url string
* @param string $protocol (optional) Protocol string
* @return string
*/
public static function addProtocolToUrl($url, $protocol = 'http')
{
$pattern = sprintf('/^%s.*/', $protocol);
if ((bool)preg_match($pattern, $url)) {
return $url;
}
return sprintf('%s://%s', $protocol, $url);
}
public static function buildUrl(string $rootUrl, string ...$urlParts): string
{
$rootUrl = Regex::clearEndingSlash($rootUrl);
if (empty($urlParts) || Arrays::containsEmptyStringsOnly($urlParts)) {
return $rootUrl;
}
array_walk($urlParts, static function (&$part) {
$part = Regex::clearBeginningSlash($part);
$part = Regex::clearEndingSlash($part);
});
return sprintf(
'%s/%s',
$rootUrl,
implode('/', $urlParts)
);
}
}

View File

@@ -88,13 +88,33 @@ class Address
}
/**
* Returns street
* Returns number of building
*
* @return string
*/
public function getStreet()
public function getBuildingNumber()
{
return $this->street;
return $this->buildingNumber;
}
/**
* Returns city, location
*
* @return string
*/
public function getCity()
{
return $this->city;
}
/**
* Returns number of flat
*
* @return string
*/
public function getFlatNumber()
{
return $this->flatNumber;
}
/**
@@ -118,23 +138,13 @@ class Address
}
/**
* Returns number of building
* Returns street
*
* @return string
*/
public function getBuildingNumber()
public function getStreet()
{
return $this->buildingNumber;
}
/**
* Returns number of flat
*
* @return string
*/
public function getFlatNumber()
{
return $this->flatNumber;
return $this->street;
}
/**
@@ -146,14 +156,4 @@ class Address
{
return $this->zipCode;
}
/**
* Returns city, location
*
* @return string
*/
public function getCity()
{
return $this->city;
}
}

View File

@@ -59,16 +59,6 @@ class BankAccount
return Arrays::getNonEmptyValuesAsString($values);
}
/**
* Returns name of bank
*
* @return string
*/
public function getBankName()
{
return $this->bankName;
}
/**
* Returns number of bank's account
*
@@ -78,4 +68,14 @@ class BankAccount
{
return $this->accountNumber;
}
/**
* Returns name of bank
*
* @return string
*/
public function getBankName()
{
return $this->bankName;
}
}

View File

@@ -69,16 +69,6 @@ class Company
return Arrays::getNonEmptyValuesAsString($values);
}
/**
* Returns name of company
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns address of company
*
@@ -98,4 +88,14 @@ class Company
{
return $this->bankAccount;
}
/**
* Returns name of company
*
* @return string
*/
public function getName()
{
return $this->name;
}
}

View File

@@ -62,8 +62,8 @@ class Size
*/
private function __construct($width = null, $height = null, $unit = 'px')
{
$width = (int)$width;
$height = (int)$height;
$width = (int) $width;
$height = (int) $height;
if ($width < 0 || $height < 0) {
throw new InvalidSizeDimensionsException($width, $height);
@@ -88,14 +88,84 @@ class Size
}
/**
* Sets separator used when converting to string
* Creates new instance from given array
*
* @param string $separator The separator
* The array should contain 2 elements: width and height.
* Examples: ['800', '600'], [800, 600].
*
* @param array $array The size represented as array
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
* @return null|Size
*/
public static function fromArray(array $array, $unit = 'px')
{
// Requirements for given array:
// - indexes "0" and "1"
// - should contains exactly 2 elements
if (
array_key_exists(0, $array)
&& array_key_exists(1, $array)
&& 2 === count($array)
) {
[$width, $height] = $array;
return new self($width, $height, $unit);
}
return null;
}
/**
* Creates new instance from given string
*
* @param string $size The size represented as string (width and height separated by given separator)
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
* @param string $separator (optional) Separator used to split width and height. Default: " x ".
* @return null|Size
*/
public static function fromString($size, $unit = 'px', $separator = ' x ')
{
if (is_string($size)) {
$matches = [];
$pattern = Regex::getSizePattern($separator);
if ((bool) preg_match($pattern, $size, $matches)) {
$width = (int) $matches[1];
$height = (int) $matches[2];
$sizeObject = new self($width, $height, $unit);
return $sizeObject->setSeparator($separator);
}
}
return null;
}
/**
* Returns the height
*
* @param bool $withUnit (optional) If is set to true, height is returned with unit ("px"). Otherwise - without
* (default behaviour).
* @return int|string
*/
public function getHeight($withUnit = false)
{
if ($withUnit) {
return sprintf('%d %s', $this->height, $this->unit);
}
return $this->height;
}
/**
* Sets the height
*
* @param int $height The height
* @return Size
*/
public function setSeparator($separator)
public function setHeight($height)
{
$this->separator = $separator;
$this->height = (int) $height;
return $this;
}
@@ -124,55 +194,24 @@ class Size
*/
public function setWidth($width)
{
$this->width = (int)$width;
$this->width = (int) $width;
return $this;
}
/**
* Returns the height
* Sets separator used when converting to string
*
* @param bool $withUnit (optional) If is set to true, height is returned with unit ("px"). Otherwise - without
* (default behaviour).
* @return int|string
*/
public function getHeight($withUnit = false)
{
if ($withUnit) {
return sprintf('%d %s', $this->height, $this->unit);
}
return $this->height;
}
/**
* Sets the height
*
* @param int $height The height
* @param string $separator The separator
* @return Size
*/
public function setHeight($height)
public function setSeparator($separator)
{
$this->height = (int)$height;
$this->separator = $separator;
return $this;
}
/**
* Returns string representation of instance of this class, e.g. '200 x 100' or '200x100'
*
* @param bool $withUnit (optional) If is set to true, width and height are returned with unit ("px"). Otherwise
* - without (default behaviour).
* @return string
*/
public function toString($withUnit = false)
{
$width = $this->getWidth($withUnit);
$height = $this->getHeight($withUnit);
return sprintf('%s%s%s', $width, $this->separator, $height);
}
/**
* Returns instance of this class as an array.
* Values of the array are width and height, eg. [800, 600] or ['800px', '600px'].
@@ -190,56 +229,17 @@ class Size
}
/**
* Creates new instance from given string
* Returns string representation of instance of this class, e.g. '200 x 100' or '200x100'
*
* @param string $size The size represented as string (width and height separated by given separator)
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
* @param string $separator (optional) Separator used to split width and height. Default: " x ".
* @return null|Size
* @param bool $withUnit (optional) If is set to true, width and height are returned with unit ("px"). Otherwise
* - without (default behaviour).
* @return string
*/
public static function fromString($size, $unit = 'px', $separator = ' x ')
public function toString($withUnit = false)
{
if (is_string($size)) {
$matches = [];
$pattern = Regex::getSizePattern($separator);
$width = $this->getWidth($withUnit);
$height = $this->getHeight($withUnit);
if ((bool)preg_match($pattern, $size, $matches)) {
$width = (int)$matches[1];
$height = (int)$matches[2];
$sizeObject = new self($width, $height, $unit);
return $sizeObject->setSeparator($separator);
}
}
return null;
}
/**
* Creates new instance from given array
*
* The array should contain 2 elements: width and height.
* Examples: ['800', '600'], [800, 600].
*
* @param array $array The size represented as array
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
* @return null|Size
*/
public static function fromArray(array $array, $unit = 'px')
{
// Requirements for given array:
// - indexes "0" and "1"
// - should contains exactly 2 elements
if (
array_key_exists(0, $array)
&& array_key_exists(1, $array)
&& 2 === count($array)
) {
list($width, $height) = $array;
return new self($width, $height, $unit);
}
return null;
return sprintf('%s%s%s', $width, $this->separator, $height);
}
}

View File

@@ -54,8 +54,8 @@ class Template
* Returns content of the template filled with given values (by replacing placeholders with their proper values)
*
* @param array $values Pairs of key-value where: key - name of placeholder, value - value of the placeholder
* @throws MissingPlaceholdersInValuesException
* @return string
* @throws MissingPlaceholdersInValuesException
*/
public function fill(array $values): string
{
@@ -82,41 +82,6 @@ class Template
return $result;
}
/**
* Returns information if given template is valid
*
* @param string $content Raw string with placeholders to validate (content of the template)
* @return bool
*/
private static function isValid(string $content): bool
{
if ('' === $content) {
return false;
}
return (bool)preg_match_all(static::getPlaceholderPattern(), $content);
}
/**
* Returns placeholders of given template
*
* @param string $content Content of template
* @return array
*/
private static function getPlaceholders(string $content): array
{
$result = [];
$matchCount = preg_match_all(static::getPlaceholderPattern(), $content, $result);
if (false !== $matchCount && 0 < $matchCount) {
foreach ($result as $index => $placeholders) {
$result[$index] = array_unique($placeholders);
}
}
return $result;
}
/**
* Returns regular expression that defines format of placeholder
*
@@ -148,4 +113,39 @@ class Template
static::PLACEHOLDER_TAG
);
}
/**
* Returns placeholders of given template
*
* @param string $content Content of template
* @return array
*/
private static function getPlaceholders(string $content): array
{
$result = [];
$matchCount = preg_match_all(static::getPlaceholderPattern(), $content, $result);
if (false !== $matchCount && 0 < $matchCount) {
foreach ($result as $index => $placeholders) {
$result[$index] = array_unique($placeholders);
}
}
return $result;
}
/**
* Returns information if given template is valid
*
* @param string $content Raw string with placeholders to validate (content of the template)
* @return bool
*/
private static function isValid(string $content): bool
{
if ('' === $content) {
return false;
}
return (bool) preg_match_all(static::getPlaceholderPattern(), $content);
}
}

View File

@@ -65,36 +65,41 @@ class Version
}
/**
* Returns the "major" part.
* Incremented when you make incompatible API changes.
* Returns new instance based on given version as array.
* Given version should contain 3 integers, 1 per each part ("major", "minor" and "patch").
*
* @return int
* Examples:
* [1, 0, 2];
* [10, 4, 0];
*
* @param array $version The version
* @return null|Version
*/
public function getMajorPart()
public static function fromArray(array $version)
{
return $this->majorPart;
}
/*
* No version provided?
* Nothing to do
*/
if (empty($version)) {
return null;
}
/**
* Returns the "minor" part.
* Incremented when you add functionality in a backwards-compatible manner.
*
* @return int
*/
public function getMinorPart()
{
return $this->minorPart;
}
$count = count($version);
/**
* Returns the "patch" part.
* Incremented when you make backwards-compatible bug fixes.
*
* @return int
*/
public function getPatchPart()
{
return $this->patchPart;
/*
* Incorrect version?
* Nothing to do
*/
if (3 !== $count) {
return null;
}
$majorPart = (int) $version[0];
$minorPart = (int) $version[1];
$patchPart = (int) $version[2];
return new static($majorPart, $minorPart, $patchPart);
}
/**
@@ -132,48 +137,43 @@ class Version
return null;
}
$majorPart = (int)$matches[1];
$minorPart = (int)$matches[2];
$patchPart = (int)$matches[3];
$majorPart = (int) $matches[1];
$minorPart = (int) $matches[2];
$patchPart = (int) $matches[3];
return new static($majorPart, $minorPart, $patchPart);
}
/**
* Returns new instance based on given version as array.
* Given version should contain 3 integers, 1 per each part ("major", "minor" and "patch").
* Returns the "major" part.
* Incremented when you make incompatible API changes.
*
* Examples:
* [1, 0, 2];
* [10, 4, 0];
*
* @param array $version The version
* @return null|Version
* @return int
*/
public static function fromArray(array $version)
public function getMajorPart()
{
/*
* No version provided?
* Nothing to do
*/
if (empty($version)) {
return null;
}
return $this->majorPart;
}
$count = count($version);
/**
* Returns the "minor" part.
* Incremented when you add functionality in a backwards-compatible manner.
*
* @return int
*/
public function getMinorPart()
{
return $this->minorPart;
}
/*
* Incorrect version?
* Nothing to do
*/
if (3 !== $count) {
return null;
}
$majorPart = (int)$version[0];
$minorPart = (int)$version[1];
$patchPart = (int)$version[2];
return new static($majorPart, $minorPart, $patchPart);
/**
* Returns the "patch" part.
* Incremented when you make backwards-compatible bug fixes.
*
* @return int
*/
public function getPatchPart()
{
return $this->patchPart;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -27,6 +27,44 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class DateTimeCollectionTest extends BaseTestCase
{
public function provideDifferentTypesOfElements(): ?Generator
{
yield [
'An empty array',
[],
[],
];
yield [
'Valid elements only',
[
new DateTime('2001-01-01'),
new DateTime('2001-01-02'),
],
[
new DateTime('2001-01-01'),
new DateTime('2001-01-02'),
],
];
yield [
'Mixed elements',
[
1,
'test',
new DateTime('2001-01-01'),
'',
[],
234,
new DateTime('2001-01-02'),
],
[
2 => new DateTime('2001-01-01'),
6 => new DateTime('2001-01-02'),
],
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -51,42 +89,4 @@ class DateTimeCollectionTest extends BaseTestCase
$collection = new DateTimeCollection($elements);
static::assertEquals($expectedElements, $collection->toArray(), $description);
}
public function provideDifferentTypesOfElements(): ?Generator
{
yield[
'An empty array',
[],
[],
];
yield[
'Valid elements only',
[
new DateTime('2001-01-01'),
new DateTime('2001-01-02'),
],
[
new DateTime('2001-01-01'),
new DateTime('2001-01-02'),
],
];
yield[
'Mixed elements',
[
1,
'test',
new DateTime('2001-01-01'),
'',
[],
234,
new DateTime('2001-01-02'),
],
[
2 => new DateTime('2001-01-01'),
6 => new DateTime('2001-01-02'),
],
];
}
}

View File

@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Meritoo\Test\Common\Collection;
use Generator;
use Meritoo\Common\Collection\IntegerCollection;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
@@ -25,6 +26,45 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class IntegerCollectionTest extends BaseTestCase
{
public function provideDifferentTypesOfElements(): ?Generator
{
yield [
'An empty array',
[],
[],
];
yield [
'Valid elements only',
[
1,
2,
3,
],
[
1,
2,
3,
],
];
yield [
'Mixed elements',
[
1,
'test',
'',
[],
234,
'test',
],
[
0 => 1,
4 => 234,
],
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -49,43 +89,4 @@ class IntegerCollectionTest extends BaseTestCase
$collection = new IntegerCollection($elements);
static::assertSame($expectedElements, $collection->toArray(), $description);
}
public function provideDifferentTypesOfElements(): ?\Generator
{
yield[
'An empty array',
[],
[],
];
yield[
'Valid elements only',
[
1,
2,
3,
],
[
1,
2,
3,
],
];
yield[
'Mixed elements',
[
1,
'test',
'',
[],
234,
'test',
],
[
0 => 1,
4 => 234,
],
];
}
}

View File

@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Meritoo\Test\Common\Collection;
use Generator;
use Meritoo\Common\Collection\StringCollection;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
@@ -25,6 +26,46 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class StringCollectionTest extends BaseTestCase
{
public function provideDifferentTypesOfElements(): ?Generator
{
yield [
'An empty array',
[],
[],
];
yield [
'Valid elements only',
[
'1',
'test',
'',
],
[
'1',
'test',
'',
],
];
yield [
'Mixed elements',
[
1,
'test',
'',
[],
234,
'test',
],
[
1 => 'test',
2 => '',
5 => 'test',
],
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -49,44 +90,4 @@ class StringCollectionTest extends BaseTestCase
$collection = new StringCollection($elements);
static::assertSame($expectedElements, $collection->toArray(), $description);
}
public function provideDifferentTypesOfElements(): ?\Generator
{
yield[
'An empty array',
[],
[],
];
yield[
'Valid elements only',
[
'1',
'test',
'',
],
[
'1',
'test',
'',
],
];
yield[
'Mixed elements',
[
1,
'test',
'',
[],
234,
'test',
],
[
1 => 'test',
2 => '',
5 => 'test',
],
];
}
}

View File

@@ -26,6 +26,102 @@ use Meritoo\Common\ValueObject\Template;
*/
class TemplatesTest extends BaseTestCase
{
public function provideArrayWithTemplates(): ?Generator
{
yield [
'An empty array',
[],
new Templates(),
];
yield [
'Number-based indexes',
[
'First name: %first_name%',
'Last name: %last_name%',
],
new Templates([
new Template('First name: %first_name%'),
new Template('Last name: %last_name%'),
]),
];
yield [
'String-based indexes',
[
'first' => 'First name: %first_name%',
'last' => 'Last name: %last_name%',
],
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
];
}
public function provideTemplatesToFind(): ?Generator
{
yield [
'2 templates only',
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'first',
new Template('First name: %first_name%'),
];
yield [
'Different indexes',
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
1 => new Template('Hi %name%, how are you?'),
'2' => new Template('Your score is: %score%'),
]),
'1',
new Template('Hi %name%, how are you?'),
];
}
public function provideTemplatesWithNotExistingIndex(): ?Generator
{
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
yield [
new Templates(),
'test',
sprintf($template, 'test'),
];
yield [
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'test',
sprintf($template, 'test'),
];
yield [
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'',
sprintf($template, ''),
];
yield [
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'4',
sprintf($template, 4),
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -37,14 +133,15 @@ class TemplatesTest extends BaseTestCase
/**
* @param string $description Description of test
* @param array $templates Pairs of key-value where: key - template's index, value - template's content
* @param Templates $expected Expected collection/storage of templates
* @param Templates $templates All templates
* @param string $index Index that contains required template
* @param Template $expected Expected template
*
* @dataProvider provideArrayWithTemplates
* @dataProvider provideTemplatesToFind
*/
public function testFromArray(string $description, array $templates, Templates $expected): void
public function testFindTemplate(string $description, Templates $templates, string $index, Template $expected): void
{
static::assertEquals($expected, Templates::fromArray($templates), $description);
static::assertEquals($expected, $templates->findTemplate($index), $description);
}
public function testFindTemplateUsingEmptyCollection(): void
@@ -79,110 +176,13 @@ class TemplatesTest extends BaseTestCase
/**
* @param string $description Description of test
* @param Templates $templates All templates
* @param string $index Index that contains required template
* @param Template $expected Expected template
* @param array $templates Pairs of key-value where: key - template's index, value - template's content
* @param Templates $expected Expected collection/storage of templates
*
* @dataProvider provideTemplatesToFind
* @dataProvider provideArrayWithTemplates
*/
public function testFindTemplate(string $description, Templates $templates, string $index, Template $expected): void
public function testFromArray(string $description, array $templates, Templates $expected): void
{
static::assertEquals($expected, $templates->findTemplate($index), $description);
}
public function provideArrayWithTemplates(): ?Generator
{
yield[
'An empty array',
[],
new Templates(),
];
yield[
'Number-based indexes',
[
'First name: %first_name%',
'Last name: %last_name%',
],
new Templates([
new Template('First name: %first_name%'),
new Template('Last name: %last_name%'),
]),
];
yield[
'String-based indexes',
[
'first' => 'First name: %first_name%',
'last' => 'Last name: %last_name%',
],
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
];
}
public function provideTemplatesWithNotExistingIndex(): ?Generator
{
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
yield[
new Templates(),
'test',
sprintf($template, 'test'),
];
yield[
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'test',
sprintf($template, 'test'),
];
yield[
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'',
sprintf($template, ''),
];
yield[
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'4',
sprintf($template, 4),
];
}
public function provideTemplatesToFind(): ?Generator
{
yield[
'2 templates only',
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
]),
'first',
new Template('First name: %first_name%'),
];
yield[
'Different indexes',
new Templates([
'first' => new Template('First name: %first_name%'),
'last' => new Template('Last name: %last_name%'),
1 => new Template('Hi %name%, how are you?'),
'2' => new Template('Your score is: %score%'),
]),
'1',
new Template('Hi %name%, how are you?'),
];
static::assertEquals($expected, Templates::fromArray($templates), $description);
}
}

View File

@@ -29,16 +29,16 @@ class UnknownTypeExceptionTest extends BaseTestCase
static::assertConstructorVisibilityAndArguments(UnknownTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testWithoutException()
{
self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2'));
}
public function testTheException()
{
$this->expectException(UnknownTestTypeException::class);
self::assertEmpty((new TestService())->getTranslatedType('test_3'));
}
public function testWithoutException()
{
self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2'));
}
}
/**
@@ -89,8 +89,8 @@ class TestService
* Returns translated type (for testing purposes)
*
* @param string $type Type of something (for testing purposes)
* @throws UnknownTestTypeException
* @return string
* @throws UnknownTestTypeException
*/
public function getTranslatedType(string $type): string
{

View File

@@ -20,10 +20,34 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Bundle\IncorrectBundleNameException
* @covers \Meritoo\Common\Exception\Bundle\IncorrectBundleNameException
*/
class IncorrectBundleNameExceptionTest extends BaseTestCase
{
public function provideBundleNameAndMessage(): Generator
{
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
.' there everything ok?';
yield [
'An empty string as name of bundle',
'',
sprintf($template, ''),
];
yield [
'String with spaces as name of bundle',
'This is test',
sprintf($template, 'This is test'),
];
yield [
'String without spaces as name of bundle',
'ThisIsTest',
sprintf($template, 'ThisIsTest'),
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -45,28 +69,4 @@ class IncorrectBundleNameExceptionTest extends BaseTestCase
$exception = IncorrectBundleNameException::create($bundleName);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideBundleNameAndMessage(): Generator
{
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
. ' there everything ok?';
yield[
'An empty string as name of bundle',
'',
sprintf($template, ''),
];
yield[
'String with spaces as name of bundle',
'This is test',
sprintf($template, 'This is test'),
];
yield[
'String without spaces as name of bundle',
'ThisIsTest',
sprintf($template, 'ThisIsTest'),
];
}
}

View File

@@ -21,10 +21,39 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Type\UnknownDatePartTypeException
* @covers \Meritoo\Common\Exception\Type\UnknownDatePartTypeException
*/
class UnknownDatePartTypeExceptionTest extends BaseTestCase
{
/**
* Provides type of date part, incorrect value and expected exception's message
*
* @return Generator
*/
public function provideDatePartAndValue()
{
$template = 'The \'%s\' type of date part (with value %s) is unknown. Probably doesn\'t exist or there is a'
.' typo. You should use one of these types: day, hour, minute, month, second, year.';
yield [
DatePartType::DAY,
'44',
sprintf($template, DatePartType::DAY, '44'),
];
yield [
DatePartType::MONTH,
'22',
sprintf($template, DatePartType::MONTH, '22'),
];
yield [
DatePartType::MINUTE,
'77',
sprintf($template, DatePartType::MINUTE, '77'),
];
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownDatePartTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
@@ -42,33 +71,4 @@ class UnknownDatePartTypeExceptionTest extends BaseTestCase
$exception = UnknownDatePartTypeException::createException($unknownDatePart, $value);
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides type of date part, incorrect value and expected exception's message
*
* @return Generator
*/
public function provideDatePartAndValue()
{
$template = 'The \'%s\' type of date part (with value %s) is unknown. Probably doesn\'t exist or there is a'
. ' typo. You should use one of these types: day, hour, minute, month, second, year.';
yield[
DatePartType::DAY,
'44',
sprintf($template, DatePartType::DAY, '44'),
];
yield[
DatePartType::MONTH,
'22',
sprintf($template, DatePartType::MONTH, '22'),
];
yield[
DatePartType::MINUTE,
'77',
sprintf($template, DatePartType::MINUTE, '77'),
];
}
}

View File

@@ -20,10 +20,30 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\File\EmptyFileException
* @covers \Meritoo\Common\Exception\File\EmptyFileException
*/
class EmptyFileExceptionTest extends BaseTestCase
{
/**
* Provides path of the empty file and expected exception's message
*
* @return Generator
*/
public function providePathOfFile()
{
$template = 'File with path \'%s\' is empty (has no content). Did you provide path of proper file?';
yield [
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield [
'images/show/car.jpg',
sprintf($template, 'images/show/car.jpg'),
];
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFileException::class, OopVisibilityType::IS_PUBLIC, 3);
@@ -40,24 +60,4 @@ class EmptyFileExceptionTest extends BaseTestCase
$exception = EmptyFileException::create($emptyFilePath);
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides path of the empty file and expected exception's message
*
* @return Generator
*/
public function providePathOfFile()
{
$template = 'File with path \'%s\' is empty (has no content). Did you provide path of proper file?';
yield[
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield[
'images/show/car.jpg',
sprintf($template, 'images/show/car.jpg'),
];
}
}

View File

@@ -19,18 +19,18 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\File\EmptyFilePathException
* @covers \Meritoo\Common\Exception\File\EmptyFilePathException
*/
class EmptyFilePathExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFilePathException::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testConstructorMessage()
{
$exception = EmptyFilePathException::create();
static::assertSame('Path of the file is empty. Did you provide path of proper file?', $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFilePathException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -20,13 +20,28 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\File\NotExistingFileException
* @covers \Meritoo\Common\Exception\File\NotExistingFileException
*/
class NotExistingFileExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
/**
* Provides path of not existing file and expected exception's message
*
* @return Generator
*/
public function providePathOfFile()
{
static::assertConstructorVisibilityAndArguments(NotExistingFileException::class, OopVisibilityType::IS_PUBLIC, 3);
$template = 'File with path \'%s\' does not exist (or is not readable). Did you provide path of proper file?';
yield [
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield [
'images/show/car.jpg',
sprintf($template, 'images/show/car.jpg'),
];
}
/**
@@ -41,23 +56,8 @@ class NotExistingFileExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides path of not existing file and expected exception's message
*
* @return Generator
*/
public function providePathOfFile()
public function testConstructorVisibilityAndArguments()
{
$template = 'File with path \'%s\' does not exist (or is not readable). Did you provide path of proper file?';
yield[
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield[
'images/show/car.jpg',
sprintf($template, 'images/show/car.jpg'),
];
static::assertConstructorVisibilityAndArguments(NotExistingFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -20,13 +20,31 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Method\DisabledMethodException
* @covers \Meritoo\Common\Exception\Method\DisabledMethodException
*/
class DisabledMethodExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
/**
* Provides name of the disabled method, name of the alternative method and expected exception's message
*
* @return Generator
*/
public function provideMethodsNames()
{
static::assertConstructorVisibilityAndArguments(DisabledMethodException::class, OopVisibilityType::IS_PUBLIC, 3);
$templateShort = 'Method %s() cannot be called, because is disabled.';
$templateLong = $templateShort.' Use %s() instead.';
yield [
'FooBar::loremIpsum',
'',
sprintf($templateShort, 'FooBar::loremIpsum'),
];
yield [
'FooBar::loremIpsum',
'AnotherClass::alternativeMethod',
sprintf($templateLong, 'FooBar::loremIpsum', 'AnotherClass::alternativeMethod'),
];
}
/**
@@ -43,26 +61,8 @@ class DisabledMethodExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides name of the disabled method, name of the alternative method and expected exception's message
*
* @return Generator
*/
public function provideMethodsNames()
public function testConstructorVisibilityAndArguments()
{
$templateShort = 'Method %s() cannot be called, because is disabled.';
$templateLong = $templateShort . ' Use %s() instead.';
yield[
'FooBar::loremIpsum',
'',
sprintf($templateShort, 'FooBar::loremIpsum'),
];
yield[
'FooBar::loremIpsum',
'AnotherClass::alternativeMethod',
sprintf($templateLong, 'FooBar::loremIpsum', 'AnotherClass::alternativeMethod'),
];
static::assertConstructorVisibilityAndArguments(DisabledMethodException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -25,6 +25,33 @@ use stdClass;
*/
class CannotResolveClassNameExceptionTest extends BaseTestCase
{
/**
* Provides source of the class's / trait's name, information if message of this exception should be prepared for
* class and the expected exception's message
*
* @return Generator
*/
public function provideClassName(): Generator
{
yield [
'Not\Existing\Class',
true,
'Name of class from given \'string\' Not\Existing\Class cannot be resolved. Is there everything ok?',
];
yield [
'Not\Existing\Trait',
false,
'Name of trait from given \'string\' Not\Existing\Trait cannot be resolved. Is there everything ok?',
];
yield [
stdClass::class,
true,
'Name of class from given \'string\' stdClass cannot be resolved. Is there everything ok?',
];
}
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -34,14 +61,6 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase
);
}
public function testCreateUsingDefaults(): void
{
$exception = CannotResolveClassNameException::create(stdClass::class);
$expectedMessage = 'Name of class from given \'string\' stdClass cannot be resolved. Is there everything ok?';
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* @param string $source Source of name of the class or trait
* @param bool $forClass (optional) If is set to true, message of this exception for class is prepared.
@@ -56,30 +75,11 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides source of the class's / trait's name, information if message of this exception should be prepared for
* class and the expected exception's message
*
* @return Generator
*/
public function provideClassName(): Generator
public function testCreateUsingDefaults(): void
{
yield[
'Not\Existing\Class',
true,
'Name of class from given \'string\' Not\Existing\Class cannot be resolved. Is there everything ok?',
];
$exception = CannotResolveClassNameException::create(stdClass::class);
$expectedMessage = 'Name of class from given \'string\' stdClass cannot be resolved. Is there everything ok?';
yield[
'Not\Existing\Trait',
false,
'Name of trait from given \'string\' Not\Existing\Trait cannot be resolved. Is there everything ok?',
];
yield[
stdClass::class,
true,
'Name of class from given \'string\' stdClass cannot be resolved. Is there everything ok?',
];
static::assertSame($expectedMessage, $exception->getMessage());
}
}

View File

@@ -25,6 +25,23 @@ use Meritoo\Common\Utilities\Arrays;
*/
class ClassWithoutConstructorExceptionTest extends BaseTestCase
{
public function provideClassName(): Generator
{
$template = 'Oops, class \'%s\' hasn\'t constructor. Did you use proper class?';
yield [
'An empty name of class',
'',
sprintf($template, ''),
];
yield [
'The Arrays class',
Arrays::class,
sprintf($template, Arrays::class),
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -46,21 +63,4 @@ class ClassWithoutConstructorExceptionTest extends BaseTestCase
$exception = ClassWithoutConstructorException::create($className);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideClassName(): Generator
{
$template = 'Oops, class \'%s\' hasn\'t constructor. Did you use proper class?';
yield[
'An empty name of class',
'',
sprintf($template, ''),
];
yield[
'The Arrays class',
Arrays::class,
sprintf($template, Arrays::class),
];
}
}

View File

@@ -12,6 +12,7 @@ use Generator;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/**
* Test case of an exception used while given class has no child classes
@@ -24,6 +25,30 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class MissingChildClassesExceptionTest extends BaseTestCase
{
/**
* Provides name of class that hasn't child classes, but it should, and expected exception's message
*
* @return Generator
*/
public function provideParentClass(): ?Generator
{
$template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract'
.' class), but the child classes are missing. Did you forget to extend this class?';
yield [
MissingChildClassesException::class,
sprintf($template, MissingChildClassesException::class),
];
yield [
[
new stdClass(),
new stdClass(),
],
sprintf($template, stdClass::class),
];
}
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -45,28 +70,4 @@ class MissingChildClassesExceptionTest extends BaseTestCase
$exception = MissingChildClassesException::create($parentClass);
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides name of class that hasn't child classes, but it should, and expected exception's message
*
* @return Generator
*/
public function provideParentClass(): ?Generator
{
$template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract'
. ' class), but the child classes are missing. Did you forget to extend this class?';
yield[
MissingChildClassesException::class,
sprintf($template, MissingChildClassesException::class),
];
yield[
[
new \stdClass(),
new \stdClass(),
],
sprintf($template, \stdClass::class),
];
}
}

View File

@@ -8,9 +8,11 @@
namespace Meritoo\Test\Common\Exception\Reflection;
use Generator;
use Meritoo\Common\Exception\Reflection\NotExistingPropertyException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/**
* Class NotExistingPropertyExceptionTest
@@ -23,6 +25,39 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class NotExistingPropertyExceptionTest extends BaseTestCase
{
public function provideObjectPropertyAndMessage(): ?Generator
{
$template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?';
yield [
'An empty string as name of property',
new stdClass(),
'',
sprintf($template, '', get_class(new stdClass())),
];
yield [
'Null as name of property',
new stdClass(),
null,
sprintf($template, '', get_class(new stdClass())),
];
yield [
'String with spaces as name of property',
new stdClass(),
'This is test',
sprintf($template, 'This is test', get_class(new stdClass())),
];
yield [
'String without spaces as name of property',
new stdClass(),
'ThisIsTest',
sprintf($template, 'ThisIsTest', get_class(new stdClass())),
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -45,37 +80,4 @@ class NotExistingPropertyExceptionTest extends BaseTestCase
$exception = NotExistingPropertyException::create($object, $property);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideObjectPropertyAndMessage(): ?\Generator
{
$template = 'Property \'%s\' does not exist in instance of class \'%s\'. Did you use proper name of property?';
yield[
'An empty string as name of property',
new \stdClass(),
'',
sprintf($template, '', get_class(new \stdClass())),
];
yield[
'Null as name of property',
new \stdClass(),
null,
sprintf($template, '', get_class(new \stdClass())),
];
yield[
'String with spaces as name of property',
new \stdClass(),
'This is test',
sprintf($template, 'This is test', get_class(new \stdClass())),
];
yield[
'String without spaces as name of property',
new \stdClass(),
'ThisIsTest',
sprintf($template, 'ThisIsTest', get_class(new \stdClass())),
];
}
}

View File

@@ -12,6 +12,7 @@ use Generator;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/**
* Test case of an exception used while given class has more than one child class
@@ -24,6 +25,38 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class TooManyChildClassesExceptionTest extends BaseTestCase
{
/**
* Provides name of class that has more than one child class, but it shouldn't, child classes, and expected
* exception's message
*
* @return Generator
*/
public function provideParentAndChildClasses(): ?Generator
{
$template = "The '%s' class requires one child class at most who will extend her, but more than one child"
." class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";
yield [
BaseTestCase::class,
[
stdClass::class,
OopVisibilityType::class,
],
sprintf($template, BaseTestCase::class, implode("\n- ", [
stdClass::class,
OopVisibilityType::class,
]), BaseTestCase::class),
];
yield [
TooManyChildClassesException::class,
[
stdClass::class,
],
sprintf($template, TooManyChildClassesException::class, implode("\n- ", [stdClass::class]), TooManyChildClassesException::class),
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -46,36 +79,4 @@ class TooManyChildClassesExceptionTest extends BaseTestCase
$exception = TooManyChildClassesException::create($parentClass, $childClasses);
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides name of class that has more than one child class, but it shouldn't, child classes, and expected
* exception's message
*
* @return Generator
*/
public function provideParentAndChildClasses(): ?Generator
{
$template = "The '%s' class requires one child class at most who will extend her, but more than one child"
. " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";
yield[
BaseTestCase::class,
[
\stdClass::class,
OopVisibilityType::class,
],
sprintf($template, BaseTestCase::class, implode("\n- ", [
\stdClass::class,
OopVisibilityType::class,
]), BaseTestCase::class),
];
yield[
TooManyChildClassesException::class,
[
\stdClass::class,
],
sprintf($template, TooManyChildClassesException::class, implode("\n- ", [\stdClass::class]), TooManyChildClassesException::class),
];
}
}

View File

@@ -20,13 +20,28 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException
* @covers \Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException
*/
class IncorrectColorHexLengthExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
/**
* Provides incorrect hexadecimal value of color and expected exception's message
*
* @return Generator
*/
public function provideColor()
{
static::assertConstructorVisibilityAndArguments(IncorrectColorHexLengthException::class, OopVisibilityType::IS_PUBLIC, 3);
$template = 'Length of hexadecimal value of color \'%s\' is incorrect. It\'s %d, but it should be 3 or 6. Is there everything ok?';
yield [
'',
sprintf($template, '', strlen('')),
];
yield [
'aa-bb-cc',
sprintf($template, 'aa-bb-cc', strlen('aa-bb-cc')),
];
}
/**
@@ -41,23 +56,8 @@ class IncorrectColorHexLengthExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides incorrect hexadecimal value of color and expected exception's message
*
* @return Generator
*/
public function provideColor()
public function testConstructorVisibilityAndArguments()
{
$template = 'Length of hexadecimal value of color \'%s\' is incorrect. It\'s %d, but it should be 3 or 6. Is there everything ok?';
yield[
'',
sprintf($template, '', strlen('')),
];
yield[
'aa-bb-cc',
sprintf($template, 'aa-bb-cc', strlen('aa-bb-cc')),
];
static::assertConstructorVisibilityAndArguments(IncorrectColorHexLengthException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -20,13 +20,28 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\InvalidColorHexValueException
* @covers \Meritoo\Common\Exception\Regex\InvalidColorHexValueException
*/
class InvalidColorHexValueExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
/**
* Provides invalid hexadecimal value of color and expected exception's message
*
* @return Generator
*/
public function provideColor()
{
static::assertConstructorVisibilityAndArguments(InvalidColorHexValueException::class, OopVisibilityType::IS_PUBLIC, 3);
$template = 'Hexadecimal value of color \'%s\' is invalid. Is there everything ok?';
yield [
'',
sprintf($template, ''),
];
yield [
'aa-bb-cc',
sprintf($template, 'aa-bb-cc'),
];
}
/**
@@ -41,23 +56,8 @@ class InvalidColorHexValueExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides invalid hexadecimal value of color and expected exception's message
*
* @return Generator
*/
public function provideColor()
public function testConstructorVisibilityAndArguments()
{
$template = 'Hexadecimal value of color \'%s\' is invalid. Is there everything ok?';
yield[
'',
sprintf($template, ''),
];
yield[
'aa-bb-cc',
sprintf($template, 'aa-bb-cc'),
];
static::assertConstructorVisibilityAndArguments(InvalidColorHexValueException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -20,13 +20,33 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\InvalidHtmlAttributesException
* @covers \Meritoo\Common\Exception\Regex\InvalidHtmlAttributesException
*/
class InvalidHtmlAttributesExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
/**
* Provides html attributes
*
* @return Generator
*/
public function provideHtmlAttributes()
{
static::assertConstructorVisibilityAndArguments(InvalidHtmlAttributesException::class, OopVisibilityType::IS_PUBLIC, 3);
$template = 'HTML attributes \'%s\' are invalid. Is there everything ok?';
yield [
'abc = def',
sprintf($template, 'abc = def'),
];
yield [
'abc = def ghi = jkl',
sprintf($template, 'abc = def ghi = jkl'),
];
yield [
'abc=def ghi=jkl',
sprintf($template, 'abc=def ghi=jkl'),
];
}
/**
@@ -41,28 +61,8 @@ class InvalidHtmlAttributesExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides html attributes
*
* @return Generator
*/
public function provideHtmlAttributes()
public function testConstructorVisibilityAndArguments()
{
$template = 'HTML attributes \'%s\' are invalid. Is there everything ok?';
yield[
'abc = def',
sprintf($template, 'abc = def'),
];
yield[
'abc = def ghi = jkl',
sprintf($template, 'abc = def ghi = jkl'),
];
yield[
'abc=def ghi=jkl',
sprintf($template, 'abc=def ghi=jkl'),
];
static::assertConstructorVisibilityAndArguments(InvalidHtmlAttributesException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -20,13 +20,28 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\Regex\InvalidUrlException
* @covers \Meritoo\Common\Exception\Regex\InvalidUrlException
*/
class InvalidUrlExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
/**
* Provides invalid url and expected exception's message
*
* @return Generator
*/
public function provideUrl()
{
static::assertConstructorVisibilityAndArguments(InvalidUrlException::class, OopVisibilityType::IS_PUBLIC, 3);
$template = 'Url \'%s\' is invalid. Is there everything ok?';
yield [
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield [
'http:/images\show\car.jpg',
sprintf($template, 'http:/images\show\car.jpg'),
];
}
/**
@@ -41,23 +56,8 @@ class InvalidUrlExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides invalid url and expected exception's message
*
* @return Generator
*/
public function provideUrl()
public function testConstructorVisibilityAndArguments()
{
$template = 'Url \'%s\' is invalid. Is there everything ok?';
yield[
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield[
'http:/images\show\car.jpg',
sprintf($template, 'http:/images\show\car.jpg'),
];
static::assertConstructorVisibilityAndArguments(InvalidUrlException::class, OopVisibilityType::IS_PUBLIC, 3);
}
}

View File

@@ -25,13 +25,27 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments(): void
/**
* Provides path of the empty file and expected exception's message
*
* @return Generator
*/
public function provideUnknownType(): Generator
{
static::assertConstructorVisibilityAndArguments(
UnknownOopVisibilityTypeException::class,
OopVisibilityType::IS_PUBLIC,
3
);
$allTypes = (new OopVisibilityType())->getAll();
$template = 'The \'%s\' type of OOP-related visibility is unknown. Probably doesn\'t exist or there is a typo.'
.' You should use one of these types: %s.';
yield [
'',
sprintf($template, '', implode(', ', $allTypes)),
];
yield [
123,
sprintf($template, 123, implode(', ', $allTypes)),
];
}
/**
@@ -46,26 +60,12 @@ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
static::assertSame($expectedMessage, $exception->getMessage());
}
/**
* Provides path of the empty file and expected exception's message
*
* @return Generator
*/
public function provideUnknownType(): Generator
public function testConstructorVisibilityAndArguments(): void
{
$allTypes = (new OopVisibilityType())->getAll();
$template = 'The \'%s\' type of OOP-related visibility is unknown. Probably doesn\'t exist or there is a typo.'
. ' You should use one of these types: %s.';
yield[
'',
sprintf($template, '', implode(', ', $allTypes)),
];
yield[
123,
sprintf($template, 123, implode(', ', $allTypes)),
];
static::assertConstructorVisibilityAndArguments(
UnknownOopVisibilityTypeException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
}

View File

@@ -19,10 +19,33 @@ use Meritoo\Common\Type\OopVisibilityType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Exception\ValueObject\InvalidSizeDimensionsException
* @covers \Meritoo\Common\Exception\ValueObject\InvalidSizeDimensionsException
*/
class InvalidSizeDimensionsExceptionTest extends BaseTestCase
{
public function provideWidthAndHeight()
{
$template = 'Dimensions of size should be positive, but they are not: %d, %d. Is there everything ok?';
yield [
0,
0,
sprintf($template, 0, 0),
];
yield [
-1,
-1,
sprintf($template, -1, -1),
];
yield [
200,
100,
sprintf($template, 200, 100),
];
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(
@@ -44,27 +67,4 @@ class InvalidSizeDimensionsExceptionTest extends BaseTestCase
$exception = InvalidSizeDimensionsException::create($width, $height);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function provideWidthAndHeight()
{
$template = 'Dimensions of size should be positive, but they are not: %d, %d. Is there everything ok?';
yield[
0,
0,
sprintf($template, 0, 0),
];
yield[
-1,
-1,
sprintf($template, -1, -1),
];
yield[
200,
100,
sprintf($template, 200, 100),
];
}
}

View File

@@ -24,6 +24,29 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class InvalidContentExceptionTest extends BaseTestCase
{
public function provideContent(): ?Generator
{
$template = 'Content of template \'%s\' is invalid. Did you use string with 1 placeholder at least?';
yield [
'An empty string',
'',
sprintf($template, ''),
];
yield [
'Simple string',
'Lorem ipsum',
sprintf($template, 'Lorem ipsum'),
];
yield [
'One sentence',
'Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.',
sprintf($template, 'Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.'),
];
}
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -45,27 +68,4 @@ class InvalidContentExceptionTest extends BaseTestCase
$exception = InvalidContentException::create($content);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideContent(): ?Generator
{
$template = 'Content of template \'%s\' is invalid. Did you use string with 1 placeholder at least?';
yield[
'An empty string',
'',
sprintf($template, ''),
];
yield[
'Simple string',
'Lorem ipsum',
sprintf($template, 'Lorem ipsum'),
];
yield[
'One sentence',
'Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.',
sprintf($template, 'Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh.'),
];
}
}

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Exception\ValueObject\Template;
use Generator;
use Meritoo\Common\Exception\ValueObject\Template\MissingPlaceholdersInValuesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
@@ -23,6 +24,39 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class MissingPlaceholdersInValuesExceptionTest extends BaseTestCase
{
public function provideContentAndMissingPlaceholders(): ?Generator
{
$template = 'Cannot fill template \'%s\', because of missing values for placeholder(s): %s. Did you provide all'
.' required values?';
yield [
'Missing 2nd placeholder',
'%test1% - %test2%',
[
'test2',
],
sprintf(
$template,
'%test1% - %test2%',
'test2'
),
];
yield [
'Missing 2nd and 3rd placeholder',
'%test1% / %test2% / %test3%',
[
'test2',
'test3',
],
sprintf(
$template,
'%test1% / %test2% / %test3%',
'test2, test3'
),
];
}
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -49,37 +83,4 @@ class MissingPlaceholdersInValuesExceptionTest extends BaseTestCase
$exception = MissingPlaceholdersInValuesException::create($content, $missingPlaceholders);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideContentAndMissingPlaceholders(): ?\Generator
{
$template = 'Cannot fill template \'%s\', because of missing values for placeholder(s): %s. Did you provide all'
. ' required values?';
yield[
'Missing 2nd placeholder',
'%test1% - %test2%',
[
'test2',
],
sprintf(
$template,
'%test1% - %test2%',
'test2'
),
];
yield[
'Missing 2nd and 3rd placeholder',
'%test1% / %test2% / %test3%',
[
'test2',
'test3',
],
sprintf(
$template,
'%test1% / %test2% / %test3%',
'test2, test3'
),
];
}
}

View File

@@ -24,6 +24,29 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class TemplateNotFoundExceptionTest extends BaseTestCase
{
public function provideIndexAndException(): ?Generator
{
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
yield [
'An empty string',
'',
new TemplateNotFoundException(sprintf($template, '')),
];
yield [
'Non-empty string',
'test',
new TemplateNotFoundException(sprintf($template, 'test')),
];
yield [
'Integer',
'2',
new TemplateNotFoundException(sprintf($template, 2)),
];
}
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
@@ -45,27 +68,4 @@ class TemplateNotFoundExceptionTest extends BaseTestCase
$created = TemplateNotFoundException::create($index);
static::assertEquals($expected, $created, $description);
}
public function provideIndexAndException(): ?Generator
{
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
yield[
'An empty string',
'',
new TemplateNotFoundException(sprintf($template, '')),
];
yield[
'Non-empty string',
'test',
new TemplateNotFoundException(sprintf($template, 'test')),
];
yield[
'Integer',
'2',
new TemplateNotFoundException(sprintf($template, 2)),
];
}
}

View File

@@ -21,28 +21,59 @@ use Meritoo\Common\Utilities\GeneratorUtility;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Test\Base\BaseTestCase
* @covers \Meritoo\Common\Test\Base\BaseTestCase
*/
class BaseTestCaseTest extends BaseTestCase
{
/**
* Provides name of file and path of directory containing the file
*
* @return Generator
*/
public function provideFileNameAndDirectoryPath()
{
yield [
'abc.jpg',
'',
];
yield [
'abc.def.jpg',
'',
];
yield [
'abc.jpg',
'def',
];
yield [
'abc.def.jpg',
'def',
];
}
public function testConstructor()
{
static::assertConstructorVisibilityAndArguments(BaseTestCase::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testProvideEmptyValue()
/**
* @param string $fileName Name of file
* @param string $directoryPath Path of directory containing the file
*
* @dataProvider provideFileNameAndDirectoryPath
*/
public function testGetFilePathForTesting($fileName, $directoryPath)
{
$elements = [
[''],
[' '],
[null],
[0],
[false],
[[]],
];
$path = (new SimpleTestCase())->getFilePathForTesting($fileName, $directoryPath);
$generator = (new SimpleTestCase())->provideEmptyValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
if (!empty($directoryPath)) {
$directoryPath .= '/';
}
$expectedContains = sprintf('/data/tests/%s%s', $directoryPath, $fileName);
static::assertStringContainsString($expectedContains, $path);
}
public function testProvideBooleanValue()
@@ -109,6 +140,21 @@ class BaseTestCaseTest extends BaseTestCase
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
public function testProvideEmptyValue()
{
$elements = [
[''],
[' '],
[null],
[0],
[false],
[[]],
];
$generator = (new SimpleTestCase())->provideEmptyValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
public function testProvideNotExistingFilePath()
{
$elements = [
@@ -120,52 +166,6 @@ class BaseTestCaseTest extends BaseTestCase
$generator = (new SimpleTestCase())->provideNotExistingFilePath();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
/**
* @param string $fileName Name of file
* @param string $directoryPath Path of directory containing the file
*
* @dataProvider provideFileNameAndDirectoryPath
*/
public function testGetFilePathForTesting($fileName, $directoryPath)
{
$path = (new SimpleTestCase())->getFilePathForTesting($fileName, $directoryPath);
if (!empty($directoryPath)) {
$directoryPath .= '/';
}
$expectedContains = sprintf('/data/tests/%s%s', $directoryPath, $fileName);
static::assertStringContainsString($expectedContains, $path);
}
/**
* Provides name of file and path of directory containing the file
*
* @return Generator
*/
public function provideFileNameAndDirectoryPath()
{
yield[
'abc.jpg',
'',
];
yield[
'abc.def.jpg',
'',
];
yield[
'abc.jpg',
'def',
];
yield[
'abc.def.jpg',
'def',
];
}
}
/**

View File

@@ -33,6 +33,17 @@ class BaseTestCaseTraitTest extends BaseTestCase
{
use BaseTestCaseTrait;
public function testAssertConstructorVisibilityAndArgumentsUsingClassWithoutConstructor(): void
{
$this->expectException(ClassWithoutConstructorException::class);
static::assertConstructorVisibilityAndArguments(SimpleTestCase::class, OopVisibilityType::IS_PUBLIC);
}
public function testAssertHasNoConstructor(): void
{
static::assertHasNoConstructor(SimpleTestCase::class);
}
public function testAssertMethodVisibility(): void
{
$method = new ReflectionMethod(SimpleTestCase::class, 'assertMethodVisibility');
@@ -53,54 +64,6 @@ class BaseTestCaseTraitTest extends BaseTestCase
static::assertMethodVisibility($method, OopVisibilityType::IS_PRIVATE);
}
public function testAssertConstructorVisibilityAndArgumentsUsingClassWithoutConstructor(): void
{
$this->expectException(ClassWithoutConstructorException::class);
static::assertConstructorVisibilityAndArguments(SimpleTestCase::class, OopVisibilityType::IS_PUBLIC);
}
public function testAssertHasNoConstructor(): void
{
static::assertHasNoConstructor(SimpleTestCase::class);
}
public function testProvideEmptyValue(): void
{
$testCase = new SimpleTestCase();
$values = $testCase->provideEmptyValue();
$expected = [
[''],
[' '],
[null],
[0],
[false],
[[]],
];
foreach ($values as $index => $value) {
static::assertSame($expected[$index], $value);
}
}
public function testProvideEmptyScalarValue(): void
{
$testCase = new SimpleTestCase();
$values = $testCase->provideEmptyScalarValue();
$expected = [
[''],
[' '],
[null],
[0],
[false],
];
foreach ($values as $index => $value) {
static::assertSame($expected[$index], $value);
}
}
public function testProvideBooleanValue(): void
{
$testCase = new SimpleTestCase();
@@ -164,19 +127,40 @@ class BaseTestCaseTraitTest extends BaseTestCase
}
}
public function testProvideNotExistingFilePath(): void
public function testProvideEmptyScalarValue(): void
{
$testCase = new SimpleTestCase();
$paths = $testCase->provideNotExistingFilePath();
$values = $testCase->provideEmptyScalarValue();
$expected = [
['lets-test.doc'],
['lorem/ipsum.jpg'],
['surprise/me/one/more/time.txt'],
[''],
[' '],
[null],
[0],
[false],
];
foreach ($paths as $index => $path) {
static::assertSame($expected[$index], $path);
foreach ($values as $index => $value) {
static::assertSame($expected[$index], $value);
}
}
public function testProvideEmptyValue(): void
{
$testCase = new SimpleTestCase();
$values = $testCase->provideEmptyValue();
$expected = [
[''],
[' '],
[null],
[0],
[false],
[[]],
];
foreach ($values as $index => $value) {
static::assertSame($expected[$index], $value);
}
}
@@ -195,4 +179,20 @@ class BaseTestCaseTraitTest extends BaseTestCase
static::assertEquals($expected[$index], $value);
}
}
public function testProvideNotExistingFilePath(): void
{
$testCase = new SimpleTestCase();
$paths = $testCase->provideNotExistingFilePath();
$expected = [
['lets-test.doc'],
['lorem/ipsum.jpg'],
['surprise/me/one/more/time.txt'],
];
foreach ($paths as $index => $path) {
static::assertSame($expected[$index], $path);
}
}
}

View File

@@ -23,6 +23,138 @@ use Meritoo\Common\Type\Base\BaseType;
*/
class BaseTypeTest extends BaseTestCase
{
/**
* Provides type of something for testing the getAll() method
*
* @return Generator
*/
public function provideType(): ?Generator
{
yield [
new TestEmptyType(),
[],
];
yield [
new TestType(),
[
'TEST_1' => TestType::TEST_1,
'TEST_2' => TestType::TEST_2,
],
];
}
/**
* Provides type of something for testing the isCorrectType() method
*
* @return Generator
*/
public function provideTypeToVerifyUsingTestEmptyType(): ?Generator
{
yield [
null,
false,
];
yield [
'null',
false,
];
yield [
'false',
false,
];
yield [
'true',
false,
];
yield [
'',
false,
];
yield [
'0',
false,
];
yield [
'1',
false,
];
yield [
'lorem',
false,
];
}
/**
* Provides type of something for testing the isCorrectType() method
*
* @return Generator
*/
public function provideTypeToVerifyUsingTestType(): ?Generator
{
yield [
null,
false,
];
yield [
'null',
false,
];
yield [
'false',
false,
];
yield [
'true',
false,
];
yield [
'',
false,
];
yield [
'0',
false,
];
yield [
'1',
false,
];
yield [
'lorem',
false,
];
yield [
'test',
false,
];
yield [
'test_1',
true,
];
yield [
'test_2',
true,
];
}
public function testConstructor(): void
{
static::assertHasNoConstructor(BaseType::class);
@@ -61,138 +193,6 @@ class BaseTypeTest extends BaseTestCase
{
self::assertEquals($isCorrect, TestType::isCorrectType($toVerifyType));
}
/**
* Provides type of something for testing the getAll() method
*
* @return Generator
*/
public function provideType(): ?Generator
{
yield[
new TestEmptyType(),
[],
];
yield[
new TestType(),
[
'TEST_1' => TestType::TEST_1,
'TEST_2' => TestType::TEST_2,
],
];
}
/**
* Provides type of something for testing the isCorrectType() method
*
* @return Generator
*/
public function provideTypeToVerifyUsingTestEmptyType(): ?Generator
{
yield[
null,
false,
];
yield[
'null',
false,
];
yield[
'false',
false,
];
yield[
'true',
false,
];
yield[
'',
false,
];
yield[
'0',
false,
];
yield[
'1',
false,
];
yield[
'lorem',
false,
];
}
/**
* Provides type of something for testing the isCorrectType() method
*
* @return Generator
*/
public function provideTypeToVerifyUsingTestType(): ?Generator
{
yield[
null,
false,
];
yield[
'null',
false,
];
yield[
'false',
false,
];
yield[
'true',
false,
];
yield[
'',
false,
];
yield[
'0',
false,
];
yield[
'1',
false,
];
yield[
'lorem',
false,
];
yield[
'test',
false,
];
yield[
'test_1',
true,
];
yield[
'test_2',
true,
];
}
}
/**

View File

@@ -20,7 +20,7 @@ use Meritoo\Common\Type\DatePartType;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Type\DatePartType
* @covers \Meritoo\Common\Type\DatePartType
*/
class DatePartTypeTest extends BaseTypeTestCase
{
@@ -29,52 +29,52 @@ class DatePartTypeTest extends BaseTypeTestCase
*/
public function provideTypeToVerify(): Generator
{
yield[
yield [
DatePartType::isCorrectType(''),
false,
];
yield[
yield [
DatePartType::isCorrectType(null),
false,
];
yield[
yield [
DatePartType::isCorrectType('0'),
false,
];
yield[
yield [
DatePartType::isCorrectType('1'),
false,
];
yield[
yield [
DatePartType::isCorrectType('day'),
true,
];
yield[
yield [
DatePartType::isCorrectType('hour'),
true,
];
yield[
yield [
DatePartType::isCorrectType('minute'),
true,
];
yield[
yield [
DatePartType::isCorrectType('month'),
true,
];
yield[
yield [
DatePartType::isCorrectType('second'),
true,
];
yield[
yield [
DatePartType::isCorrectType('year'),
true,
];
@@ -86,12 +86,12 @@ class DatePartTypeTest extends BaseTypeTestCase
protected function getAllExpectedTypes(): array
{
return [
'DAY' => 'day',
'HOUR' => 'hour',
'DAY' => 'day',
'HOUR' => 'hour',
'MINUTE' => 'minute',
'MONTH' => 'month',
'MONTH' => 'month',
'SECOND' => 'second',
'YEAR' => 'year',
'YEAR' => 'year',
];
}

View File

@@ -26,13 +26,222 @@ use Meritoo\Common\Type\OopVisibilityType;
*/
class DatePeriodTest extends BaseTypeTestCase
{
public function testConstructorVisibilityAndArguments(): void
/**
* Provides the start and end date of date period
*
* @return Generator
*/
public function provideDatePeriod(): Generator
{
static::assertConstructorVisibilityAndArguments(
DatePeriod::class,
OopVisibilityType::IS_PUBLIC,
2
);
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield [
null,
null,
];
yield [
$startDate,
$startDate,
null,
];
yield [
null,
null,
$endDate,
];
yield [
$startDate,
$endDate,
];
}
/**
* Provides period and format of date to verify
*
* @return Generator
*/
public function provideDatePeriodAndDateFormat(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
// For start date
yield [
new DatePeriod($startDate, $endDate),
'Y',
true,
'2001',
];
yield [
new DatePeriod($startDate, $endDate),
'D',
true,
'Mon',
];
yield [
new DatePeriod($startDate, $endDate),
'Y-m-d',
true,
'2001-01-01',
];
yield [
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
true,
'2001-01-01 00:00',
];
// For end date
yield [
new DatePeriod($startDate, $endDate),
'Y',
false,
'2002',
];
yield [
new DatePeriod($startDate, $endDate),
'D',
false,
'Sat',
];
yield [
new DatePeriod($startDate, $endDate),
'Y-m-d',
false,
'2002-02-02',
];
yield [
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
false,
'2002-02-02 00:00',
];
}
/**
* Provides period and format of date to verify using the start date
*
* @return Generator
*/
public function provideDatePeriodAndDateFormatUsingStartDateOnly(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield [
new DatePeriod($startDate, $endDate),
'Y',
'2001',
];
yield [
new DatePeriod($startDate, $endDate),
'D',
'Mon',
];
yield [
new DatePeriod($startDate, $endDate),
'Y-m-d',
'2001-01-01',
];
yield [
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
'2001-01-01 00:00',
];
}
/**
* Provides period and incorrect format of date to verify
*
* @return Generator
*/
public function provideDatePeriodAndIncorrectDateFormat(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield [
new DatePeriod($startDate, $endDate),
'',
];
yield [
new DatePeriod($startDate, $endDate),
false,
];
}
public function provideDatePeriodAndUnknownDate(): ?Generator
{
$date = new DateTime('2001-01-01');
yield [
new DatePeriod(),
'Y-m-d',
false,
];
yield [
new DatePeriod(),
'Y-m-d',
true,
];
yield [
new DatePeriod($date),
'Y-m-d',
false,
];
yield [
new DatePeriod(null, $date),
'Y-m-d',
true,
];
}
/**
* {@inheritdoc}
*/
public function provideTypeToVerify(): Generator
{
yield [
DatePeriod::isCorrectType(''),
false,
];
yield [
DatePeriod::isCorrectType('-1'),
false,
];
yield [
DatePeriod::isCorrectType('4'),
true,
];
yield [
DatePeriod::isCorrectType('3'),
true,
];
yield [
DatePeriod::isCorrectType('8'),
true,
];
}
/**
@@ -49,6 +258,63 @@ class DatePeriodTest extends BaseTypeTestCase
self::assertEquals($endDate, $period->getEndDate());
}
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
DatePeriod::class,
OopVisibilityType::IS_PUBLIC,
2
);
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param bool $startDate If is set to true, start date is formatted. Otherwise - end date.
* @param string $expected Expected, formatted date
*
* @dataProvider provideDatePeriodAndDateFormat
*/
public function testGetFormattedDate(DatePeriod $period, $format, $startDate, $expected): void
{
self::assertEquals($expected, $period->getFormattedDate($format, $startDate));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
*
* @dataProvider provideDatePeriodAndIncorrectDateFormat
*/
public function testGetFormattedDateUsingIncorrectDateFormat(DatePeriod $period, $format): void
{
self::assertEquals('', $period->getFormattedDate($format));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param string $expected Expected, formatted date
*
* @dataProvider provideDatePeriodAndDateFormatUsingStartDateOnly
*/
public function testGetFormattedDateUsingStartDateOnly(DatePeriod $period, $format, $expected): void
{
self::assertEquals($expected, $period->getFormattedDate($format));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param bool $startDate If is set to true, start date is formatted. Otherwise - end date.
*
* @dataProvider provideDatePeriodAndUnknownDate
*/
public function testGetFormattedDateUsingUnknownDate(DatePeriod $period, $format, $startDate): void
{
self::assertEquals('', $period->getFormattedDate($format, $startDate));
}
/**
* @param DateTime $startDate (optional) Start date of period
* @param DateTime $endDate (optional) End date of period
@@ -66,272 +332,6 @@ class DatePeriodTest extends BaseTypeTestCase
self::assertEquals($endDate, $period->getEndDate());
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
*
* @dataProvider provideDatePeriodAndIncorrectDateFormat
*/
public function testGetFormattedDateUsingIncorrectDateFormat(DatePeriod $period, $format): void
{
self::assertEquals('', $period->getFormattedDate($format));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param bool $startDate If is set to true, start date is formatted. Otherwise - end date.
*
* @dataProvider provideDatePeriodAndUnknownDate
*/
public function testGetFormattedDateUsingUnknownDate(DatePeriod $period, $format, $startDate): void
{
self::assertEquals('', $period->getFormattedDate($format, $startDate));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param string $expected Expected, formatted date
*
* @dataProvider provideDatePeriodAndDateFormatUsingStartDateOnly
*/
public function testGetFormattedDateUsingStartDateOnly(DatePeriod $period, $format, $expected): void
{
self::assertEquals($expected, $period->getFormattedDate($format));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param bool $startDate If is set to true, start date is formatted. Otherwise - end date.
* @param string $expected Expected, formatted date
*
* @dataProvider provideDatePeriodAndDateFormat
*/
public function testGetFormattedDate(DatePeriod $period, $format, $startDate, $expected): void
{
self::assertEquals($expected, $period->getFormattedDate($format, $startDate));
}
/**
* Provides the start and end date of date period
*
* @return Generator
*/
public function provideDatePeriod(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield[
null,
null,
];
yield[
$startDate,
$startDate,
null,
];
yield[
null,
null,
$endDate,
];
yield[
$startDate,
$endDate,
];
}
/**
* Provides period and incorrect format of date to verify
*
* @return Generator
*/
public function provideDatePeriodAndIncorrectDateFormat(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield[
new DatePeriod($startDate, $endDate),
'',
];
yield[
new DatePeriod($startDate, $endDate),
false,
];
}
public function provideDatePeriodAndUnknownDate(): ?Generator
{
$date = new DateTime('2001-01-01');
yield[
new DatePeriod(),
'Y-m-d',
false,
];
yield[
new DatePeriod(),
'Y-m-d',
true,
];
yield[
new DatePeriod($date),
'Y-m-d',
false,
];
yield[
new DatePeriod(null, $date),
'Y-m-d',
true,
];
}
/**
* Provides period and format of date to verify using the start date
*
* @return Generator
*/
public function provideDatePeriodAndDateFormatUsingStartDateOnly(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield[
new DatePeriod($startDate, $endDate),
'Y',
'2001',
];
yield[
new DatePeriod($startDate, $endDate),
'D',
'Mon',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d',
'2001-01-01',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
'2001-01-01 00:00',
];
}
/**
* Provides period and format of date to verify
*
* @return Generator
*/
public function provideDatePeriodAndDateFormat(): Generator
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
// For start date
yield[
new DatePeriod($startDate, $endDate),
'Y',
true,
'2001',
];
yield[
new DatePeriod($startDate, $endDate),
'D',
true,
'Mon',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d',
true,
'2001-01-01',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
true,
'2001-01-01 00:00',
];
// For end date
yield[
new DatePeriod($startDate, $endDate),
'Y',
false,
'2002',
];
yield[
new DatePeriod($startDate, $endDate),
'D',
false,
'Sat',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d',
false,
'2002-02-02',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
false,
'2002-02-02 00:00',
];
}
/**
* {@inheritdoc}
*/
public function provideTypeToVerify(): Generator
{
yield[
DatePeriod::isCorrectType(''),
false,
];
yield[
DatePeriod::isCorrectType('-1'),
false,
];
yield[
DatePeriod::isCorrectType('4'),
true,
];
yield[
DatePeriod::isCorrectType('3'),
true,
];
yield[
DatePeriod::isCorrectType('8'),
true,
];
}
/**
* Returns all expected types of the tested type
*
@@ -341,14 +341,14 @@ class DatePeriodTest extends BaseTypeTestCase
{
return [
'LAST_MONTH' => 4,
'LAST_WEEK' => 1,
'LAST_YEAR' => 7,
'LAST_WEEK' => 1,
'LAST_YEAR' => 7,
'NEXT_MONTH' => 6,
'NEXT_WEEK' => 3,
'NEXT_YEAR' => 9,
'NEXT_WEEK' => 3,
'NEXT_YEAR' => 9,
'THIS_MONTH' => 5,
'THIS_WEEK' => 2,
'THIS_YEAR' => 8,
'THIS_WEEK' => 2,
'THIS_YEAR' => 8,
];
}

View File

@@ -29,32 +29,32 @@ class OopVisibilityTypeTest extends BaseTypeTestCase
*/
public function provideTypeToVerify(): Generator
{
yield[
yield [
OopVisibilityType::isCorrectType(''),
false,
];
yield[
yield [
OopVisibilityType::isCorrectType(null),
false,
];
yield[
yield [
OopVisibilityType::isCorrectType('-1'),
false,
];
yield[
yield [
OopVisibilityType::isCorrectType('1'),
true,
];
yield[
yield [
OopVisibilityType::isCorrectType('2'),
true,
];
yield[
yield [
OopVisibilityType::isCorrectType('3'),
true,
];
@@ -66,9 +66,9 @@ class OopVisibilityTypeTest extends BaseTypeTestCase
protected function getAllExpectedTypes(): array
{
return [
'IS_PRIVATE' => 3,
'IS_PRIVATE' => 3,
'IS_PROTECTED' => 2,
'IS_PUBLIC' => 1,
'IS_PUBLIC' => 1,
];
}

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Utilities;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Bootstrap4CssSelector;
@@ -18,28 +19,145 @@ use Meritoo\Common\Utilities\Bootstrap4CssSelector;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Bootstrap4CssSelector
* @covers \Meritoo\Common\Utilities\Bootstrap4CssSelector
*/
class Bootstrap4CssSelectorTest extends BaseTestCase
{
/**
* Provides name of form and expected selector
*
* @return Generator
*/
public function provideFormNameAndSelector()
{
yield [
'test',
'form[name="test"] .form-group',
];
yield [
'test-123-test-456',
'form[name="test-123-test-456"] .form-group',
];
yield [
'test_something_098_different',
'form[name="test_something_098_different"] .form-group',
];
}
/**
* Provides name of form, name of field and expected selector
*
* @return Generator
*/
public function provideFormNameFieldNameAndSelector()
{
yield [
'test',
'test',
'form[name="test"] label[for="test"] .invalid-feedback .form-error-message',
];
yield [
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] label[for="great-000-field"] .invalid-feedback .form-error-message',
];
yield [
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] label[for="this-is-the-123789-field"] .invalid-feedback .form-error-message',
];
}
/**
* Provides name of form, index/position of the field-set and expected selector
*
* @return Generator
*/
public function provideFormNameFieldSetIndexAndSelector()
{
yield [
'test',
0,
'form[name="test"] fieldset:nth-of-type(0) legend.col-form-label .invalid-feedback .form-error-message',
];
yield [
'test-123-test-456',
1,
'form[name="test-123-test-456"] fieldset:nth-of-type(1) legend.col-form-label .invalid-feedback .form-error-message',
];
yield [
'test_something_098_different',
1245,
'form[name="test_something_098_different"] fieldset:nth-of-type(1245) legend.col-form-label .invalid-feedback .form-error-message',
];
}
public function testConstructor()
{
static::assertHasNoConstructor(Bootstrap4CssSelector::class);
}
public function testGetFieldErrorContainerSelector()
{
static::assertSame('.invalid-feedback .form-error-message', Bootstrap4CssSelector::getFieldErrorContainerSelector());
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldName Name of field (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldNameAndSelector
*/
public function testGetFieldErrorSelector($formName, $fieldName, $expected)
{
static::assertSame($expected, Bootstrap4CssSelector::getFieldErrorSelector($formName, $fieldName));
}
/**
* @param string $emptyValue Name of field (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldErrorSelectorUsingEmptyFieldName($emptyValue)
{
$formName = 'test';
static::assertSame('', Bootstrap4CssSelector::getFieldErrorSelector($formName, $emptyValue));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetRadioButtonErrorSelectorUsingEmptyFormName($emptyValue)
public function testGetFieldErrorSelectorUsingEmptyFormName($emptyValue)
{
$fieldSetIndex = 1;
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector($emptyValue, $fieldSetIndex));
$fieldName = 'test';
static::assertSame('', Bootstrap4CssSelector::getFieldErrorSelector($emptyValue, $fieldName));
}
public function testGetRadioButtonErrorSelectorUsingNegativeFieldSetIndex()
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameAndSelector
*/
public function testGetFieldGroupSelector($formName, $expected)
{
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector('test-test', -1));
static::assertSame($expected, Bootstrap4CssSelector::getFieldGroupSelector($formName));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldGroupSelectorUsingEmptyFormName($emptyValue)
{
static::assertSame('', Bootstrap4CssSelector::getFieldGroupSelector($emptyValue));
}
/**
@@ -58,131 +176,14 @@ class Bootstrap4CssSelectorTest extends BaseTestCase
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldErrorSelectorUsingEmptyFormName($emptyValue)
public function testGetRadioButtonErrorSelectorUsingEmptyFormName($emptyValue)
{
$fieldName = 'test';
static::assertSame('', Bootstrap4CssSelector::getFieldErrorSelector($emptyValue, $fieldName));
$fieldSetIndex = 1;
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector($emptyValue, $fieldSetIndex));
}
/**
* @param string $emptyValue Name of field (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldErrorSelectorUsingEmptyFieldName($emptyValue)
public function testGetRadioButtonErrorSelectorUsingNegativeFieldSetIndex()
{
$formName = 'test';
static::assertSame('', Bootstrap4CssSelector::getFieldErrorSelector($formName, $emptyValue));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldName Name of field (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldNameAndSelector
*/
public function testGetFieldErrorSelector($formName, $fieldName, $expected)
{
static::assertSame($expected, Bootstrap4CssSelector::getFieldErrorSelector($formName, $fieldName));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldGroupSelectorUsingEmptyFormName($emptyValue)
{
static::assertSame('', Bootstrap4CssSelector::getFieldGroupSelector($emptyValue));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameAndSelector
*/
public function testGetFieldGroupSelector($formName, $expected)
{
static::assertSame($expected, Bootstrap4CssSelector::getFieldGroupSelector($formName));
}
public function testGetFieldErrorContainerSelector()
{
static::assertSame('.invalid-feedback .form-error-message', Bootstrap4CssSelector::getFieldErrorContainerSelector());
}
/**
* Provides name of form, index/position of the field-set and expected selector
*
* @return \Generator
*/
public function provideFormNameFieldSetIndexAndSelector()
{
yield[
'test',
0,
'form[name="test"] fieldset:nth-of-type(0) legend.col-form-label .invalid-feedback .form-error-message',
];
yield[
'test-123-test-456',
1,
'form[name="test-123-test-456"] fieldset:nth-of-type(1) legend.col-form-label .invalid-feedback .form-error-message',
];
yield[
'test_something_098_different',
1245,
'form[name="test_something_098_different"] fieldset:nth-of-type(1245) legend.col-form-label .invalid-feedback .form-error-message',
];
}
/**
* Provides name of form, name of field and expected selector
*
* @return \Generator
*/
public function provideFormNameFieldNameAndSelector()
{
yield[
'test',
'test',
'form[name="test"] label[for="test"] .invalid-feedback .form-error-message',
];
yield[
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] label[for="great-000-field"] .invalid-feedback .form-error-message',
];
yield[
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] label[for="this-is-the-123789-field"] .invalid-feedback .form-error-message',
];
}
/**
* Provides name of form and expected selector
*
* @return \Generator
*/
public function provideFormNameAndSelector()
{
yield[
'test',
'form[name="test"] .form-group',
];
yield[
'test-123-test-456',
'form[name="test-123-test-456"] .form-group',
];
yield[
'test_something_098_different',
'form[name="test_something_098_different"] .form-group',
];
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector('test-test', -1));
}
}

View File

@@ -20,15 +20,174 @@ use Meritoo\Common\Utilities\Bundle;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Bundle
* @covers \Meritoo\Common\Utilities\Bundle
*/
class BundleTest extends BaseTestCase
{
/**
* Provides empty path of the view / template and/or name of bundle
*
* @return Generator
*/
public function provideEmptyViewPathAndBundle()
{
yield [
'',
'',
];
yield [
'test',
'',
];
yield [
'',
'test',
];
}
/**
* Provides full and short name of bundle
*
* @return Generator
*/
public function provideFullAndShortBundleName()
{
yield [
'MyExtraBundle',
'MyExtra',
];
yield [
'MySuperExtraGorgeousBundle',
'MySuperExtraGorgeous',
];
}
/**
* Provides incorrect name of bundle
*
* @return Generator
*/
public function provideIncorrectBundleName()
{
yield [
'myExtra',
];
yield [
'MyExtra',
];
yield [
'MySuperExtraGorgeous',
];
}
/**
* Provides path of the view / template and name of bundle
*
* @return Generator
*/
public function provideViewPathAndBundle()
{
yield [
'User',
'MyExtraBundle',
'@MyExtra/User.html.twig',
];
yield [
'User:Active',
'MyExtraBundle',
'@MyExtra/User/Active.html.twig',
];
yield [
'User:Active',
'MySuperExtraGorgeousBundle',
'@MySuperExtraGorgeous/User/Active.html.twig',
];
}
/**
* Provides path of the view / template, name of bundle and extension of the view / template
*
* @return Generator
*/
public function provideViewPathAndBundleAndExtension()
{
yield [
'User:Active',
'MyExtraBundle',
'',
null,
];
yield [
'User:Active',
'MyExtraBundle',
'js.twig',
'@MyExtra/User/Active.js.twig',
];
}
/**
* Provides path of the view / template and incorrect name of bundle
*
* @return Generator
*/
public function provideViewPathAndIncorrectBundleName()
{
yield [
'User:Active',
'myExtra',
];
yield [
'User:Active',
'MyExtra',
];
yield [
'User:Active',
'MySuperExtraGorgeous',
];
}
public function testConstructor()
{
static::assertHasNoConstructor(Bundle::class);
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template
* @param string $expected Expected path to view / template
*
* @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundleAndExtension
*/
public function testGetBundleViewPathUsingCustomExtension($viewPath, $bundleName, $extension, $expected)
{
self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName, $extension));
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $expected Expected path to view / template
*
* @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundle
*/
public function testGetBundleViewPathUsingDefaultExtension($viewPath, $bundleName, $expected)
{
self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName));
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
@@ -50,7 +209,7 @@ class BundleTest extends BaseTestCase
public function testGetBundleViewPathUsingIncorrectBundleName($viewPath, $bundleName)
{
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
. ' there everything ok?';
.' there everything ok?';
$this->expectException(IncorrectBundleNameException::class);
$this->expectExceptionMessage(sprintf($template, $bundleName));
@@ -59,30 +218,15 @@ class BundleTest extends BaseTestCase
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $expected Expected path to view / template
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $shortBundleName Short name of bundle (without "Bundle")
*
* @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundle
* @dataProvider provideFullAndShortBundleName
*/
public function testGetBundleViewPathUsingDefaultExtension($viewPath, $bundleName, $expected)
public function testGetShortBundleName($fullBundleName, $shortBundleName)
{
self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName));
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template
* @param string $expected Expected path to view / template
*
* @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundleAndExtension
*/
public function testGetBundleViewPathUsingCustomExtension($viewPath, $bundleName, $extension, $expected)
{
self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName, $extension));
self::assertEquals($shortBundleName, Bundle::getShortBundleName($fullBundleName));
}
public function testGetShortBundleNameUsingEmptyValue(): void
@@ -102,148 +246,4 @@ class BundleTest extends BaseTestCase
$this->expectException(IncorrectBundleNameException::class);
Bundle::getShortBundleName($bundleName);
}
/**
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $shortBundleName Short name of bundle (without "Bundle")
*
* @throws IncorrectBundleNameException
* @dataProvider provideFullAndShortBundleName
*/
public function testGetShortBundleName($fullBundleName, $shortBundleName)
{
self::assertEquals($shortBundleName, Bundle::getShortBundleName($fullBundleName));
}
/**
* Provides empty path of the view / template and/or name of bundle
*
* @return Generator
*/
public function provideEmptyViewPathAndBundle()
{
yield[
'',
'',
];
yield[
'test',
'',
];
yield[
'',
'test',
];
}
/**
* Provides path of the view / template and incorrect name of bundle
*
* @return Generator
*/
public function provideViewPathAndIncorrectBundleName()
{
yield[
'User:Active',
'myExtra',
];
yield[
'User:Active',
'MyExtra',
];
yield[
'User:Active',
'MySuperExtraGorgeous',
];
}
/**
* Provides path of the view / template and name of bundle
*
* @return Generator
*/
public function provideViewPathAndBundle()
{
yield[
'User',
'MyExtraBundle',
'@MyExtra/User.html.twig',
];
yield[
'User:Active',
'MyExtraBundle',
'@MyExtra/User/Active.html.twig',
];
yield[
'User:Active',
'MySuperExtraGorgeousBundle',
'@MySuperExtraGorgeous/User/Active.html.twig',
];
}
/**
* Provides path of the view / template, name of bundle and extension of the view / template
*
* @return Generator
*/
public function provideViewPathAndBundleAndExtension()
{
yield[
'User:Active',
'MyExtraBundle',
'',
null,
];
yield[
'User:Active',
'MyExtraBundle',
'js.twig',
'@MyExtra/User/Active.js.twig',
];
}
/**
* Provides incorrect name of bundle
*
* @return Generator
*/
public function provideIncorrectBundleName()
{
yield[
'myExtra',
];
yield[
'MyExtra',
];
yield[
'MySuperExtraGorgeous',
];
}
/**
* Provides full and short name of bundle
*
* @return Generator
*/
public function provideFullAndShortBundleName()
{
yield[
'MyExtraBundle',
'MyExtra',
];
yield[
'MySuperExtraGorgeousBundle',
'MySuperExtraGorgeous',
];
}
}

View File

@@ -19,7 +19,7 @@ use Meritoo\Common\Utilities\Composer;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Composer
* @covers \Meritoo\Common\Utilities\Composer
*/
class ComposerTest extends BaseTestCase
{
@@ -30,11 +30,40 @@ class ComposerTest extends BaseTestCase
*/
private $composerJsonPath;
/**
* Provides names and values of existing nodes
*
* @return Generator
*/
public function getExistingNode(): Generator
{
yield [
'name',
'test/test',
];
yield [
'version',
'1.0.2',
];
}
public function testConstructor()
{
static::assertHasNoConstructor(Composer::class);
}
/**
* @param string $nodeName Name of existing node
* @param string $nodeValue Value of existing node
*
* @dataProvider getExistingNode
*/
public function testGetValueExistingNode(string $nodeName, string $nodeValue): void
{
self::assertEquals($nodeValue, Composer::getValue($this->composerJsonPath, $nodeName));
}
public function testGetValueNotExistingComposerJson(): void
{
self::assertNull(Composer::getValue('', ''));
@@ -47,35 +76,6 @@ class ComposerTest extends BaseTestCase
self::assertNull(Composer::getValue($this->composerJsonPath, 'not_existing_node'));
}
/**
* @param string $nodeName Name of existing node
* @param string $nodeValue Value of existing node
*
* @dataProvider getExistingNode
*/
public function testGetValueExistingNode(string $nodeName, string $nodeValue): void
{
self::assertEquals($nodeValue, Composer::getValue($this->composerJsonPath, $nodeName));
}
/**
* Provides names and values of existing nodes
*
* @return Generator
*/
public function getExistingNode(): Generator
{
yield[
'name',
'test/test',
];
yield[
'version',
'1.0.2',
];
}
/**
* {@inheritdoc}
*/

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Utilities;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\CssSelector;
@@ -18,129 +19,152 @@ use Meritoo\Common\Utilities\CssSelector;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\CssSelector
* @covers \Meritoo\Common\Utilities\CssSelector
*/
class CssSelectorTest extends BaseTestCase
{
/**
* Provides name of form and selector of the form
*
* @return Generator
*/
public function provideFormNameAndSelector()
{
yield [
'test',
'form[name="test"]',
];
yield [
'test-123-test-456',
'form[name="test-123-test-456"]',
];
yield [
'test_something_098_different',
'form[name="test_something_098_different"]',
];
}
/**
* Provides name of form, ID of field and expected selector of label
*
* @return Generator
*/
public function provideFormNameFieldIdAndLabelSelector()
{
yield [
'test',
'test',
'form[name="test"] label[for="test"]',
];
yield [
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] label[for="great-000-field"]',
];
yield [
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] label[for="this-is-the-123789-field"]',
];
}
/**
* Provides name of form, ID of field and expected selector
*
* @return Generator
*/
public function provideFormNameFieldIdAndSelector()
{
yield [
'test',
'test',
'form[name="test"] input#test',
];
yield [
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] input#great-000-field',
];
yield [
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] input#this-is-the-123789-field',
];
}
/**
* Provides name of form, name of field and expected selector
*
* @return Generator
*/
public function provideFormNameFieldNameAndSelector()
{
yield [
'test',
'test',
'form[name="test"] input[name="test"]',
];
yield [
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] input[name="great-000-field"]',
];
yield [
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] input[name="this-is-the-123789-field"]',
];
}
/**
* Provides name of form, index/position of the field-set and expected selector
*
* @return Generator
*/
public function provideFormNameFieldSetIndexAndSelector()
{
yield [
'test',
0,
'form[name="test"] fieldset:nth-of-type(0)',
];
yield [
'test-123-test-456',
1,
'form[name="test-123-test-456"] fieldset:nth-of-type(1)',
];
yield [
'test_something_098_different',
1245,
'form[name="test_something_098_different"] fieldset:nth-of-type(1245)',
];
}
public function testConstructor()
{
static::assertHasNoConstructor(CssSelector::class);
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFormByNameSelectorUsingEmptyName($emptyValue)
{
static::assertSame('', CssSelector::getFormByNameSelector($emptyValue));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $expected Expected selector
* @param string $formName Name of form (value of the "name" attribute)
* @param int $fieldSetIndex Index/Position of the field-set
* @param string $expected Expected selector
*
* @dataProvider provideFormNameAndSelector
* @dataProvider provideFormNameFieldSetIndexAndSelector
*/
public function testGetFormByNameSelector($formName, $expected)
public function testGetFieldSetByIndexSelector($formName, $fieldSetIndex, $expected)
{
static::assertSame($expected, CssSelector::getFormByNameSelector($formName));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByNameSelectorUsingEmptyFormName($emptyValue)
{
$fieldName = 'test-test';
static::assertSame('', CssSelector::getInputByNameSelector($emptyValue, $fieldName));
}
/**
* @param string $emptyValue Name of field (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByNameSelectorUsingEmptyFieldName($emptyValue)
{
$formName = 'test-test';
static::assertSame('', CssSelector::getInputByNameSelector($formName, $emptyValue));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldName Name of field (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldNameAndSelector
*/
public function testGetInputByNameSelector($formName, $fieldName, $expected)
{
static::assertSame($expected, CssSelector::getInputByNameSelector($formName, $fieldName));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByIdSelectorUsingEmptyFormName($emptyValue)
{
$fieldId = 'test-test';
static::assertSame('', CssSelector::getInputByIdSelector($emptyValue, $fieldId));
}
/**
* @param string $emptyValue ID of field (value of the "id" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByIdSelectorUsingEmptyFieldName($emptyValue)
{
$formName = 'test-test';
static::assertSame('', CssSelector::getInputByIdSelector($formName, $emptyValue));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldId ID of field (value of the "id" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldIdAndSelector
*/
public function testGetInputByIdSelector($formName, $fieldId, $expected)
{
static::assertSame($expected, CssSelector::getInputByIdSelector($formName, $fieldId));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetLabelSelectorUsingEmptyFormName($emptyValue)
{
$fieldId = 'test-test';
static::assertSame('', CssSelector::getLabelSelector($emptyValue, $fieldId));
}
/**
* @param string $emptyValue ID of field (value of the "id" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetLabelSelectorUsingEmptyFieldId($emptyValue)
{
$formName = 'test-test';
static::assertSame('', CssSelector::getLabelSelector($formName, $emptyValue));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldId ID of field (value of the "id" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldIdAndLabelSelector
*/
public function testGetLabelSelector($formName, $fieldId, $expected)
{
static::assertSame($expected, CssSelector::getLabelSelector($formName, $fieldId));
static::assertSame($expected, CssSelector::getFieldSetByIndexSelector($formName, $fieldSetIndex));
}
/**
@@ -159,141 +183,118 @@ class CssSelectorTest extends BaseTestCase
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param int $fieldSetIndex Index/Position of the field-set
* @param string $expected Expected selector
* @param string $formName Name of form (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldSetIndexAndSelector
* @dataProvider provideFormNameAndSelector
*/
public function testGetFieldSetByIndexSelector($formName, $fieldSetIndex, $expected)
public function testGetFormByNameSelector($formName, $expected)
{
static::assertSame($expected, CssSelector::getFieldSetByIndexSelector($formName, $fieldSetIndex));
static::assertSame($expected, CssSelector::getFormByNameSelector($formName));
}
/**
* Provides name of form and selector of the form
*
* @return \Generator
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function provideFormNameAndSelector()
public function testGetFormByNameSelectorUsingEmptyName($emptyValue)
{
yield[
'test',
'form[name="test"]',
];
yield[
'test-123-test-456',
'form[name="test-123-test-456"]',
];
yield[
'test_something_098_different',
'form[name="test_something_098_different"]',
];
static::assertSame('', CssSelector::getFormByNameSelector($emptyValue));
}
/**
* Provides name of form, name of field and expected selector
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldId ID of field (value of the "id" attribute)
* @param string $expected Expected selector
*
* @return \Generator
* @dataProvider provideFormNameFieldIdAndSelector
*/
public function provideFormNameFieldNameAndSelector()
public function testGetInputByIdSelector($formName, $fieldId, $expected)
{
yield[
'test',
'test',
'form[name="test"] input[name="test"]',
];
yield[
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] input[name="great-000-field"]',
];
yield[
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] input[name="this-is-the-123789-field"]',
];
static::assertSame($expected, CssSelector::getInputByIdSelector($formName, $fieldId));
}
/**
* Provides name of form, ID of field and expected selector of label
*
* @return \Generator
* @param string $emptyValue ID of field (value of the "id" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function provideFormNameFieldIdAndLabelSelector()
public function testGetInputByIdSelectorUsingEmptyFieldName($emptyValue)
{
yield[
'test',
'test',
'form[name="test"] label[for="test"]',
];
yield[
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] label[for="great-000-field"]',
];
yield[
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] label[for="this-is-the-123789-field"]',
];
$formName = 'test-test';
static::assertSame('', CssSelector::getInputByIdSelector($formName, $emptyValue));
}
/**
* Provides name of form, index/position of the field-set and expected selector
*
* @return \Generator
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function provideFormNameFieldSetIndexAndSelector()
public function testGetInputByIdSelectorUsingEmptyFormName($emptyValue)
{
yield[
'test',
0,
'form[name="test"] fieldset:nth-of-type(0)',
];
yield[
'test-123-test-456',
1,
'form[name="test-123-test-456"] fieldset:nth-of-type(1)',
];
yield[
'test_something_098_different',
1245,
'form[name="test_something_098_different"] fieldset:nth-of-type(1245)',
];
$fieldId = 'test-test';
static::assertSame('', CssSelector::getInputByIdSelector($emptyValue, $fieldId));
}
/**
* Provides name of form, ID of field and expected selector
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldName Name of field (value of the "name" attribute)
* @param string $expected Expected selector
*
* @return \Generator
* @dataProvider provideFormNameFieldNameAndSelector
*/
public function provideFormNameFieldIdAndSelector()
public function testGetInputByNameSelector($formName, $fieldName, $expected)
{
yield[
'test',
'test',
'form[name="test"] input#test',
];
static::assertSame($expected, CssSelector::getInputByNameSelector($formName, $fieldName));
}
yield[
'test-123-test-456',
'great-000-field',
'form[name="test-123-test-456"] input#great-000-field',
];
/**
* @param string $emptyValue Name of field (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByNameSelectorUsingEmptyFieldName($emptyValue)
{
$formName = 'test-test';
static::assertSame('', CssSelector::getInputByNameSelector($formName, $emptyValue));
}
yield[
'test_something_098_different',
'this-is-the-123789-field',
'form[name="test_something_098_different"] input#this-is-the-123789-field',
];
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByNameSelectorUsingEmptyFormName($emptyValue)
{
$fieldName = 'test-test';
static::assertSame('', CssSelector::getInputByNameSelector($emptyValue, $fieldName));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $fieldId ID of field (value of the "id" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldIdAndLabelSelector
*/
public function testGetLabelSelector($formName, $fieldId, $expected)
{
static::assertSame($expected, CssSelector::getLabelSelector($formName, $fieldId));
}
/**
* @param string $emptyValue ID of field (value of the "id" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetLabelSelectorUsingEmptyFieldId($emptyValue)
{
$formName = 'test-test';
static::assertSame('', CssSelector::getLabelSelector($formName, $emptyValue));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetLabelSelectorUsingEmptyFormName($emptyValue)
{
$fieldId = 'test-test';
static::assertSame('', CssSelector::getLabelSelector($emptyValue, $fieldId));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -18,7 +18,7 @@ use Meritoo\Common\Utilities\GeneratorUtility;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\GeneratorUtility
* @covers \Meritoo\Common\Utilities\GeneratorUtility
*/
class GeneratorUtilityTest extends BaseTestCase
{

View File

@@ -20,10 +20,138 @@ use ReflectionException;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\Locale
* @covers \Meritoo\Common\Utilities\Locale
*/
class LocaleTest extends BaseTestCase
{
/**
* Provides category
*
* @return Generator
*/
public function provideCategoryLanguageCodeAndExpectedLocale()
{
yield [
LC_ALL,
'fr',
'',
'fr_FR.UTF-8',
];
yield [
LC_COLLATE,
'fr',
'FR',
'fr_FR.UTF-8',
];
yield [
LC_CTYPE,
'en',
'US',
'en_US.UTF-8',
];
yield [
LC_NUMERIC,
'en',
'GB',
'en_GB.UTF-8',
];
yield [
LC_MONETARY,
'es',
'',
'es_ES.UTF-8',
];
yield [
LC_MONETARY,
'es',
'ES',
'es_ES.UTF-8',
];
yield [
LC_TIME,
'it',
'',
'it_IT.UTF-8',
];
yield [
LC_TIME,
'it',
'IT',
'it_IT.UTF-8',
];
yield [
LC_TIME,
'it',
'it',
'it_IT.UTF-8',
];
}
/**
* Provides language, encoding and country code
*
* @return Generator
*/
public function provideLanguageEncodingAndCountryCode()
{
yield [
'fr',
'',
'',
'fr_FR',
];
yield [
'fr',
'',
'UTF-8',
'fr_FR.UTF-8',
];
yield [
'fr',
'FR',
'',
'fr_FR',
];
yield [
'fr',
'FR',
'UTF-8',
'fr_FR.UTF-8',
];
yield [
'en',
'US',
'',
'en_US',
];
yield [
'en',
'US',
'UTF-8',
'en_US.UTF-8',
];
yield [
'en',
'US',
'ISO-8859-1',
'en_US.ISO-8859-1',
];
}
/**
* @throws ReflectionException
*/
@@ -32,56 +160,6 @@ class LocaleTest extends BaseTestCase
static::assertHasNoConstructor(Locale::class);
}
/**
* @param mixed $languageCode Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetLongFormEmptyLanguageCode($languageCode)
{
self::assertEquals('', Locale::getLongForm($languageCode));
}
/**
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @param string $encoding Encoding of the final locale
* @param string $expected Expected long form of the locale
*
* @dataProvider provideLanguageEncodingAndCountryCode
*/
public function testGetLongForm($languageCode, $countryCode, $encoding, $expected)
{
self::assertEquals($expected, Locale::getLongForm($languageCode, $countryCode, $encoding));
}
/**
* @param mixed $emptyValue Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testSetLocaleEmptyCategoryAndLanguageCode($emptyValue)
{
self::assertFalse(Locale::setLocale($emptyValue, $emptyValue));
}
public function testSetLocaleIncorrectCategory()
{
self::assertFalse(Locale::setLocale(-1, 'en'));
}
/**
* @param int $category Named constant specifying the category of the functions affected by the locale
* setting. It's the same constant as required by setlocale() function.
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @param string $expectedLocale Expected locale
*
* @dataProvider provideCategoryLanguageCodeAndExpectedLocale
*/
public function testSetLocale($category, $languageCode, $countryCode, $expectedLocale)
{
self::assertEquals($expectedLocale, Locale::setLocale($category, $languageCode, $countryCode));
}
/**
* @param int $category Named constant specifying the category of the functions affected by the locale
* setting. It's the same constant as required by setlocale() function.
@@ -98,130 +176,52 @@ class LocaleTest extends BaseTestCase
}
/**
* Provides language, encoding and country code
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @param string $encoding Encoding of the final locale
* @param string $expected Expected long form of the locale
*
* @return Generator
* @dataProvider provideLanguageEncodingAndCountryCode
*/
public function provideLanguageEncodingAndCountryCode()
public function testGetLongForm($languageCode, $countryCode, $encoding, $expected)
{
yield[
'fr',
'',
'',
'fr_FR',
];
yield[
'fr',
'',
'UTF-8',
'fr_FR.UTF-8',
];
yield[
'fr',
'FR',
'',
'fr_FR',
];
yield[
'fr',
'FR',
'UTF-8',
'fr_FR.UTF-8',
];
yield[
'en',
'US',
'',
'en_US',
];
yield[
'en',
'US',
'UTF-8',
'en_US.UTF-8',
];
yield[
'en',
'US',
'ISO-8859-1',
'en_US.ISO-8859-1',
];
self::assertEquals($expected, Locale::getLongForm($languageCode, $countryCode, $encoding));
}
/**
* Provides category
*
* @return Generator
* @param mixed $languageCode Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function provideCategoryLanguageCodeAndExpectedLocale()
public function testGetLongFormEmptyLanguageCode($languageCode)
{
yield[
LC_ALL,
'fr',
'',
'fr_FR.UTF-8',
];
self::assertEquals('', Locale::getLongForm($languageCode));
}
yield[
LC_COLLATE,
'fr',
'FR',
'fr_FR.UTF-8',
];
/**
* @param int $category Named constant specifying the category of the functions affected by the locale
* setting. It's the same constant as required by setlocale() function.
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @param string $expectedLocale Expected locale
*
* @dataProvider provideCategoryLanguageCodeAndExpectedLocale
*/
public function testSetLocale($category, $languageCode, $countryCode, $expectedLocale)
{
self::assertEquals($expectedLocale, Locale::setLocale($category, $languageCode, $countryCode));
}
yield[
LC_CTYPE,
'en',
'US',
'en_US.UTF-8',
];
/**
* @param mixed $emptyValue Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testSetLocaleEmptyCategoryAndLanguageCode($emptyValue)
{
self::assertFalse(Locale::setLocale($emptyValue, $emptyValue));
}
yield[
LC_NUMERIC,
'en',
'GB',
'en_GB.UTF-8',
];
yield[
LC_MONETARY,
'es',
'',
'es_ES.UTF-8',
];
yield[
LC_MONETARY,
'es',
'ES',
'es_ES.UTF-8',
];
yield[
LC_TIME,
'it',
'',
'it_IT.UTF-8',
];
yield[
LC_TIME,
'it',
'IT',
'it_IT.UTF-8',
];
yield[
LC_TIME,
'it',
'it',
'it_IT.UTF-8',
];
public function testSetLocaleIncorrectCategory()
{
self::assertFalse(Locale::setLocale(-1, 'en'));
}
}

View File

@@ -19,15 +19,309 @@ use Meritoo\Common\Utilities\MimeTypes;
* @copyright Meritoo <http://www.meritoo.pl>
*
* @internal
* @covers \Meritoo\Common\Utilities\MimeTypes
* @covers \Meritoo\Common\Utilities\MimeTypes
*/
class MimeTypesTest extends BaseTestCase
{
/**
* Provides real file path to get information if the file is an image
*
* @return Generator
*/
public function provideExistingFilePathToCheckIsImagePath()
{
yield [
$this->getFilePathForTesting('minion.jpg'),
true,
];
yield [
$this->getFilePathForTesting('lorem-ipsum.txt'),
false,
];
}
/**
* Provides real file path to get mime type
*
* @return Generator
*/
public function provideFilePathToGetMimeTypeOfRealFile()
{
yield [
$this->getFilePathForTesting('minion.jpg'),
'image/jpeg',
];
yield [
$this->getFilePathForTesting('lorem-ipsum.txt'),
'text/plain',
];
}
/**
* Provides mime type of image
*
* @return Generator
*/
public function provideImageMimeType()
{
yield ['image/bmp'];
yield ['image/jpeg'];
yield ['image/png'];
yield ['image/tiff'];
yield ['image/vnd.microsoft.icon'];
yield ['image/x-rgb'];
}
/**
* Provides existing mime type used to get multiple, more than one extension
*
* @return Generator
*/
public function provideMimeTypeToGetMultipleExtension()
{
yield [
'application/postscript',
[
'ai',
'eps',
'ps',
],
];
yield [
'audio/midi',
[
'mid',
'midi',
'kar',
'rmi',
],
];
yield [
'image/jpeg',
[
'jpeg',
'jpe',
'jpg',
],
];
yield [
'text/html',
[
'html',
'htm',
],
];
yield [
'text/plain',
[
'txt',
'text',
'conf',
'def',
'list',
'log',
'in',
],
];
yield [
'video/mp4',
[
'mp4',
'mp4v',
'mpg4',
'm4v',
],
];
}
/**
* Provides existing mime type used to get single, one extension
*
* @return Generator
*/
public function provideMimeTypeToGetSingleExtension()
{
yield [
'application/x-7z-compressed',
'7z',
];
yield [
'application/json',
'json',
];
yield [
'application/zip',
'zip',
];
}
/**
* Provides mime types used to get extensions
*
* @return Generator
*/
public function provideMimesTypesToGetExtensions()
{
yield [
[
'application/x-7z-compressed',
'application/json',
],
[
'application/x-7z-compressed' => '7z',
'application/json' => 'json',
],
];
yield [
[
'application/mathematica',
'application/xml',
'audio/mp4',
'video/mp4',
],
[
'application/mathematica' => [
'ma',
'nb',
'mb',
],
'application/xml' => [
'xml',
'xsl',
],
'audio/mp4' => 'mp4a',
'video/mp4' => [
'mp4',
'mp4v',
'mpg4',
'm4v',
],
],
];
}
/**
* Provides mime types used to get extensions as upper case
*
* @return Generator
*/
public function provideMimesTypesToGetExtensionsUpperCase()
{
yield [
[
'application/x-7z-compressed',
'application/json',
],
[
'application/x-7z-compressed' => '7Z',
'application/json' => 'JSON',
],
];
yield [
[
'application/xml',
'audio/mp4',
'text/html',
'video/mp4',
],
[
'application/xml' => [
'XML',
'XSL',
],
'audio/mp4' => 'MP4A',
'text/html' => [
'HTML',
'HTM',
],
'video/mp4' => [
'MP4',
'MP4V',
'MPG4',
'M4V',
],
],
];
}
/**
* Provides mime type of non-image
*
* @return Generator
*/
public function provideNonImageMimeType()
{
yield ['application/rtf'];
yield ['audio/mp4'];
yield ['text/plain'];
yield ['text/html'];
}
/**
* Provides not existing mime type
*
* @return Generator
*/
public function provideNotExistingMimeType()
{
yield ['lorem/ipsum'];
yield ['dolor'];
yield ['x/y/z'];
}
/**
* Provides not existing mime types
*
* @return Generator
*/
public function provideNotExistingMimeTypes()
{
yield [
[],
];
yield [
[
'',
null,
false,
0,
],
];
yield [
[
'lorem/ipsum',
'dolor/sit',
],
];
}
public function testConstructor()
{
static::assertHasNoConstructor(MimeTypes::class);
}
/**
* @param bool $mimeType The mime type, e.g. "video/mpeg"
* @dataProvider provideBooleanValue
*/
public function testGetExtensionBooleanMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue
@@ -38,12 +332,14 @@ class MimeTypesTest extends BaseTestCase
}
/**
* @param bool $mimeType The mime type, e.g. "video/mpeg"
* @dataProvider provideBooleanValue
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param array $extensions Expected extensions
*
* @dataProvider provideMimeTypeToGetMultipleExtension
*/
public function testGetExtensionBooleanMimeType($mimeType)
public function testGetExtensionMultiple($mimeType, $extensions)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
self::assertEquals($extensions, MimeTypes::getExtension($mimeType));
}
/**
@@ -67,14 +363,14 @@ class MimeTypesTest extends BaseTestCase
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param array $extensions Expected extensions
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param array $extensions Expected extensions
*
* @dataProvider provideMimeTypeToGetMultipleExtension
* @dataProvider provideMimesTypesToGetExtensions
*/
public function testGetExtensionMultiple($mimeType, $extensions)
public function testGetExtensions($mimesTypes, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtension($mimeType));
self::assertEquals($extensions, MimeTypes::getExtensions($mimesTypes));
}
/**
@@ -86,17 +382,6 @@ class MimeTypesTest extends BaseTestCase
self::assertEquals([], MimeTypes::getExtensions($mimesTypes));
}
/**
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param array $extensions Expected extensions
*
* @dataProvider provideMimesTypesToGetExtensions
*/
public function testGetExtensions($mimesTypes, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtensions($mimesTypes));
}
/**
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param array $extensions Expected extensions
@@ -138,12 +423,12 @@ class MimeTypesTest extends BaseTestCase
}
/**
* @param string $mimeType Not existing mime type, e.g. "lorem/ipsum"
* @dataProvider provideNotExistingMimeType
* @param string $mimeType Mime type of image, e.g. "image/jpeg"
* @dataProvider provideImageMimeType
*/
public function testIsImageNotExistingMimeType($mimeType)
public function testIsImageImageMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
self::assertTrue(MimeTypes::isImage($mimeType));
}
/**
@@ -155,6 +440,15 @@ class MimeTypesTest extends BaseTestCase
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param string $mimeType Not existing mime type, e.g. "lorem/ipsum"
* @dataProvider provideNotExistingMimeType
*/
public function testIsImageNotExistingMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param mixed $path Empty value, e.g. ""
* @dataProvider provideEmptyValue
@@ -164,15 +458,6 @@ class MimeTypesTest extends BaseTestCase
self::assertFalse(MimeTypes::isImagePath($path));
}
/**
* @param mixed $path Path of not existing file, e.g. "lorem/ipsum.jpg"
* @dataProvider provideNotExistingFilePath
*/
public function testIsImagePathNotExistingPath($path)
{
self::assertFalse(MimeTypes::isImagePath($path));
}
/**
* @param string $path Path of the file to check
* @param bool $isImage Expected information if the file is an image
@@ -185,296 +470,11 @@ class MimeTypesTest extends BaseTestCase
}
/**
* @param string $mimeType Mime type of image, e.g. "image/jpeg"
* @dataProvider provideImageMimeType
* @param mixed $path Path of not existing file, e.g. "lorem/ipsum.jpg"
* @dataProvider provideNotExistingFilePath
*/
public function testIsImageImageMimeType($mimeType)
public function testIsImagePathNotExistingPath($path)
{
self::assertTrue(MimeTypes::isImage($mimeType));
}
/**
* Provides not existing mime type
*
* @return Generator
*/
public function provideNotExistingMimeType()
{
yield['lorem/ipsum'];
yield['dolor'];
yield['x/y/z'];
}
/**
* Provides mime type of non-image
*
* @return Generator
*/
public function provideNonImageMimeType()
{
yield['application/rtf'];
yield['audio/mp4'];
yield['text/plain'];
yield['text/html'];
}
/**
* Provides mime type of image
*
* @return Generator
*/
public function provideImageMimeType()
{
yield['image/bmp'];
yield['image/jpeg'];
yield['image/png'];
yield['image/tiff'];
yield['image/vnd.microsoft.icon'];
yield['image/x-rgb'];
}
/**
* Provides existing mime type used to get single, one extension
*
* @return Generator
*/
public function provideMimeTypeToGetSingleExtension()
{
yield[
'application/x-7z-compressed',
'7z',
];
yield[
'application/json',
'json',
];
yield[
'application/zip',
'zip',
];
}
/**
* Provides existing mime type used to get multiple, more than one extension
*
* @return Generator
*/
public function provideMimeTypeToGetMultipleExtension()
{
yield[
'application/postscript',
[
'ai',
'eps',
'ps',
],
];
yield[
'audio/midi',
[
'mid',
'midi',
'kar',
'rmi',
],
];
yield[
'image/jpeg',
[
'jpeg',
'jpe',
'jpg',
],
];
yield[
'text/html',
[
'html',
'htm',
],
];
yield[
'text/plain',
[
'txt',
'text',
'conf',
'def',
'list',
'log',
'in',
],
];
yield[
'video/mp4',
[
'mp4',
'mp4v',
'mpg4',
'm4v',
],
];
}
/**
* Provides not existing mime types
*
* @return Generator
*/
public function provideNotExistingMimeTypes()
{
yield[
[],
];
yield[
[
'',
null,
false,
0,
],
];
yield[
[
'lorem/ipsum',
'dolor/sit',
],
];
}
/**
* Provides mime types used to get extensions
*
* @return Generator
*/
public function provideMimesTypesToGetExtensions()
{
yield[
[
'application/x-7z-compressed',
'application/json',
],
[
'application/x-7z-compressed' => '7z',
'application/json' => 'json',
],
];
yield[
[
'application/mathematica',
'application/xml',
'audio/mp4',
'video/mp4',
],
[
'application/mathematica' => [
'ma',
'nb',
'mb',
],
'application/xml' => [
'xml',
'xsl',
],
'audio/mp4' => 'mp4a',
'video/mp4' => [
'mp4',
'mp4v',
'mpg4',
'm4v',
],
],
];
}
/**
* Provides mime types used to get extensions as upper case
*
* @return Generator
*/
public function provideMimesTypesToGetExtensionsUpperCase()
{
yield[
[
'application/x-7z-compressed',
'application/json',
],
[
'application/x-7z-compressed' => '7Z',
'application/json' => 'JSON',
],
];
yield[
[
'application/xml',
'audio/mp4',
'text/html',
'video/mp4',
],
[
'application/xml' => [
'XML',
'XSL',
],
'audio/mp4' => 'MP4A',
'text/html' => [
'HTML',
'HTM',
],
'video/mp4' => [
'MP4',
'MP4V',
'MPG4',
'M4V',
],
],
];
}
/**
* Provides real file path to get mime type
*
* @return Generator
*/
public function provideFilePathToGetMimeTypeOfRealFile()
{
yield[
$this->getFilePathForTesting('minion.jpg'),
'image/jpeg',
];
yield[
$this->getFilePathForTesting('lorem-ipsum.txt'),
'text/plain',
];
}
/**
* Provides real file path to get information if the file is an image
*
* @return Generator
*/
public function provideExistingFilePathToCheckIsImagePath()
{
yield[
$this->getFilePathForTesting('minion.jpg'),
true,
];
yield[
$this->getFilePathForTesting('lorem-ipsum.txt'),
false,
];
self::assertFalse(MimeTypes::isImagePath($path));
}
}

Some files were not shown because too many files have changed in this diff Show More