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,8 +8,7 @@ $finder = PhpCsFixer\Finder::create()
]) ])
->notPath([ ->notPath([
'tests/Resources/var/', 'tests/Resources/var/',
]) ]);
;
return PhpCsFixer\Config::create() return PhpCsFixer\Config::create()
->setRules([ ->setRules([

View File

@@ -2,6 +2,10 @@
Common and useful classes, methods, exceptions etc. Common and useful classes, methods, exceptions etc.
# 1.1.8
1.
# 1.1.7 # 1.1.7
1. [Arrays] Allow to define a key of next level elements in a function that returns elements from given level 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.1.1
1. [BaseCollection] Treat the `null` index as "no index" only while adding new element, iow. do not treat empty 1. [BaseCollection] Treat the `null` index as "no index" only while adding new element, iow. do not treat empty string
string as "no index" behaviour. as "no index" behaviour.
2. [Miscellaneous] [Regex] Use simpler & stronger pattern to match name of file 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 3. Do not install `hirak/prestissimo` package while running Travis CI (incompatible with your PHP version, PHP
extensions and Composer version) extensions and Composer version)
@@ -41,9 +45,9 @@ string as "no index" behaviour.
# 1.1.0 # 1.1.0
1. Rename Meritoo\Common\Collection\Collection class to Meritoo\Common\Collection\BaseCollection. 1. Rename Meritoo\Common\Collection\Collection class to Meritoo\Common\Collection\BaseCollection. Add BaseCollection::
Add BaseCollection::isValidType() method to validate type of element before add it to collection. isValidType() method to validate type of element before add it to collection. Add BaseCollection ::prepareElements()
Add BaseCollection ::prepareElements() method to allow preparation of elements in custom way. method to allow preparation of elements in custom way.
# 1.0.6 # 1.0.6
@@ -135,7 +139,8 @@ character class at offset 4" bug
1. Tests > refactoring & minor improvements 1. Tests > refactoring & minor improvements
2. Utilities > CssSelector > useful methods related to CSS selectors 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 # 0.1.2
@@ -174,5 +179,6 @@ character class at offset 4" bug
4. StyleCI & PHP Coding Standards Fixer: update configuration 4. StyleCI & PHP Coding Standards Fixer: update configuration
5. Documentation > Docker > add paragraph for PHP Coding Standards Fixer 5. Documentation > Docker > add paragraph for PHP Coding Standards Fixer
6. Coding standard > fix automatically 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 8. StyleCI > disable & remove

View File

@@ -10,8 +10,9 @@ Common and useful classes, methods, exceptions etc.
### Info ### Info
It's a set of some elements with the same type, e.g. objects. It's iterable and countable. Provides very useful It's a set of some elements with the same type, e.g. objects. It's iterable and countable. Provides very useful methods.
methods. Some of them: Some of them:
- `getFirst()` - returns the first element in the collection - `getFirst()` - returns the first element in the collection
- `getLast()` - returns the last element in the collection - `getLast()` - returns the last element in the collection
- `isEmpty()` - returns information if collection is empty - `isEmpty()` - returns information if collection is empty

View File

@@ -36,7 +36,8 @@ New instance can be created using:
##### Methods ##### 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: Example of usage:
@@ -49,7 +50,8 @@ $templates = new Templates([
$template = $templates->findTemplate('first'); // new Template('First name: %first_name%') $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 # More

View File

@@ -128,6 +128,7 @@ root@18f2f0cfaa5d:/var/www/application# XDEBUG_MODE=coverage phing -f phing/test
##### Terminal ##### Terminal
Example of output: Example of output:
```bash ```bash
125 mutations were generated: 125 mutations were generated:
105 mutants were killed 105 mutants were killed

View File

@@ -6,7 +6,8 @@ Common and useful classes, methods, exceptions etc.
### Create instance of exception ### 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 ```php
use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException; use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException;
@@ -17,11 +18,14 @@ throw IncorrectBundleNameException::create('RisusIpsum');
##### Short description ##### 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 ##### 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 ##### Example

View File

@@ -4,7 +4,8 @@ Common and useful classes, methods, exceptions etc.
# Static methods # 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 ```php
use Meritoo\Common\Utilities\Arrays; use Meritoo\Common\Utilities\Arrays;

View File

@@ -25,10 +25,12 @@ File: `src/Utilities/Arrays.php`
- result: `false` - result: `false`
2) 2)
- array: `["", -1]` - array: `["", -1]`
- result: `false` - result: `false`
3) 3)
- array: `["", null, ""]` - array: `["", null, ""]`
- result: `true` - result: `true`

View File

@@ -15,6 +15,7 @@ Located in `Meritoo\Common\ValueObject` namespace and in `src/ValueObject/` dire
##### Info ##### Info
Represents address of company, institution, user etc. Contains properties: Represents address of company, institution, user etc. Contains properties:
1. `$street` - the street 1. `$street` - the street
2. `$buildingNumber` - the number of building 2. `$buildingNumber` - the number of building
3. `$flatNumber` - the number of flat 3. `$flatNumber` - the number of flat
@@ -66,6 +67,7 @@ $asString = (string)$address; // "4th Avenue 10/200, 00123, New York"
##### Info ##### Info
Represents bank account. Contains properties: Represents bank account. Contains properties:
1. `$bankName` - name of bank 1. `$bankName` - name of bank
2. `$accountNumber` - number of bank's account 2. `$accountNumber` - number of bank's account
@@ -101,6 +103,7 @@ $asString = (string)$bank; // "Bank of America, 1234567890"
##### Info ##### Info
Represents a company. Contains properties: Represents a company. Contains properties:
1. `$name` - name of company 1. `$name` - name of company
2. `$address` - address of company 2. `$address` - address of company
3. `$bankAccount` - bank account 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 ##### 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 1. `$firstName` - first name
2. `$lastName` - last name 2. `$lastName` - last name
3. `$email` - email address 3. `$email` - email address
@@ -186,6 +191,7 @@ $asString2 = (string)$human2; // "John Scott <john@scott.com>"
##### Info ##### Info
Size, e.g. of image. Contains properties: Size, e.g. of image. Contains properties:
1. `width` - the width 1. `width` - the width
2. `height` - the height 2. `height` - the height
3. `unit` - unit used when width or height should be returned with unit, default: `"px"` 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 ##### Methods
Has: Has:
- getters and setters for `width` and `height` properties. - getters and setters for `width` and `height` properties.
- setter for `separator` property - setter for `separator` property
- `toString()` and `toArray()` methods that returns size represented as string and array - `toString()` and `toArray()` methods that returns size represented as string and array
##### Conversion to string (using `__toString()` method) ##### 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: Example:
@@ -248,6 +256,7 @@ $asString2 = (string)$size; // "200X100"
##### Info ##### Info
Template with placeholders that may be filled by real data. Contains properties: Template with placeholders that may be filled by real data. Contains properties:
1. `$content` - raw string with placeholders (content of the template) 1. `$content` - raw string with placeholders (content of the template)
##### New instance ##### New instance
@@ -258,7 +267,9 @@ New instance can be created using constructor:
new Template('First name: %first_name%'); 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: Examples of invalid content of template:
@@ -270,7 +281,8 @@ new Template('This is %test'); // With starting tag only (invalid placeholder)
##### Methods ##### 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: Example of usage:
@@ -282,7 +294,8 @@ $result = $template->fill([
]); // "My name is Jane and I am photographer" ]); // "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 ### Version
@@ -293,6 +306,7 @@ Throws an `Meritoo\Common\Exception\ValueObject\Template\NotEnoughValuesExceptio
##### Info ##### Info
Represents version of software. Contains properties: Represents version of software. Contains properties:
1. `$majorPart` - the "major" part of version 1. `$majorPart` - the "major" part of version
2. `$minorPart` - the "minor" part of version 2. `$minorPart` - the "minor" part of version
3. `$patchPart` - the "patch" part of version 3. `$patchPart` - the "patch" part of version
@@ -326,7 +340,8 @@ Has getters for each property: `getMajorPart()`, `getMinorPart()`, `getPatchPart
##### Conversion to string (using `__toString()` method) ##### 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: Example:

View File

@@ -40,16 +40,6 @@ abstract class BaseCollection implements CollectionInterface
$this->elements = $this->prepareElements($validated); $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) * Adds given element (at the end of collection)
* *
@@ -97,45 +87,50 @@ abstract class BaseCollection implements CollectionInterface
} }
} }
/** public function clear(): void
* Prepends given element (adds given element at the beginning of collection)
*
* @param mixed $element The element to prepend
*/
public function prepend($element): void
{ {
array_unshift($this->elements, $element); $this->elements = [];
} }
/** public function count(): int
* Removes given element
*
* @param mixed $element The element to remove
*/
public function remove($element): void
{ {
if (0 === $this->count()) { return count($this->elements);
return;
}
foreach ($this->elements as $index => $existing) {
if ($element === $existing) {
unset($this->elements[$index]);
break;
}
}
} }
/** /**
* Returns previous element for given element * Returns element with given index
* *
* @param mixed $element The element to verify * @param mixed $index Index / key of the element
* @return null|mixed * @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 * @param mixed $element The element to verify
*/
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
* @return null|mixed * @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; 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 public function limit(int $max, int $offset = 0): CollectionInterface
{ {
$result = clone $this; $result = clone $this;
@@ -260,11 +230,6 @@ abstract class BaseCollection implements CollectionInterface
return $result; return $result;
} }
public function count(): int
{
return count($this->elements);
}
public function offsetExists($offset): bool public function offsetExists($offset): bool
{ {
return $this->exists($offset); 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. * Prepares elements to initialize the collection.
* Feel free to override and prepare elements in your way. * 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 * @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 * Returns elements of collection with valid types
@@ -340,15 +351,4 @@ abstract class BaseCollection implements CollectionInterface
return $result; 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 * Finds and returns template with given index
* *
* @param string $index Index that contains required template * @param string $index Index that contains required template
* @throws TemplateNotFoundException
* @return Template * @return Template
* @throws TemplateNotFoundException
*/ */
public function findTemplate(string $index): Template public function findTemplate(string $index): Template
{ {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -16,6 +16,24 @@ namespace Meritoo\Common\Traits\CssSelector;
*/ */
trait FormCssSelector 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 * Returns selector of form based on its name
* *
@@ -33,25 +51,6 @@ trait FormCssSelector
return sprintf('form[name="%s"]', $formName); 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 * Returns selector of the input field based on its ID
* *
@@ -71,6 +70,25 @@ trait FormCssSelector
return sprintf('%s input#%s', $formSelector, $fieldId); 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 * Returns selector of label
* *
@@ -89,22 +107,4 @@ trait FormCssSelector
return sprintf('%s label[for="%s"]', $formSelector, $fieldId); 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'; 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 * Provides boolean value
* *
@@ -110,15 +81,32 @@ trait BaseTestCaseTrait
} }
/** /**
* Provides path of not existing file, e.g. "lorem/ipsum.jpg" * Provides an empty scalar value
* *
* @return Generator * @return Generator
*/ */
public function provideNotExistingFilePath(): ?Generator public function provideEmptyScalarValue(): ?Generator
{ {
yield['lets-test.doc']; yield [''];
yield['lorem/ipsum.jpg']; yield [' '];
yield['surprise/me/one/more/time.txt']; 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 [[]];
} }
/** /**
@@ -134,75 +122,15 @@ trait BaseTestCaseTrait
} }
/** /**
* Returns path of file used by tests. * Provides path of not existing file, e.g. "lorem/ipsum.jpg"
* It should be placed in /data/tests directory of this project.
* *
* @param string $fileName Name of file * @return Generator
* @param string $directoryPath (optional) Path of directory containing the file
* @return string
*/ */
protected function getFilePathForTesting(string $fileName, string $directoryPath = ''): string public function provideNotExistingFilePath(): ?Generator
{ {
$rootPath = Miscellaneous::getProjectRootPath(); yield ['lets-test.doc'];
yield ['lorem/ipsum.jpg'];
$paths = [ yield ['surprise/me/one/more/time.txt'];
$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());
} }
/** /**
@@ -246,6 +174,78 @@ trait BaseTestCaseTrait
static::assertNull($constructor); 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 * Sets path of directory with data used by test cases
* *

View File

@@ -21,6 +21,13 @@ use Meritoo\Common\Type\Base\BaseType;
*/ */
trait BaseTypeTestCaseTrait trait BaseTypeTestCaseTrait
{ {
/**
* Provides type to verify and information if it's correct
*
* @return Generator
*/
abstract public function provideTypeToVerify(): Generator;
/** /**
* Verifies availability of all types * 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 * Returns instance of the tested type
@@ -58,11 +65,4 @@ trait BaseTypeTestCaseTrait
* @return BaseType * @return BaseType
*/ */
abstract protected function getTestedTypeInstance(): 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; return $this->birthDate;
}
/**
* Returns last name
*
* @return string
*/
public function getLastName(): string
{
return $this->lastName;
} }
/** /**
@@ -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)); 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; 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 * Returns all types
* *
@@ -50,4 +39,15 @@ abstract class BaseType
return $this->all; 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; $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 * 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); 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 * 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); 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 * Returns selector of radio-button's validation error
* *
@@ -65,21 +82,4 @@ class Bootstrap4CssSelector
return sprintf('%s legend.col-form-label %s', $fieldSetSelector, $errorContainerSelector); 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 $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 $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template (default: "html.twig") * @param string $extension (optional) Extension of the view / template (default: "html.twig")
* @throws IncorrectBundleNameException
* @return null|string * @return null|string
* @throws IncorrectBundleNameException
*/ */
public static function getBundleViewPath( public static function getBundleViewPath(
string $viewPath, string $viewPath,
@@ -58,8 +58,8 @@ class Bundle
* Returns short name of bundle (without "Bundle") * Returns short name of bundle (without "Bundle")
* *
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle" * @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @throws IncorrectBundleNameException
* @return null|string * @return null|string
* @throws IncorrectBundleNameException
*/ */
public static function getShortBundleName(string $fullBundleName): ?string public static function getShortBundleName(string $fullBundleName): ?string
{ {

View File

@@ -63,127 +63,6 @@ class Date
*/ */
public const DATE_DIFFERENCE_UNIT_YEARS = 'years'; 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) * Generates and returns random time (the hour, minute and second values)
* *
@@ -246,39 +125,6 @@ class Date
return self::getDayOfWeek($year, $month, $day); 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 * Returns based on locale name of current weekday
* *
@@ -295,32 +141,6 @@ class Date
return self::getDayOfWeekName($year, $month, $day); 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. * Returns difference between given dates.
* *
@@ -455,95 +275,6 @@ class Date
return $difference; 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. * Returns the DateTime object for given value.
* If the DateTime object cannot be created, false is returned. * If the DateTime object cannot be created, false is returned.
@@ -655,6 +386,275 @@ class Date
return false; 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 * 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 * @throws UnknownDatePartTypeException
*/ */
private static function validateYear(int $year): void private static function validateDay(int $day): void
{ {
// Oops, given year is incorrect // Oops, given day is incorrect
if ($year >= 0) { if ($day >= 1 && $day <= 31) {
return; 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 * @throws UnknownDatePartTypeException
*/ */
private static function validateDay(int $day): void private static function validateYear(int $year): void
{ {
// Oops, given day is incorrect // Oops, given year is incorrect
if ($day >= 1 && $day <= 31) { if ($year >= 0) {
return; 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 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 * Returns locale for given category
* *
@@ -123,4 +78,49 @@ class Locale
return sprintf('%s_%s%s', $languageCode, strtoupper($countryCode), $encoding); 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);
}
} }

View File

@@ -8,6 +8,9 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
use finfo;
use RuntimeException;
/** /**
* Useful methods for mime types of files * Useful methods for mime types of files
* *
@@ -679,6 +682,23 @@ class MimeTypes
'ice' => 'x-conference/x-cooltalk', 'ice' => 'x-conference/x-cooltalk',
]; ];
/**
* Returns extension for given mime type
*
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @return array|string
*/
public static function getExtension($mimeType)
{
if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes, true)) {
$data = Arrays::setKeysAsValues(self::$mimeTypes, false);
return $data[$mimeType];
}
return '';
}
/** /**
* Returns extensions for given mimes types * Returns extensions for given mimes types
* *
@@ -722,42 +742,12 @@ class MimeTypes
return $extensions; return $extensions;
} }
/**
* Returns extension for given mime type
*
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @return array|string
*/
public static function getExtension($mimeType)
{
if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes, true)) {
$data = Arrays::setKeysAsValues(self::$mimeTypes, false);
return $data[$mimeType];
}
return '';
}
/**
* Returns information whether file with the given path is an image
*
* @param string $path Path of the file to check
* @return bool
*/
public static function isImagePath($path)
{
$mimeType = self::getMimeType($path);
return self::isImage($mimeType);
}
/** /**
* Returns mime type of given file * Returns mime type of given file
* *
* @param string $filePath Path of the file to check * @param string $filePath Path of the file to check
* @throws \RuntimeException
* @return string * @return string
* @throws RuntimeException
*/ */
public static function getMimeType($filePath) public static function getMimeType($filePath)
{ {
@@ -771,7 +761,7 @@ class MimeTypes
// 1st possibility: the finfo class // 1st possibility: the finfo class
if (class_exists('finfo')) { if (class_exists('finfo')) {
$finfo = new \finfo(); $finfo = new finfo();
return $finfo->file($filePath, FILEINFO_MIME_TYPE); return $finfo->file($filePath, FILEINFO_MIME_TYPE);
} }
@@ -787,7 +777,7 @@ class MimeTypes
$message = sprintf($template, $filePath); $message = sprintf($template, $filePath);
throw new \RuntimeException($message); throw new RuntimeException($message);
} }
/** /**
@@ -804,4 +794,17 @@ class MimeTypes
return false; return false;
} }
/**
* Returns information whether file with the given path is an image
*
* @param string $path Path of the file to check
* @return bool
*/
public static function isImagePath($path)
{
$mimeType = self::getMimeType($path);
return self::isImage($mimeType);
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -23,25 +23,68 @@ use Doctrine\ORM\QueryBuilder;
class QueryBuilderUtility class QueryBuilderUtility
{ {
/** /**
* Returns root alias of given query builder. * Adds given parameters to given query builder.
* If null is returned, alias was not found. * Attention. Existing parameters will be overridden.
* *
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias * @param QueryBuilder $queryBuilder The query builder
* @return null|string * @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 * Nothing to do
*/ */
if (empty($aliases)) { if (empty($parameters)) {
return null; 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; 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 * Sets the WHERE criteria in given query builder
* *
@@ -149,69 +214,4 @@ class QueryBuilderUtility
return $queryBuilder; 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 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 array|object|string $class Class who child classes should be returned. An array of objects, strings,
* @param bool $withoutInheritance (optional) If is set to true, only methods for given class are returned. * object or string.
* Otherwise - all methods, with inherited methods too. * @return null|array
* @return 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) { // Oops, cannot resolve class
if ($method instanceof ReflectionMethod) { if (null === $className) {
if ($withoutInheritance && $className !== $method->class) { throw CannotResolveClassNameException::create('');
}
$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; continue;
} }
$effect[] = $method->name; $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 object|string $class The object or name of object's class
* @param string $method Name of the method to find * @param bool $withoutInheritance (optional) If is set to true, only methods for given class are returned.
* @return bool * 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 array|object|string $parentClass Class who child class should be returned. An array of objects,
* @param string $property Name of the property to find * namespaces, object or namespace.
* @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
* @return mixed * @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; 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 object|string $class The object or name of object's class
* @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise - * @param string $constant Name of the constant to find
* 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
* @return bool * @return bool
*/ */
public static function isInterfaceImplemented($source, string $interface): bool public static function hasConstant($class, string $constant): bool
{ {
$className = self::getClassName($source); $reflection = new ReflectionClass($class);
$interfaces = class_implements($className);
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 array|object|string $source An array of objects, namespaces, object or namespace
* @param int $filter (optional) Filter of properties. Uses \ReflectionProperty class * @param string $interface The interface that should be implemented
* constants. By default all properties are returned. * @return bool
* @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 public static function isInterfaceImplemented($source, string $interface): bool
{ {
$className = self::getClassName($source); $className = self::getClassName($source);
$reflection = new ReflectionClass($className); $interfaces = class_implements($className);
if (null === $filter) { return in_array($interface, $interfaces, true);
$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 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 * @param mixed $object Object that should contains given property
* @return false|ReflectionClass * @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 * Nothing to do
*/ */
if (empty($allClasses)) { if (empty($propertiesValues)) {
return null; return;
} }
$className = self::getClassName($class); foreach ($propertiesValues as $property => $value) {
static::setPropertyValue($object, $property, $value);
// Oops, cannot resolve class
if (null === $className) {
throw CannotResolveClassNameException::create('');
} }
$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. * Sets value of given property in given object
* Extended class should has only one child class.
* *
* @param array|object|string $parentClass Class who child class should be returned. An array of objects, * @param mixed $object Object that should contains given property
* namespaces, object or namespace.
* @return mixed
* @throws TooManyChildClassesException|MissingChildClassesException|CannotResolveClassNameException
*/
public static function getOneChildClass($parentClass)
{
$childClasses = self::getChildClasses($parentClass);
/*
* 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 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 string $property Name of the property
* @param int|null $filter (optional) Filter of properties. Uses \ReflectionProperty class constants. * @param mixed $value Value of the property
* By default all properties are allowed / processed. * @throws NotExistingPropertyException
* @return null|ReflectionProperty
*/ */
public static function getProperty($class, string $property, int $filter = null): ?ReflectionProperty public static function setPropertyValue($object, string $property, $value): void
{ {
$className = self::getClassName($class); $reflectionProperty = self::getProperty($object, $property);
$properties = self::getProperties($className, $filter);
if (!empty($properties)) { // Oops, property does not exist
foreach ($properties as $reflectionProperty) { if (null === $reflectionProperty) {
if ($reflectionProperty->getName() === $property) { throw NotExistingPropertyException::create($object, $property);
return $reflectionProperty;
}
}
} }
return null; $isPublic = $reflectionProperty->isPublic();
if (!$isPublic) {
$reflectionProperty->setAccessible(true);
}
$reflectionProperty->setValue($object, $value);
if (!$isPublic) {
$reflectionProperty->setAccessible(false);
}
} }
/** /**
@@ -563,135 +634,6 @@ class Reflection
return $uses; 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 * Returns value of given property using getter of the property
* *
@@ -828,4 +770,62 @@ class Reflection
return null; 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'; 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 * 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 * Returns information if given item is sortable
* *

View File

@@ -16,6 +16,45 @@ namespace Meritoo\Common\Utilities;
*/ */
class Uri 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 * Returns full uri string
* *
@@ -45,35 +84,6 @@ class Uri
return self::getServerNameOrIp(true).$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;
}
/** /**
* Returns protocol name * Returns protocol name
* *
@@ -108,6 +118,69 @@ class Uri
return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_REFERER'); 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 * Returns user's IP address
* *
@@ -118,6 +191,59 @@ class Uri
return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'REMOTE_ADDR'); return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'REMOTE_ADDR');
} }
/**
* Returns name of user's operating system
*
* @return string
*/
public static function getUserOperatingSystemName()
{
$info = self::getUserWebBrowserInfo();
$knownSystems = [
'Linux' => 'Linux',
'Win' => 'Windows',
'Mac' => 'Mac OS',
];
foreach ($knownSystems as $pattern => $systemName) {
$matches = [];
$matchCount = preg_match(sprintf('|%s|', $pattern), $info, $matches);
if ($matchCount > 0) {
return $systemName;
}
}
return '';
}
/**
* Returns user's web browser information
*
* @return string
*
* Examples:
* - Mozilla Firefox:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0'
*
* - Google Chrome:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95
* Safari/537.36'
*
* - Opera:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65
* Safari/537.36 OPR/26.0.1656.24'
*
* - Apple Safari:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like Gecko) Version/8.0.2
* Safari/600.2.5'
*/
public static function getUserWebBrowserInfo()
{
return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_USER_AGENT');
}
/** /**
* Returns name and version of user's web browser * Returns name and version of user's web browser
* *
@@ -154,75 +280,6 @@ class Uri
return ''; return '';
} }
/**
* Returns user's web browser information
*
* @return string
*
* Examples:
* - Mozilla Firefox:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0'
*
* - Google Chrome:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95
* Safari/537.36'
*
* - Opera:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65
* Safari/537.36 OPR/26.0.1656.24'
*
* - Apple Safari:
* 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like Gecko) Version/8.0.2
* Safari/600.2.5'
*/
public static function getUserWebBrowserInfo()
{
return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_USER_AGENT');
}
/**
* Returns name of user's operating system
*
* @return string
*/
public static function getUserOperatingSystemName()
{
$info = self::getUserWebBrowserInfo();
$knownSystems = [
'Linux' => 'Linux',
'Win' => 'Windows',
'Mac' => 'Mac OS',
];
foreach ($knownSystems as $pattern => $systemName) {
$matches = [];
$matchCount = preg_match(sprintf('|%s|', $pattern), $info, $matches);
if ($matchCount > 0) {
return $systemName;
}
}
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 * Returns information if given url is external, from another server / domain
* *
@@ -260,6 +317,22 @@ class Uri
return !Regex::contains($url, $currentUrlPattern); 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 * Replenishes protocol in the given url
* *
@@ -298,77 +371,4 @@ class Uri
return sprintf('%s://%s', $protocol, $url); 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 * @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 * @return string
*/ */
public function getBuildingNumber() public function getStreet()
{ {
return $this->buildingNumber; return $this->street;
}
/**
* Returns number of flat
*
* @return string
*/
public function getFlatNumber()
{
return $this->flatNumber;
} }
/** /**
@@ -146,14 +156,4 @@ class Address
{ {
return $this->zipCode; 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); return Arrays::getNonEmptyValuesAsString($values);
} }
/**
* Returns name of bank
*
* @return string
*/
public function getBankName()
{
return $this->bankName;
}
/** /**
* Returns number of bank's account * Returns number of bank's account
* *
@@ -78,4 +68,14 @@ class BankAccount
{ {
return $this->accountNumber; 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); return Arrays::getNonEmptyValuesAsString($values);
} }
/**
* Returns name of company
*
* @return string
*/
public function getName()
{
return $this->name;
}
/** /**
* Returns address of company * Returns address of company
* *
@@ -98,4 +88,14 @@ class Company
{ {
return $this->bankAccount; return $this->bankAccount;
} }
/**
* Returns name of company
*
* @return string
*/
public function getName()
{
return $this->name;
}
} }

View File

@@ -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 * @return Size
*/ */
public function setSeparator($separator) public function setHeight($height)
{ {
$this->separator = $separator; $this->height = (int) $height;
return $this; return $this;
} }
@@ -130,49 +200,18 @@ class Size
} }
/** /**
* 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 * @param string $separator The separator
* (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 * @return Size
*/ */
public function setHeight($height) public function setSeparator($separator)
{ {
$this->height = (int)$height; $this->separator = $separator;
return $this; 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. * Returns instance of this class as an array.
* Values of the array are width and height, eg. [800, 600] or ['800px', '600px']. * 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 bool $withUnit (optional) If is set to true, width and height are returned with unit ("px"). Otherwise
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px". * - without (default behaviour).
* @param string $separator (optional) Separator used to split width and height. Default: " x ". * @return string
* @return null|Size
*/ */
public static function fromString($size, $unit = 'px', $separator = ' x ') public function toString($withUnit = false)
{ {
if (is_string($size)) { $width = $this->getWidth($withUnit);
$matches = []; $height = $this->getHeight($withUnit);
$pattern = Regex::getSizePattern($separator);
if ((bool)preg_match($pattern, $size, $matches)) { return sprintf('%s%s%s', $width, $this->separator, $height);
$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;
} }
} }

View File

@@ -54,8 +54,8 @@ class Template
* Returns content of the template filled with given values (by replacing placeholders with their proper values) * 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 * @param array $values Pairs of key-value where: key - name of placeholder, value - value of the placeholder
* @throws MissingPlaceholdersInValuesException
* @return string * @return string
* @throws MissingPlaceholdersInValuesException
*/ */
public function fill(array $values): string public function fill(array $values): string
{ {
@@ -82,41 +82,6 @@ class Template
return $result; 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 * Returns regular expression that defines format of placeholder
* *
@@ -148,4 +113,39 @@ class Template
static::PLACEHOLDER_TAG 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. * Returns new instance based on given version as array.
* Incremented when you make incompatible API changes. * 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;
} }
/** $count = count($version);
* Returns the "minor" part.
* Incremented when you add functionality in a backwards-compatible manner. /*
* * Incorrect version?
* @return int * Nothing to do
*/ */
public function getMinorPart() if (3 !== $count) {
{ return null;
return $this->minorPart;
} }
/** $majorPart = (int) $version[0];
* Returns the "patch" part. $minorPart = (int) $version[1];
* Incremented when you make backwards-compatible bug fixes. $patchPart = (int) $version[2];
*
* @return int return new static($majorPart, $minorPart, $patchPart);
*/
public function getPatchPart()
{
return $this->patchPart;
} }
/** /**
@@ -140,40 +145,35 @@ class Version
} }
/** /**
* Returns new instance based on given version as array. * Returns the "major" part.
* Given version should contain 3 integers, 1 per each part ("major", "minor" and "patch"). * Incremented when you make incompatible API changes.
* *
* Examples: * @return int
* [1, 0, 2];
* [10, 4, 0];
*
* @param array $version The version
* @return null|Version
*/ */
public static function fromArray(array $version) public function getMajorPart()
{ {
/* return $this->majorPart;
* No version provided? }
* Nothing to do
/**
* Returns the "minor" part.
* Incremented when you add functionality in a backwards-compatible manner.
*
* @return int
*/ */
if (empty($version)) { public function getMinorPart()
return null; {
return $this->minorPart;
} }
$count = count($version); /**
* Returns the "patch" part.
/* * Incremented when you make backwards-compatible bug fixes.
* Incorrect version? *
* Nothing to do * @return int
*/ */
if (3 !== $count) { public function getPatchPart()
return null; {
} return $this->patchPart;
$majorPart = (int)$version[0];
$minorPart = (int)$version[1];
$patchPart = (int)$version[2];
return new static($majorPart, $minorPart, $patchPart);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -27,31 +27,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class DateTimeCollectionTest extends BaseTestCase class DateTimeCollectionTest extends BaseTestCase
{ {
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
DateTimeCollection::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @param string $description
* @param array $elements
* @param array $expectedElements
*
* @dataProvider provideDifferentTypesOfElements
*/
public function testCreateWithDifferentTypesOfElements(
string $description,
array $elements,
array $expectedElements
): void {
$collection = new DateTimeCollection($elements);
static::assertEquals($expectedElements, $collection->toArray(), $description);
}
public function provideDifferentTypesOfElements(): ?Generator public function provideDifferentTypesOfElements(): ?Generator
{ {
yield [ yield [
@@ -89,4 +64,29 @@ class DateTimeCollectionTest extends BaseTestCase
], ],
]; ];
} }
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
DateTimeCollection::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @param string $description
* @param array $elements
* @param array $expectedElements
*
* @dataProvider provideDifferentTypesOfElements
*/
public function testCreateWithDifferentTypesOfElements(
string $description,
array $elements,
array $expectedElements
): void {
$collection = new DateTimeCollection($elements);
static::assertEquals($expectedElements, $collection->toArray(), $description);
}
} }

View File

@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Meritoo\Test\Common\Collection; namespace Meritoo\Test\Common\Collection;
use Generator;
use Meritoo\Common\Collection\IntegerCollection; use Meritoo\Common\Collection\IntegerCollection;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
@@ -25,32 +26,7 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class IntegerCollectionTest extends BaseTestCase class IntegerCollectionTest extends BaseTestCase
{ {
public function testConstructor(): void public function provideDifferentTypesOfElements(): ?Generator
{
static::assertConstructorVisibilityAndArguments(
IntegerCollection::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @param string $description
* @param array $elements
* @param array $expectedElements
*
* @dataProvider provideDifferentTypesOfElements
*/
public function testCreateWithDifferentTypesOfElements(
string $description,
array $elements,
array $expectedElements
): void {
$collection = new IntegerCollection($elements);
static::assertSame($expectedElements, $collection->toArray(), $description);
}
public function provideDifferentTypesOfElements(): ?\Generator
{ {
yield [ yield [
'An empty array', 'An empty array',
@@ -88,4 +64,29 @@ class IntegerCollectionTest extends BaseTestCase
], ],
]; ];
} }
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
IntegerCollection::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @param string $description
* @param array $elements
* @param array $expectedElements
*
* @dataProvider provideDifferentTypesOfElements
*/
public function testCreateWithDifferentTypesOfElements(
string $description,
array $elements,
array $expectedElements
): void {
$collection = new IntegerCollection($elements);
static::assertSame($expectedElements, $collection->toArray(), $description);
}
} }

View File

@@ -10,6 +10,7 @@ declare(strict_types=1);
namespace Meritoo\Test\Common\Collection; namespace Meritoo\Test\Common\Collection;
use Generator;
use Meritoo\Common\Collection\StringCollection; use Meritoo\Common\Collection\StringCollection;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
@@ -25,32 +26,7 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class StringCollectionTest extends BaseTestCase class StringCollectionTest extends BaseTestCase
{ {
public function testConstructor(): void public function provideDifferentTypesOfElements(): ?Generator
{
static::assertConstructorVisibilityAndArguments(
StringCollection::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @param string $description
* @param array $elements
* @param array $expectedElements
*
* @dataProvider provideDifferentTypesOfElements
*/
public function testCreateWithDifferentTypesOfElements(
string $description,
array $elements,
array $expectedElements
): void {
$collection = new StringCollection($elements);
static::assertSame($expectedElements, $collection->toArray(), $description);
}
public function provideDifferentTypesOfElements(): ?\Generator
{ {
yield [ yield [
'An empty array', 'An empty array',
@@ -89,4 +65,29 @@ class StringCollectionTest extends BaseTestCase
], ],
]; ];
} }
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
StringCollection::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @param string $description
* @param array $elements
* @param array $expectedElements
*
* @dataProvider provideDifferentTypesOfElements
*/
public function testCreateWithDifferentTypesOfElements(
string $description,
array $elements,
array $expectedElements
): void {
$collection = new StringCollection($elements);
static::assertSame($expectedElements, $collection->toArray(), $description);
}
} }

View File

@@ -26,70 +26,6 @@ use Meritoo\Common\ValueObject\Template;
*/ */
class TemplatesTest extends BaseTestCase class TemplatesTest extends BaseTestCase
{ {
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
Templates::class,
OopVisibilityType::IS_PUBLIC,
1
);
}
/**
* @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
*
* @dataProvider provideArrayWithTemplates
*/
public function testFromArray(string $description, array $templates, Templates $expected): void
{
static::assertEquals($expected, Templates::fromArray($templates), $description);
}
public function testFindTemplateUsingEmptyCollection(): void
{
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
$message = sprintf($template, 'test');
$this->expectException(TemplateNotFoundException::class);
$this->expectExceptionMessage($message);
$templates = new Templates();
$templates->findTemplate('test');
}
/**
* @param Templates $templates All templates
* @param string $index Index that contains required template
* @param string $expectedMessage Expected message of exception
*
* @dataProvider provideTemplatesWithNotExistingIndex
*/
public function testFindTemplateUsingNotExistingIndex(
Templates $templates,
string $index,
string $expectedMessage
): void {
$this->expectException(TemplateNotFoundException::class);
$this->expectExceptionMessage($expectedMessage);
$templates->findTemplate($index);
}
/**
* @param string $description Description of test
* @param Templates $templates All templates
* @param string $index Index that contains required template
* @param Template $expected Expected template
*
* @dataProvider provideTemplatesToFind
*/
public function testFindTemplate(string $description, Templates $templates, string $index, Template $expected): void
{
static::assertEquals($expected, $templates->findTemplate($index), $description);
}
public function provideArrayWithTemplates(): ?Generator public function provideArrayWithTemplates(): ?Generator
{ {
yield [ yield [
@@ -123,6 +59,31 @@ class TemplatesTest extends BaseTestCase
]; ];
} }
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 public function provideTemplatesWithNotExistingIndex(): ?Generator
{ {
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?'; $template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
@@ -161,28 +122,67 @@ class TemplatesTest extends BaseTestCase
]; ];
} }
public function provideTemplatesToFind(): ?Generator public function testConstructor(): void
{ {
yield[ static::assertConstructorVisibilityAndArguments(
'2 templates only', Templates::class,
new Templates([ OopVisibilityType::IS_PUBLIC,
'first' => new Template('First name: %first_name%'), 1
'last' => new Template('Last name: %last_name%'), );
]), }
'first',
new Template('First name: %first_name%'),
];
yield[ /**
'Different indexes', * @param string $description Description of test
new Templates([ * @param Templates $templates All templates
'first' => new Template('First name: %first_name%'), * @param string $index Index that contains required template
'last' => new Template('Last name: %last_name%'), * @param Template $expected Expected template
1 => new Template('Hi %name%, how are you?'), *
'2' => new Template('Your score is: %score%'), * @dataProvider provideTemplatesToFind
]), */
'1', public function testFindTemplate(string $description, Templates $templates, string $index, Template $expected): void
new Template('Hi %name%, how are you?'), {
]; static::assertEquals($expected, $templates->findTemplate($index), $description);
}
public function testFindTemplateUsingEmptyCollection(): void
{
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
$message = sprintf($template, 'test');
$this->expectException(TemplateNotFoundException::class);
$this->expectExceptionMessage($message);
$templates = new Templates();
$templates->findTemplate('test');
}
/**
* @param Templates $templates All templates
* @param string $index Index that contains required template
* @param string $expectedMessage Expected message of exception
*
* @dataProvider provideTemplatesWithNotExistingIndex
*/
public function testFindTemplateUsingNotExistingIndex(
Templates $templates,
string $index,
string $expectedMessage
): void {
$this->expectException(TemplateNotFoundException::class);
$this->expectExceptionMessage($expectedMessage);
$templates->findTemplate($index);
}
/**
* @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
*
* @dataProvider provideArrayWithTemplates
*/
public function testFromArray(string $description, array $templates, Templates $expected): void
{
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); static::assertConstructorVisibilityAndArguments(UnknownTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
} }
public function testWithoutException()
{
self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2'));
}
public function testTheException() public function testTheException()
{ {
$this->expectException(UnknownTestTypeException::class); $this->expectException(UnknownTestTypeException::class);
self::assertEmpty((new TestService())->getTranslatedType('test_3')); 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) * Returns translated type (for testing purposes)
* *
* @param string $type Type of something (for testing purposes) * @param string $type Type of something (for testing purposes)
* @throws UnknownTestTypeException
* @return string * @return string
* @throws UnknownTestTypeException
*/ */
public function getTranslatedType(string $type): string public function getTranslatedType(string $type): string
{ {

View File

@@ -24,28 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class IncorrectBundleNameExceptionTest extends BaseTestCase class IncorrectBundleNameExceptionTest extends BaseTestCase
{ {
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
IncorrectBundleNameException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $bundleName Incorrect name of bundle
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideBundleNameAndMessage
*/
public function testCreate(string $description, string $bundleName, string $expectedMessage): void
{
$exception = IncorrectBundleNameException::create($bundleName);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideBundleNameAndMessage(): Generator public function provideBundleNameAndMessage(): Generator
{ {
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is' $template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
@@ -69,4 +47,26 @@ class IncorrectBundleNameExceptionTest extends BaseTestCase
sprintf($template, 'ThisIsTest'), sprintf($template, 'ThisIsTest'),
]; ];
} }
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
IncorrectBundleNameException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $bundleName Incorrect name of bundle
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideBundleNameAndMessage
*/
public function testCreate(string $description, string $bundleName, string $expectedMessage): void
{
$exception = IncorrectBundleNameException::create($bundleName);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
} }

View File

@@ -25,24 +25,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class UnknownDatePartTypeExceptionTest extends BaseTestCase class UnknownDatePartTypeExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownDatePartTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $unknownDatePart Type of date part, e.g. "year". One of DatePartType class constants.
* @param string $value Incorrect value
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideDatePartAndValue
*/
public function testMessage($unknownDatePart, $value, $expectedMessage)
{
$exception = UnknownDatePartTypeException::createException($unknownDatePart, $value);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides type of date part, incorrect value and expected exception's message * Provides type of date part, incorrect value and expected exception's message
* *
@@ -71,4 +53,22 @@ class UnknownDatePartTypeExceptionTest extends BaseTestCase
sprintf($template, DatePartType::MINUTE, '77'), sprintf($template, DatePartType::MINUTE, '77'),
]; ];
} }
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownDatePartTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $unknownDatePart Type of date part, e.g. "year". One of DatePartType class constants.
* @param string $value Incorrect value
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideDatePartAndValue
*/
public function testMessage($unknownDatePart, $value, $expectedMessage)
{
$exception = UnknownDatePartTypeException::createException($unknownDatePart, $value);
static::assertSame($expectedMessage, $exception->getMessage());
}
} }

View File

@@ -24,23 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class EmptyFileExceptionTest extends BaseTestCase class EmptyFileExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $emptyFilePath Path of the empty file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testMessage($emptyFilePath, $expectedMessage)
{
$exception = EmptyFileException::create($emptyFilePath);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides path of the empty file and expected exception's message * Provides path of the empty file and expected exception's message
* *
@@ -60,4 +43,21 @@ class EmptyFileExceptionTest extends BaseTestCase
sprintf($template, 'images/show/car.jpg'), sprintf($template, 'images/show/car.jpg'),
]; ];
} }
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $emptyFilePath Path of the empty file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testMessage($emptyFilePath, $expectedMessage)
{
$exception = EmptyFileException::create($emptyFilePath);
static::assertSame($expectedMessage, $exception->getMessage());
}
} }

View File

@@ -23,14 +23,14 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class EmptyFilePathExceptionTest extends BaseTestCase class EmptyFilePathExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFilePathException::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testConstructorMessage() public function testConstructorMessage()
{ {
$exception = EmptyFilePathException::create(); $exception = EmptyFilePathException::create();
static::assertSame('Path of the file is empty. Did you provide path of proper file?', $exception->getMessage()); 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

@@ -24,23 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class NotExistingFileExceptionTest extends BaseTestCase class NotExistingFileExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(NotExistingFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $notExistingFilePath Path of not existing (or not readable) file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testConstructorMessage($notExistingFilePath, $expectedMessage)
{
$exception = NotExistingFileException::create($notExistingFilePath);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides path of not existing file and expected exception's message * Provides path of not existing file and expected exception's message
* *
@@ -60,4 +43,21 @@ class NotExistingFileExceptionTest extends BaseTestCase
sprintf($template, 'images/show/car.jpg'), sprintf($template, 'images/show/car.jpg'),
]; ];
} }
/**
* @param string $notExistingFilePath Path of not existing (or not readable) file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testConstructorMessage($notExistingFilePath, $expectedMessage)
{
$exception = NotExistingFileException::create($notExistingFilePath);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(NotExistingFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
} }

View File

@@ -24,25 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class DisabledMethodExceptionTest extends BaseTestCase class DisabledMethodExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(DisabledMethodException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $disabledMethod Name of the disabled method
* @param string $alternativeMethod Name of the alternative method
* @param string $expectedMessage Expected exception's message
*
* @internal param string $emptyFilePath Path of the empty file
* @dataProvider provideMethodsNames
*/
public function testConstructorMessage($disabledMethod, $alternativeMethod, $expectedMessage)
{
$exception = DisabledMethodException::create($disabledMethod, $alternativeMethod);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides name of the disabled method, name of the alternative method and expected exception's message * Provides name of the disabled method, name of the alternative method and expected exception's message
* *
@@ -65,4 +46,23 @@ class DisabledMethodExceptionTest extends BaseTestCase
sprintf($templateLong, 'FooBar::loremIpsum', 'AnotherClass::alternativeMethod'), sprintf($templateLong, 'FooBar::loremIpsum', 'AnotherClass::alternativeMethod'),
]; ];
} }
/**
* @param string $disabledMethod Name of the disabled method
* @param string $alternativeMethod Name of the alternative method
* @param string $expectedMessage Expected exception's message
*
* @internal param string $emptyFilePath Path of the empty file
* @dataProvider provideMethodsNames
*/
public function testConstructorMessage($disabledMethod, $alternativeMethod, $expectedMessage)
{
$exception = DisabledMethodException::create($disabledMethod, $alternativeMethod);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(DisabledMethodException::class, OopVisibilityType::IS_PUBLIC, 3);
}
} }

View File

@@ -25,37 +25,6 @@ use stdClass;
*/ */
class CannotResolveClassNameExceptionTest extends BaseTestCase class CannotResolveClassNameExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
CannotResolveClassNameException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
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.
* Otherwise - for trait.
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideClassName
*/
public function testCreate(string $source, bool $forClass, string $expectedMessage): void
{
$exception = CannotResolveClassNameException::create($source, $forClass);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides source of the class's / trait's name, information if message of this exception should be prepared for * 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 * class and the expected exception's message
@@ -82,4 +51,35 @@ class CannotResolveClassNameExceptionTest extends BaseTestCase
'Name of class from given \'string\' stdClass cannot be resolved. Is there everything ok?', 'Name of class from given \'string\' stdClass cannot be resolved. Is there everything ok?',
]; ];
} }
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
CannotResolveClassNameException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @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.
* Otherwise - for trait.
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideClassName
*/
public function testCreate(string $source, bool $forClass, string $expectedMessage): void
{
$exception = CannotResolveClassNameException::create($source, $forClass);
static::assertSame($expectedMessage, $exception->getMessage());
}
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());
}
} }

View File

@@ -25,6 +25,23 @@ use Meritoo\Common\Utilities\Arrays;
*/ */
class ClassWithoutConstructorExceptionTest extends BaseTestCase 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 public function testConstructor(): void
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -46,21 +63,4 @@ class ClassWithoutConstructorExceptionTest extends BaseTestCase
$exception = ClassWithoutConstructorException::create($className); $exception = ClassWithoutConstructorException::create($className);
static::assertSame($expectedMessage, $exception->getMessage(), $description); 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\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/** /**
* Test case of an exception used while given class has no child classes * 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 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 public function testConstructorVisibilityAndArguments(): void
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -45,28 +70,4 @@ class MissingChildClassesExceptionTest extends BaseTestCase
$exception = MissingChildClassesException::create($parentClass); $exception = MissingChildClassesException::create($parentClass);
static::assertSame($expectedMessage, $exception->getMessage()); 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; namespace Meritoo\Test\Common\Exception\Reflection;
use Generator;
use Meritoo\Common\Exception\Reflection\NotExistingPropertyException; use Meritoo\Common\Exception\Reflection\NotExistingPropertyException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/** /**
* Class NotExistingPropertyExceptionTest * Class NotExistingPropertyExceptionTest
@@ -23,6 +25,39 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class NotExistingPropertyExceptionTest extends BaseTestCase 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 public function testConstructor(): void
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -45,37 +80,4 @@ class NotExistingPropertyExceptionTest extends BaseTestCase
$exception = NotExistingPropertyException::create($object, $property); $exception = NotExistingPropertyException::create($object, $property);
static::assertSame($expectedMessage, $exception->getMessage(), $description); 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\Exception\Reflection\TooManyChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use stdClass;
/** /**
* Test case of an exception used while given class has more than one child class * 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 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 public function testConstructor(): void
{ {
static::assertConstructorVisibilityAndArguments( static::assertConstructorVisibilityAndArguments(
@@ -46,36 +79,4 @@ class TooManyChildClassesExceptionTest extends BaseTestCase
$exception = TooManyChildClassesException::create($parentClass, $childClasses); $exception = TooManyChildClassesException::create($parentClass, $childClasses);
static::assertSame($expectedMessage, $exception->getMessage()); 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

@@ -24,23 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class IncorrectColorHexLengthExceptionTest extends BaseTestCase class IncorrectColorHexLengthExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(IncorrectColorHexLengthException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $color Incorrect hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = IncorrectColorHexLengthException::create($color);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides incorrect hexadecimal value of color and expected exception's message * Provides incorrect hexadecimal value of color and expected exception's message
* *
@@ -60,4 +43,21 @@ class IncorrectColorHexLengthExceptionTest extends BaseTestCase
sprintf($template, 'aa-bb-cc', strlen('aa-bb-cc')), sprintf($template, 'aa-bb-cc', strlen('aa-bb-cc')),
]; ];
} }
/**
* @param string $color Incorrect hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = IncorrectColorHexLengthException::create($color);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(IncorrectColorHexLengthException::class, OopVisibilityType::IS_PUBLIC, 3);
}
} }

View File

@@ -24,23 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class InvalidColorHexValueExceptionTest extends BaseTestCase class InvalidColorHexValueExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidColorHexValueException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $color Invalid hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = InvalidColorHexValueException::create($color);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides invalid hexadecimal value of color and expected exception's message * Provides invalid hexadecimal value of color and expected exception's message
* *
@@ -60,4 +43,21 @@ class InvalidColorHexValueExceptionTest extends BaseTestCase
sprintf($template, 'aa-bb-cc'), sprintf($template, 'aa-bb-cc'),
]; ];
} }
/**
* @param string $color Invalid hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = InvalidColorHexValueException::create($color);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidColorHexValueException::class, OopVisibilityType::IS_PUBLIC, 3);
}
} }

View File

@@ -24,23 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class InvalidHtmlAttributesExceptionTest extends BaseTestCase class InvalidHtmlAttributesExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidHtmlAttributesException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $htmlAttributes Invalid html attributes
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideHtmlAttributes
*/
public function testConstructorMessage($htmlAttributes, $expectedMessage)
{
$exception = InvalidHtmlAttributesException::create($htmlAttributes);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides html attributes * Provides html attributes
* *
@@ -65,4 +48,21 @@ class InvalidHtmlAttributesExceptionTest extends BaseTestCase
sprintf($template, 'abc=def ghi=jkl'), sprintf($template, 'abc=def ghi=jkl'),
]; ];
} }
/**
* @param string $htmlAttributes Invalid html attributes
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideHtmlAttributes
*/
public function testConstructorMessage($htmlAttributes, $expectedMessage)
{
$exception = InvalidHtmlAttributesException::create($htmlAttributes);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidHtmlAttributesException::class, OopVisibilityType::IS_PUBLIC, 3);
}
} }

View File

@@ -24,23 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class InvalidUrlExceptionTest extends BaseTestCase class InvalidUrlExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidUrlException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $url Invalid url
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUrl
*/
public function testConstructorMessage($url, $expectedMessage)
{
$exception = InvalidUrlException::create($url);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides invalid url and expected exception's message * Provides invalid url and expected exception's message
* *
@@ -60,4 +43,21 @@ class InvalidUrlExceptionTest extends BaseTestCase
sprintf($template, 'http:/images\show\car.jpg'), sprintf($template, 'http:/images\show\car.jpg'),
]; ];
} }
/**
* @param string $url Invalid url
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUrl
*/
public function testConstructorMessage($url, $expectedMessage)
{
$exception = InvalidUrlException::create($url);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidUrlException::class, OopVisibilityType::IS_PUBLIC, 3);
}
} }

View File

@@ -25,27 +25,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
UnknownOopVisibilityTypeException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $unknownType Unknown OOP-related visibility
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUnknownType
*/
public function testConstructorMessage($unknownType, $expectedMessage): void
{
$exception = UnknownOopVisibilityTypeException::createException($unknownType);
static::assertSame($expectedMessage, $exception->getMessage());
}
/** /**
* Provides path of the empty file and expected exception's message * Provides path of the empty file and expected exception's message
* *
@@ -68,4 +47,25 @@ class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
sprintf($template, 123, implode(', ', $allTypes)), sprintf($template, 123, implode(', ', $allTypes)),
]; ];
} }
/**
* @param string $unknownType Unknown OOP-related visibility
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUnknownType
*/
public function testConstructorMessage($unknownType, $expectedMessage): void
{
$exception = UnknownOopVisibilityTypeException::createException($unknownType);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
UnknownOopVisibilityTypeException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
} }

View File

@@ -23,28 +23,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class InvalidSizeDimensionsExceptionTest extends BaseTestCase class InvalidSizeDimensionsExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(
InvalidSizeDimensionsException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param int $width The width
* @param int $height The height
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideWidthAndHeight
*/
public function testCreate($width, $height, $expectedMessage)
{
$exception = InvalidSizeDimensionsException::create($width, $height);
static::assertSame($expectedMessage, $exception->getMessage());
}
public function provideWidthAndHeight() public function provideWidthAndHeight()
{ {
$template = 'Dimensions of size should be positive, but they are not: %d, %d. Is there everything ok?'; $template = 'Dimensions of size should be positive, but they are not: %d, %d. Is there everything ok?';
@@ -67,4 +45,26 @@ class InvalidSizeDimensionsExceptionTest extends BaseTestCase
sprintf($template, 200, 100), sprintf($template, 200, 100),
]; ];
} }
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(
InvalidSizeDimensionsException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param int $width The width
* @param int $height The height
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideWidthAndHeight
*/
public function testCreate($width, $height, $expectedMessage)
{
$exception = InvalidSizeDimensionsException::create($width, $height);
static::assertSame($expectedMessage, $exception->getMessage());
}
} }

View File

@@ -24,28 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class InvalidContentExceptionTest extends BaseTestCase class InvalidContentExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
InvalidContentException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $content Invalid content of template
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideContent
*/
public function testCreate(string $description, string $content, string $expectedMessage): void
{
$exception = InvalidContentException::create($content);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
public function provideContent(): ?Generator public function provideContent(): ?Generator
{ {
$template = 'Content of template \'%s\' is invalid. Did you use string with 1 placeholder at least?'; $template = 'Content of template \'%s\' is invalid. Did you use string with 1 placeholder at least?';
@@ -68,4 +46,26 @@ class InvalidContentExceptionTest extends BaseTestCase
sprintf($template, '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(
InvalidContentException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $content Invalid content of template
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideContent
*/
public function testCreate(string $description, string $content, string $expectedMessage): void
{
$exception = InvalidContentException::create($content);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
} }

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Exception\ValueObject\Template; namespace Meritoo\Test\Common\Exception\ValueObject\Template;
use Generator;
use Meritoo\Common\Exception\ValueObject\Template\MissingPlaceholdersInValuesException; use Meritoo\Common\Exception\ValueObject\Template\MissingPlaceholdersInValuesException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
@@ -23,34 +24,7 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class MissingPlaceholdersInValuesExceptionTest extends BaseTestCase class MissingPlaceholdersInValuesExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments(): void public function provideContentAndMissingPlaceholders(): ?Generator
{
static::assertConstructorVisibilityAndArguments(
MissingPlaceholdersInValuesException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $content Content of template
* @param array $missingPlaceholders Missing placeholders in provided values, iow. placeholders without values
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideContentAndMissingPlaceholders
*/
public function testCreate(
string $description,
string $content,
array $missingPlaceholders,
string $expectedMessage
): void {
$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' $template = 'Cannot fill template \'%s\', because of missing values for placeholder(s): %s. Did you provide all'
.' required values?'; .' required values?';
@@ -82,4 +56,31 @@ class MissingPlaceholdersInValuesExceptionTest extends BaseTestCase
), ),
]; ];
} }
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
MissingPlaceholdersInValuesException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $content Content of template
* @param array $missingPlaceholders Missing placeholders in provided values, iow. placeholders without values
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideContentAndMissingPlaceholders
*/
public function testCreate(
string $description,
string $content,
array $missingPlaceholders,
string $expectedMessage
): void {
$exception = MissingPlaceholdersInValuesException::create($content, $missingPlaceholders);
static::assertSame($expectedMessage, $exception->getMessage(), $description);
}
} }

View File

@@ -24,28 +24,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class TemplateNotFoundExceptionTest extends BaseTestCase class TemplateNotFoundExceptionTest extends BaseTestCase
{ {
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
TemplateNotFoundException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $index Index that should contain template, but it was not found
* @param TemplateNotFoundException $expected Expected exception
*
* @dataProvider provideIndexAndException
*/
public function testCreate(string $description, string $index, TemplateNotFoundException $expected): void
{
$created = TemplateNotFoundException::create($index);
static::assertEquals($expected, $created, $description);
}
public function provideIndexAndException(): ?Generator public function provideIndexAndException(): ?Generator
{ {
$template = 'Template with \'%s\' index was not found. Did you provide all required templates?'; $template = 'Template with \'%s\' index was not found. Did you provide all required templates?';
@@ -68,4 +46,26 @@ class TemplateNotFoundExceptionTest extends BaseTestCase
new TemplateNotFoundException(sprintf($template, 2)), new TemplateNotFoundException(sprintf($template, 2)),
]; ];
} }
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
TemplateNotFoundException::class,
OopVisibilityType::IS_PUBLIC,
3
);
}
/**
* @param string $description Description of test
* @param string $index Index that should contain template, but it was not found
* @param TemplateNotFoundException $expected Expected exception
*
* @dataProvider provideIndexAndException
*/
public function testCreate(string $description, string $index, TemplateNotFoundException $expected): void
{
$created = TemplateNotFoundException::create($index);
static::assertEquals($expected, $created, $description);
}
} }

View File

@@ -25,24 +25,55 @@ use Meritoo\Common\Utilities\GeneratorUtility;
*/ */
class BaseTestCaseTest extends 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() public function testConstructor()
{ {
static::assertConstructorVisibilityAndArguments(BaseTestCase::class, OopVisibilityType::IS_PUBLIC, 3); 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 = [ $path = (new SimpleTestCase())->getFilePathForTesting($fileName, $directoryPath);
[''],
[' '],
[null],
[0],
[false],
[[]],
];
$generator = (new SimpleTestCase())->provideEmptyValue(); if (!empty($directoryPath)) {
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator)); $directoryPath .= '/';
}
$expectedContains = sprintf('/data/tests/%s%s', $directoryPath, $fileName);
static::assertStringContainsString($expectedContains, $path);
} }
public function testProvideBooleanValue() public function testProvideBooleanValue()
@@ -109,6 +140,21 @@ class BaseTestCaseTest extends BaseTestCase
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator)); 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() public function testProvideNotExistingFilePath()
{ {
$elements = [ $elements = [
@@ -120,52 +166,6 @@ class BaseTestCaseTest extends BaseTestCase
$generator = (new SimpleTestCase())->provideNotExistingFilePath(); $generator = (new SimpleTestCase())->provideNotExistingFilePath();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator)); 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; 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 public function testAssertMethodVisibility(): void
{ {
$method = new ReflectionMethod(SimpleTestCase::class, 'assertMethodVisibility'); $method = new ReflectionMethod(SimpleTestCase::class, 'assertMethodVisibility');
@@ -53,54 +64,6 @@ class BaseTestCaseTraitTest extends BaseTestCase
static::assertMethodVisibility($method, OopVisibilityType::IS_PRIVATE); 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 public function testProvideBooleanValue(): void
{ {
$testCase = new SimpleTestCase(); $testCase = new SimpleTestCase();
@@ -164,19 +127,40 @@ class BaseTestCaseTraitTest extends BaseTestCase
} }
} }
public function testProvideNotExistingFilePath(): void public function testProvideEmptyScalarValue(): void
{ {
$testCase = new SimpleTestCase(); $testCase = new SimpleTestCase();
$paths = $testCase->provideNotExistingFilePath(); $values = $testCase->provideEmptyScalarValue();
$expected = [ $expected = [
['lets-test.doc'], [''],
['lorem/ipsum.jpg'], [' '],
['surprise/me/one/more/time.txt'], [null],
[0],
[false],
]; ];
foreach ($paths as $index => $path) { foreach ($values as $index => $value) {
static::assertSame($expected[$index], $path); 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); 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,45 +23,6 @@ use Meritoo\Common\Type\Base\BaseType;
*/ */
class BaseTypeTest extends BaseTestCase class BaseTypeTest extends BaseTestCase
{ {
public function testConstructor(): void
{
static::assertHasNoConstructor(BaseType::class);
}
/**
* @param BaseType $type Type of something
* @param array $expectedTypes Expected concrete types of given instance of type
*
* @dataProvider provideType
*/
public function testGetAll(BaseType $type, array $expectedTypes): void
{
$all = $type->getAll();
self::assertEquals($expectedTypes, $all);
}
/**
* @param string $toVerifyType Concrete type to verify
* @param bool $isCorrect Expected information if given type is correct
*
* @dataProvider provideTypeToVerifyUsingTestEmptyType
*/
public function testIsCorrectTypeUsingTestEmptyType(?string $toVerifyType, bool $isCorrect): void
{
self::assertEquals($isCorrect, TestEmptyType::isCorrectType($toVerifyType));
}
/**
* @param string $toVerifyType Concrete type to verify
* @param bool $isCorrect Expected information if given type is correct
*
* @dataProvider provideTypeToVerifyUsingTestType
*/
public function testIsCorrectTypeUsingTestType(?string $toVerifyType, bool $isCorrect): void
{
self::assertEquals($isCorrect, TestType::isCorrectType($toVerifyType));
}
/** /**
* Provides type of something for testing the getAll() method * Provides type of something for testing the getAll() method
* *
@@ -193,6 +154,45 @@ class BaseTypeTest extends BaseTestCase
true, true,
]; ];
} }
public function testConstructor(): void
{
static::assertHasNoConstructor(BaseType::class);
}
/**
* @param BaseType $type Type of something
* @param array $expectedTypes Expected concrete types of given instance of type
*
* @dataProvider provideType
*/
public function testGetAll(BaseType $type, array $expectedTypes): void
{
$all = $type->getAll();
self::assertEquals($expectedTypes, $all);
}
/**
* @param string $toVerifyType Concrete type to verify
* @param bool $isCorrect Expected information if given type is correct
*
* @dataProvider provideTypeToVerifyUsingTestEmptyType
*/
public function testIsCorrectTypeUsingTestEmptyType(?string $toVerifyType, bool $isCorrect): void
{
self::assertEquals($isCorrect, TestEmptyType::isCorrectType($toVerifyType));
}
/**
* @param string $toVerifyType Concrete type to verify
* @param bool $isCorrect Expected information if given type is correct
*
* @dataProvider provideTypeToVerifyUsingTestType
*/
public function testIsCorrectTypeUsingTestType(?string $toVerifyType, bool $isCorrect): void
{
self::assertEquals($isCorrect, TestType::isCorrectType($toVerifyType));
}
} }
/** /**

View File

@@ -26,94 +26,6 @@ use Meritoo\Common\Type\OopVisibilityType;
*/ */
class DatePeriodTest extends BaseTypeTestCase class DatePeriodTest extends BaseTypeTestCase
{ {
public function testConstructorVisibilityAndArguments(): void
{
static::assertConstructorVisibilityAndArguments(
DatePeriod::class,
OopVisibilityType::IS_PUBLIC,
2
);
}
/**
* @param DateTime $startDate (optional) Start date of period
* @param DateTime $endDate (optional) End date of period
*
* @dataProvider provideDatePeriod
*/
public function testConstruct(DateTime $startDate = null, DateTime $endDate = null): void
{
$period = new DatePeriod($startDate, $endDate);
self::assertEquals($startDate, $period->getStartDate());
self::assertEquals($endDate, $period->getEndDate());
}
/**
* @param DateTime $startDate (optional) Start date of period
* @param DateTime $endDate (optional) End date of period
*
* @dataProvider provideDatePeriod
*/
public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null): void
{
$period = new DatePeriod();
$period->setStartDate($startDate);
self::assertEquals($startDate, $period->getStartDate());
$period->setEndDate($endDate);
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 * Provides the start and end date of date period
* *
@@ -147,91 +59,6 @@ class DatePeriodTest extends BaseTypeTestCase
]; ];
} }
/**
* 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 * Provides period and format of date to verify
* *
@@ -301,6 +128,91 @@ class DatePeriodTest extends BaseTypeTestCase
]; ];
} }
/**
* 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} * {@inheritdoc}
*/ */
@@ -332,6 +244,94 @@ class DatePeriodTest extends BaseTypeTestCase
]; ];
} }
/**
* @param DateTime $startDate (optional) Start date of period
* @param DateTime $endDate (optional) End date of period
*
* @dataProvider provideDatePeriod
*/
public function testConstruct(DateTime $startDate = null, DateTime $endDate = null): void
{
$period = new DatePeriod($startDate, $endDate);
self::assertEquals($startDate, $period->getStartDate());
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
*
* @dataProvider provideDatePeriod
*/
public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null): void
{
$period = new DatePeriod();
$period->setStartDate($startDate);
self::assertEquals($startDate, $period->getStartDate());
$period->setEndDate($endDate);
self::assertEquals($endDate, $period->getEndDate());
}
/** /**
* Returns all expected types of the tested type * Returns all expected types of the tested type
* *

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Utilities; namespace Meritoo\Test\Common\Utilities;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Bootstrap4CssSelector; use Meritoo\Common\Utilities\Bootstrap4CssSelector;
@@ -22,125 +23,33 @@ use Meritoo\Common\Utilities\Bootstrap4CssSelector;
*/ */
class Bootstrap4CssSelectorTest extends BaseTestCase class Bootstrap4CssSelectorTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(Bootstrap4CssSelector::class);
}
/** /**
* @param string $emptyValue Name of form (value of the "name" attribute) * Provides name of form and expected selector
* @dataProvider provideEmptyScalarValue
*/
public function testGetRadioButtonErrorSelectorUsingEmptyFormName($emptyValue)
{
$fieldSetIndex = 1;
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector($emptyValue, $fieldSetIndex));
}
public function testGetRadioButtonErrorSelectorUsingNegativeFieldSetIndex()
{
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector('test-test', -1));
}
/**
* @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 provideFormNameFieldSetIndexAndSelector * @return Generator
*/ */
public function testGetRadioButtonErrorSelector($formName, $fieldSetIndex, $expected) public function provideFormNameAndSelector()
{
static::assertSame($expected, Bootstrap4CssSelector::getRadioButtonErrorSelector($formName, $fieldSetIndex));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldErrorSelectorUsingEmptyFormName($emptyValue)
{
$fieldName = 'test';
static::assertSame('', Bootstrap4CssSelector::getFieldErrorSelector($emptyValue, $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 $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 [ yield [
'test', 'test',
0, 'form[name="test"] .form-group',
'form[name="test"] fieldset:nth-of-type(0) legend.col-form-label .invalid-feedback .form-error-message',
]; ];
yield [ yield [
'test-123-test-456', 'test-123-test-456',
1, 'form[name="test-123-test-456"] .form-group',
'form[name="test-123-test-456"] fieldset:nth-of-type(1) legend.col-form-label .invalid-feedback .form-error-message',
]; ];
yield [ yield [
'test_something_098_different', 'test_something_098_different',
1245, 'form[name="test_something_098_different"] .form-group',
'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 * Provides name of form, name of field and expected selector
* *
* @return \Generator * @return Generator
*/ */
public function provideFormNameFieldNameAndSelector() public function provideFormNameFieldNameAndSelector()
{ {
@@ -164,25 +73,117 @@ class Bootstrap4CssSelectorTest extends BaseTestCase
} }
/** /**
* Provides name of form and expected selector * Provides name of form, index/position of the field-set and expected selector
* *
* @return \Generator * @return Generator
*/ */
public function provideFormNameAndSelector() public function provideFormNameFieldSetIndexAndSelector()
{ {
yield [ yield [
'test', 'test',
'form[name="test"] .form-group', 0,
'form[name="test"] fieldset:nth-of-type(0) legend.col-form-label .invalid-feedback .form-error-message',
]; ];
yield [ yield [
'test-123-test-456', 'test-123-test-456',
'form[name="test-123-test-456"] .form-group', 1,
'form[name="test-123-test-456"] fieldset:nth-of-type(1) legend.col-form-label .invalid-feedback .form-error-message',
]; ];
yield [ yield [
'test_something_098_different', 'test_something_098_different',
'form[name="test_something_098_different"] .form-group', 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 testGetFieldErrorSelectorUsingEmptyFormName($emptyValue)
{
$fieldName = 'test';
static::assertSame('', Bootstrap4CssSelector::getFieldErrorSelector($emptyValue, $fieldName));
}
/**
* @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));
}
/**
* @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 int $fieldSetIndex Index/Position of the field-set
* @param string $expected Expected selector
*
* @dataProvider provideFormNameFieldSetIndexAndSelector
*/
public function testGetRadioButtonErrorSelector($formName, $fieldSetIndex, $expected)
{
static::assertSame($expected, Bootstrap4CssSelector::getRadioButtonErrorSelector($formName, $fieldSetIndex));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetRadioButtonErrorSelectorUsingEmptyFormName($emptyValue)
{
$fieldSetIndex = 1;
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector($emptyValue, $fieldSetIndex));
}
public function testGetRadioButtonErrorSelectorUsingNegativeFieldSetIndex()
{
static::assertSame('', Bootstrap4CssSelector::getRadioButtonErrorSelector('test-test', -1));
}
} }

View File

@@ -24,97 +24,6 @@ use Meritoo\Common\Utilities\Bundle;
*/ */
class BundleTest extends BaseTestCase class BundleTest extends BaseTestCase
{ {
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"
*
* @throws IncorrectBundleNameException
* @dataProvider provideEmptyViewPathAndBundle
*/
public function testGetBundleViewPathUsingEmptyPathAndBundle($viewPath, $bundleName)
{
self::assertNull(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"
*
* @dataProvider provideViewPathAndIncorrectBundleName
*/
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?';
$this->expectException(IncorrectBundleNameException::class);
$this->expectExceptionMessage(sprintf($template, $bundleName));
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 $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"
* @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));
}
public function testGetShortBundleNameUsingEmptyValue(): void
{
$this->expectException(IncorrectBundleNameException::class);
Bundle::getShortBundleName('');
}
/**
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
*
* @throws IncorrectBundleNameException
* @dataProvider provideIncorrectBundleName
*/
public function testGetShortBundleNameUsingIncorrectBundleName($bundleName)
{
$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 * Provides empty path of the view / template and/or name of bundle
* *
@@ -139,24 +48,39 @@ class BundleTest extends BaseTestCase
} }
/** /**
* Provides path of the view / template and incorrect name of bundle * Provides full and short name of bundle
* *
* @return Generator * @return Generator
*/ */
public function provideViewPathAndIncorrectBundleName() public function provideFullAndShortBundleName()
{ {
yield [ yield [
'User:Active', 'MyExtraBundle',
'myExtra', 'MyExtra',
]; ];
yield[ yield [
'User:Active', 'MySuperExtraGorgeousBundle',
'MySuperExtraGorgeous',
];
}
/**
* Provides incorrect name of bundle
*
* @return Generator
*/
public function provideIncorrectBundleName()
{
yield [
'myExtra',
];
yield [
'MyExtra', 'MyExtra',
]; ];
yield [ yield [
'User:Active',
'MySuperExtraGorgeous', 'MySuperExtraGorgeous',
]; ];
} }
@@ -210,40 +134,116 @@ class BundleTest extends BaseTestCase
} }
/** /**
* Provides incorrect name of bundle * Provides path of the view / template and incorrect name of bundle
* *
* @return Generator * @return Generator
*/ */
public function provideIncorrectBundleName() public function provideViewPathAndIncorrectBundleName()
{ {
yield [ yield [
'User:Active',
'myExtra', 'myExtra',
]; ];
yield [ yield [
'User:Active',
'MyExtra', 'MyExtra',
]; ];
yield [ yield [
'User:Active',
'MySuperExtraGorgeous', 'MySuperExtraGorgeous',
]; ];
} }
public function testConstructor()
{
static::assertHasNoConstructor(Bundle::class);
}
/** /**
* Provides full and short name of bundle * @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
* *
* @return Generator * @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundleAndExtension
*/ */
public function provideFullAndShortBundleName() public function testGetBundleViewPathUsingCustomExtension($viewPath, $bundleName, $extension, $expected)
{ {
yield[ self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName, $extension));
'MyExtraBundle', }
'MyExtra',
];
yield[ /**
'MySuperExtraGorgeousBundle', * @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
'MySuperExtraGorgeous', * @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"
*
* @throws IncorrectBundleNameException
* @dataProvider provideEmptyViewPathAndBundle
*/
public function testGetBundleViewPathUsingEmptyPathAndBundle($viewPath, $bundleName)
{
self::assertNull(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"
*
* @dataProvider provideViewPathAndIncorrectBundleName
*/
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?';
$this->expectException(IncorrectBundleNameException::class);
$this->expectExceptionMessage(sprintf($template, $bundleName));
Bundle::getBundleViewPath($viewPath, $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));
}
public function testGetShortBundleNameUsingEmptyValue(): void
{
$this->expectException(IncorrectBundleNameException::class);
Bundle::getShortBundleName('');
}
/**
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
*
* @throws IncorrectBundleNameException
* @dataProvider provideIncorrectBundleName
*/
public function testGetShortBundleNameUsingIncorrectBundleName($bundleName)
{
$this->expectException(IncorrectBundleNameException::class);
Bundle::getShortBundleName($bundleName);
} }
} }

View File

@@ -30,34 +30,6 @@ class ComposerTest extends BaseTestCase
*/ */
private $composerJsonPath; private $composerJsonPath;
public function testConstructor()
{
static::assertHasNoConstructor(Composer::class);
}
public function testGetValueNotExistingComposerJson(): void
{
self::assertNull(Composer::getValue('', ''));
self::assertNull(Composer::getValue('not/existing/composer.json', ''));
}
public function testGetValueNotExistingNode(): void
{
self::assertNull(Composer::getValue($this->composerJsonPath, ''));
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 * Provides names and values of existing nodes
* *
@@ -76,6 +48,34 @@ class ComposerTest extends BaseTestCase
]; ];
} }
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('', ''));
self::assertNull(Composer::getValue('not/existing/composer.json', ''));
}
public function testGetValueNotExistingNode(): void
{
self::assertNull(Composer::getValue($this->composerJsonPath, ''));
self::assertNull(Composer::getValue($this->composerJsonPath, 'not_existing_node'));
}
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\Utilities; namespace Meritoo\Test\Common\Utilities;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\CssSelector; use Meritoo\Common\Utilities\CssSelector;
@@ -22,158 +23,10 @@ use Meritoo\Common\Utilities\CssSelector;
*/ */
class CssSelectorTest extends BaseTestCase class CssSelectorTest extends BaseTestCase
{ {
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
*
* @dataProvider provideFormNameAndSelector
*/
public function testGetFormByNameSelector($formName, $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));
}
/**
* @param string $emptyValue Name of form (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetFieldSetByIndexSelectorUsingEmptyFormName($emptyValue)
{
$fieldSetIndex = 1;
static::assertSame('', CssSelector::getFieldSetByIndexSelector($emptyValue, $fieldSetIndex));
}
public function testGetFieldSetByIndexSelectorUsingNegativeFieldSetIndex()
{
static::assertSame('', CssSelector::getFieldSetByIndexSelector('test-test', -1));
}
/**
* @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 provideFormNameFieldSetIndexAndSelector
*/
public function testGetFieldSetByIndexSelector($formName, $fieldSetIndex, $expected)
{
static::assertSame($expected, CssSelector::getFieldSetByIndexSelector($formName, $fieldSetIndex));
}
/** /**
* Provides name of form and selector of the form * Provides name of form and selector of the form
* *
* @return \Generator * @return Generator
*/ */
public function provideFormNameAndSelector() public function provideFormNameAndSelector()
{ {
@@ -193,36 +46,10 @@ class CssSelectorTest extends BaseTestCase
]; ];
} }
/**
* 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, ID of field and expected selector of label * Provides name of form, ID of field and expected selector of label
* *
* @return \Generator * @return Generator
*/ */
public function provideFormNameFieldIdAndLabelSelector() public function provideFormNameFieldIdAndLabelSelector()
{ {
@@ -245,10 +72,62 @@ class CssSelectorTest extends BaseTestCase
]; ];
} }
/**
* 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 * Provides name of form, index/position of the field-set and expected selector
* *
* @return \Generator * @return Generator
*/ */
public function provideFormNameFieldSetIndexAndSelector() public function provideFormNameFieldSetIndexAndSelector()
{ {
@@ -271,29 +150,151 @@ class CssSelectorTest extends BaseTestCase
]; ];
} }
/** public function testConstructor()
* Provides name of form, ID of field and expected selector
*
* @return \Generator
*/
public function provideFormNameFieldIdAndSelector()
{ {
yield[ static::assertHasNoConstructor(CssSelector::class);
'test', }
'test',
'form[name="test"] input#test',
];
yield[ /**
'test-123-test-456', * @param string $formName Name of form (value of the "name" attribute)
'great-000-field', * @param int $fieldSetIndex Index/Position of the field-set
'form[name="test-123-test-456"] input#great-000-field', * @param string $expected Expected selector
]; *
* @dataProvider provideFormNameFieldSetIndexAndSelector
*/
public function testGetFieldSetByIndexSelector($formName, $fieldSetIndex, $expected)
{
static::assertSame($expected, CssSelector::getFieldSetByIndexSelector($formName, $fieldSetIndex));
}
yield[ /**
'test_something_098_different', * @param string $emptyValue Name of form (value of the "name" attribute)
'this-is-the-123789-field', * @dataProvider provideEmptyScalarValue
'form[name="test_something_098_different"] input#this-is-the-123789-field', */
]; public function testGetFieldSetByIndexSelectorUsingEmptyFormName($emptyValue)
{
$fieldSetIndex = 1;
static::assertSame('', CssSelector::getFieldSetByIndexSelector($emptyValue, $fieldSetIndex));
}
public function testGetFieldSetByIndexSelectorUsingNegativeFieldSetIndex()
{
static::assertSame('', CssSelector::getFieldSetByIndexSelector('test-test', -1));
}
/**
* @param string $formName Name of form (value of the "name" attribute)
* @param string $expected Expected selector
*
* @dataProvider provideFormNameAndSelector
*/
public function testGetFormByNameSelector($formName, $expected)
{
static::assertSame($expected, CssSelector::getFormByNameSelector($formName));
}
/**
* @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 $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 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 $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 $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 field (value of the "name" attribute)
* @dataProvider provideEmptyScalarValue
*/
public function testGetInputByNameSelectorUsingEmptyFieldName($emptyValue)
{
$formName = 'test-test';
static::assertSame('', CssSelector::getInputByNameSelector($formName, $emptyValue));
}
/**
* @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

@@ -24,136 +24,6 @@ use ReflectionException;
*/ */
class LocaleTest extends BaseTestCase class LocaleTest extends BaseTestCase
{ {
/**
* @throws ReflectionException
*/
public function testConstructor()
{
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.
* @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 testGetLocale($category, $languageCode, $countryCode, $expectedLocale)
{
Locale::setLocale($category, $languageCode, $countryCode);
self::assertEquals($expectedLocale, Locale::getLocale($category));
}
/**
* 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',
];
}
/** /**
* Provides category * Provides category
* *
@@ -224,4 +94,134 @@ class LocaleTest extends BaseTestCase
'it_IT.UTF-8', '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
*/
public function testConstructor()
{
static::assertHasNoConstructor(Locale::class);
}
/**
* @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 testGetLocale($category, $languageCode, $countryCode, $expectedLocale)
{
Locale::setLocale($category, $languageCode, $countryCode);
self::assertEquals($expectedLocale, Locale::getLocale($category));
}
/**
* @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 $languageCode Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetLongFormEmptyLanguageCode($languageCode)
{
self::assertEquals('', Locale::getLongForm($languageCode));
}
/**
* @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 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'));
}
} }

View File

@@ -23,199 +23,40 @@ use Meritoo\Common\Utilities\MimeTypes;
*/ */
class MimeTypesTest extends BaseTestCase class MimeTypesTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(MimeTypes::class);
}
/** /**
* @param mixed $mimeType Empty value, e.g. "" * Provides real file path to get information if the file is an image
* @dataProvider provideEmptyValue
*/
public function testGetExtensionEmptyMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param bool $mimeType The mime type, e.g. "video/mpeg"
* @dataProvider provideBooleanValue
*/
public function testGetExtensionBooleanMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType Not existing mime type, e.g. "lorem/ipsum"
* @dataProvider provideNotExistingMimeType
*/
public function testGetExtensionNotExistingMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param string $extension Expected extension
*
* @dataProvider provideMimeTypeToGetSingleExtension
*/
public function testGetExtensionSingle($mimeType, $extension)
{
self::assertEquals($extension, MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param array $extensions Expected extensions
*
* @dataProvider provideMimeTypeToGetMultipleExtension
*/
public function testGetExtensionMultiple($mimeType, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtension($mimeType));
}
/**
* @param array $mimesTypes Not existing mimes types, e.g. ['lorem/ipsum']
* @dataProvider provideNotExistingMimeTypes
*/
public function testGetExtensionsNotExistingMimeTypes($mimesTypes)
{
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
*
* @dataProvider provideMimesTypesToGetExtensionsUpperCase
*/
public function testGetExtensionsUpperCase($mimesTypes, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtensions($mimesTypes, true));
}
/**
* @param mixed $filePath Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetMimeTypeEmptyPath($filePath)
{
self::assertEquals('', MimeTypes::getMimeType($filePath));
}
/**
* @param string $filePath Path of the file to check
* @param string $mimeType Expected mime type
*
* @dataProvider provideFilePathToGetMimeTypeOfRealFile
*/
public function testGetMimeTypeOfRealFile($filePath, $mimeType)
{
self::assertEquals($mimeType, MimeTypes::getMimeType($filePath));
}
/**
* @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsImageEmptyMimeType($mimeType)
{
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 string $mimeType Mime type of non-image, e.g. "text/plain"
* @dataProvider provideNonImageMimeType
*/
public function testIsImageNonImageMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param mixed $path Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsImagePathEmptyPath($path)
{
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
*
* @dataProvider provideExistingFilePathToCheckIsImagePath
*/
public function testIsImagePathExistingPath($path, $isImage)
{
self::assertEquals($isImage, MimeTypes::isImagePath($path));
}
/**
* @param string $mimeType Mime type of image, e.g. "image/jpeg"
* @dataProvider provideImageMimeType
*/
public function testIsImageImageMimeType($mimeType)
{
self::assertTrue(MimeTypes::isImage($mimeType));
}
/**
* Provides not existing mime type
* *
* @return Generator * @return Generator
*/ */
public function provideNotExistingMimeType() public function provideExistingFilePathToCheckIsImagePath()
{ {
yield['lorem/ipsum']; yield [
yield['dolor']; $this->getFilePathForTesting('minion.jpg'),
yield['x/y/z']; true,
];
yield [
$this->getFilePathForTesting('lorem-ipsum.txt'),
false,
];
} }
/** /**
* Provides mime type of non-image * Provides real file path to get mime type
* *
* @return Generator * @return Generator
*/ */
public function provideNonImageMimeType() public function provideFilePathToGetMimeTypeOfRealFile()
{ {
yield['application/rtf']; yield [
yield['audio/mp4']; $this->getFilePathForTesting('minion.jpg'),
yield['text/plain']; 'image/jpeg',
yield['text/html']; ];
yield [
$this->getFilePathForTesting('lorem-ipsum.txt'),
'text/plain',
];
} }
/** /**
@@ -233,29 +74,6 @@ class MimeTypesTest extends BaseTestCase
yield ['image/x-rgb']; 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 * Provides existing mime type used to get multiple, more than one extension
* *
@@ -324,30 +142,25 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides not existing mime types * Provides existing mime type used to get single, one extension
* *
* @return Generator * @return Generator
*/ */
public function provideNotExistingMimeTypes() public function provideMimeTypeToGetSingleExtension()
{ {
yield [ yield [
[], 'application/x-7z-compressed',
'7z',
]; ];
yield [ yield [
[ 'application/json',
'', 'json',
null,
false,
0,
],
]; ];
yield [ yield [
[ 'application/zip',
'lorem/ipsum', 'zip',
'dolor/sit',
],
]; ];
} }
@@ -443,38 +256,225 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides real file path to get mime type * Provides mime type of non-image
* *
* @return Generator * @return Generator
*/ */
public function provideFilePathToGetMimeTypeOfRealFile() public function provideNonImageMimeType()
{ {
yield[ yield ['application/rtf'];
$this->getFilePathForTesting('minion.jpg'), yield ['audio/mp4'];
'image/jpeg', yield ['text/plain'];
]; yield ['text/html'];
yield[
$this->getFilePathForTesting('lorem-ipsum.txt'),
'text/plain',
];
} }
/** /**
* Provides real file path to get information if the file is an image * Provides not existing mime type
* *
* @return Generator * @return Generator
*/ */
public function provideExistingFilePathToCheckIsImagePath() public function provideNotExistingMimeType()
{
yield ['lorem/ipsum'];
yield ['dolor'];
yield ['x/y/z'];
}
/**
* Provides not existing mime types
*
* @return Generator
*/
public function provideNotExistingMimeTypes()
{ {
yield [ yield [
$this->getFilePathForTesting('minion.jpg'), [],
true,
]; ];
yield [ yield [
$this->getFilePathForTesting('lorem-ipsum.txt'), [
'',
null,
false, 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
*/
public function testGetExtensionEmptyMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param array $extensions Expected extensions
*
* @dataProvider provideMimeTypeToGetMultipleExtension
*/
public function testGetExtensionMultiple($mimeType, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType Not existing mime type, e.g. "lorem/ipsum"
* @dataProvider provideNotExistingMimeType
*/
public function testGetExtensionNotExistingMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param string $extension Expected extension
*
* @dataProvider provideMimeTypeToGetSingleExtension
*/
public function testGetExtensionSingle($mimeType, $extension)
{
self::assertEquals($extension, MimeTypes::getExtension($mimeType));
}
/**
* @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 Not existing mimes types, e.g. ['lorem/ipsum']
* @dataProvider provideNotExistingMimeTypes
*/
public function testGetExtensionsNotExistingMimeTypes($mimesTypes)
{
self::assertEquals([], MimeTypes::getExtensions($mimesTypes));
}
/**
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param array $extensions Expected extensions
*
* @dataProvider provideMimesTypesToGetExtensionsUpperCase
*/
public function testGetExtensionsUpperCase($mimesTypes, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtensions($mimesTypes, true));
}
/**
* @param mixed $filePath Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetMimeTypeEmptyPath($filePath)
{
self::assertEquals('', MimeTypes::getMimeType($filePath));
}
/**
* @param string $filePath Path of the file to check
* @param string $mimeType Expected mime type
*
* @dataProvider provideFilePathToGetMimeTypeOfRealFile
*/
public function testGetMimeTypeOfRealFile($filePath, $mimeType)
{
self::assertEquals($mimeType, MimeTypes::getMimeType($filePath));
}
/**
* @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsImageEmptyMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param string $mimeType Mime type of image, e.g. "image/jpeg"
* @dataProvider provideImageMimeType
*/
public function testIsImageImageMimeType($mimeType)
{
self::assertTrue(MimeTypes::isImage($mimeType));
}
/**
* @param string $mimeType Mime type of non-image, e.g. "text/plain"
* @dataProvider provideNonImageMimeType
*/
public function testIsImageNonImageMimeType($mimeType)
{
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
*/
public function testIsImagePathEmptyPath($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
*
* @dataProvider provideExistingFilePathToCheckIsImagePath
*/
public function testIsImagePathExistingPath($path, $isImage)
{
self::assertEquals($isImage, 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));
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -17,6 +17,7 @@ use Doctrine\ORM\QueryBuilder;
use Generator; use Generator;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\QueryBuilderUtility; use Meritoo\Common\Utilities\QueryBuilderUtility;
use stdClass;
/** /**
* Test case of the useful methods for query builder (the Doctrine's QueryBuilder class) * Test case of the useful methods for query builder (the Doctrine's QueryBuilder class)
@@ -29,238 +30,6 @@ use Meritoo\Common\Utilities\QueryBuilderUtility;
*/ */
class QueryBuilderUtilityTest extends BaseTestCase class QueryBuilderUtilityTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(QueryBuilderUtility::class);
}
/**
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias
* @param null|string $rootAlias Expected root alias of given query builder
*
* @dataProvider provideQueryBuilderAndRootAlias
*/
public function testGetRootAlias(QueryBuilder $queryBuilder, $rootAlias)
{
static::assertSame($rootAlias, QueryBuilderUtility::getRootAlias($queryBuilder));
}
/**
* @param QueryBuilder $queryBuilder The query builder to verify
* @param string $propertyName Name of property that maybe is joined
* @param null|string $propertyAlias Expected alias of given property joined in given query builder
*
* @dataProvider provideQueryBuilderAndPropertyAlias
*/
public function testGetJoinedPropertyAlias(QueryBuilder $queryBuilder, $propertyName, $propertyAlias)
{
static::assertSame($propertyAlias, QueryBuilderUtility::getJoinedPropertyAlias($queryBuilder, $propertyName));
}
public function testSetCriteriaWithoutCriteria()
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$queryBuilder = new QueryBuilder($entityManager);
$newQueryBuilder = QueryBuilderUtility::setCriteria($queryBuilder);
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount(0, $newQueryBuilder->getParameters());
static::assertNull($newQueryBuilder->getDQLPart('where'));
}
public function testSetCriteriaWithoutAlias()
{
$criteria = [
'lorem' => 11,
'ipsum' => 22,
];
$entityManager = $this->createMock(EntityManagerInterface::class);
$queryBuilder = new QueryBuilder($entityManager);
$newQueryBuilder = QueryBuilderUtility::setCriteria($queryBuilder, $criteria);
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount(count($criteria), $newQueryBuilder->getParameters());
static::assertNotNull($newQueryBuilder->getDQLPart('where'));
}
/**
* @param QueryBuilder $queryBuilder The query builder
* @param array $criteria The criteria used in WHERE clause
*
* @dataProvider provideQueryBuilderAndCriteria
*/
public function testSetCriteria(QueryBuilder $queryBuilder, array $criteria)
{
$newQueryBuilder = QueryBuilderUtility::setCriteria($queryBuilder, $criteria);
$criteriaCount = count($criteria);
$nullsCount = 0;
// I have to verify count/amount of NULLs and decrease $criteriaCount, because for null parameter is not added
array_walk($criteria, function ($value) use (&$nullsCount) {
if (null === $value) {
++$nullsCount;
}
});
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount($criteriaCount - $nullsCount, $newQueryBuilder->getParameters());
static::assertNotNull($newQueryBuilder->getDQLPart('where'));
}
public function testDeleteEntitiesWithoutFlush()
{
$methods = [
'remove',
'flush',
];
$entityManager = $this
->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->setMethods($methods)
->getMock()
;
$entities1 = [];
$entities2 = [
new \stdClass(),
];
static::assertFalse(QueryBuilderUtility::deleteEntities($entityManager, $entities1, false));
static::assertTrue(QueryBuilderUtility::deleteEntities($entityManager, $entities2, false));
}
public function testDeleteEntities()
{
$methods = [
'remove',
'flush',
];
$entityManager = $this
->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->setMethods($methods)
->getMock()
;
$entities1 = [];
$entities2 = [
new \stdClass(),
];
static::assertFalse(QueryBuilderUtility::deleteEntities($entityManager, $entities1));
static::assertTrue(QueryBuilderUtility::deleteEntities($entityManager, $entities2));
}
/**
* @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.
*
* @dataProvider provideQueryBuilderAndParameters
*/
public function testAddParameters(QueryBuilder $queryBuilder, $parameters)
{
$newQueryBuilder = QueryBuilderUtility::addParameters($queryBuilder, $parameters);
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount(count($parameters), $newQueryBuilder->getParameters());
}
/**
* Provides query builder to retrieve root alias and expected root alias
*
* @return Generator
*/
public function provideQueryBuilderAndRootAlias()
{
$entityManager = $this->createMock(EntityManagerInterface::class);
yield[
new QueryBuilder($entityManager),
null,
];
yield[
(new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'),
'lm',
];
yield[
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i'),
'l',
];
}
/**
* Provides query builder, name of property and expected alias of given property
*
* @return Generator
*/
public function provideQueryBuilderAndPropertyAlias()
{
$entityManager = $this->createMock(EntityManagerInterface::class);
yield[
new QueryBuilder($entityManager),
'',
null,
];
yield[
new QueryBuilder($entityManager),
'lorem',
null,
];
yield[
(new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'),
'lm',
null,
];
yield[
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i'),
'ipsum',
'i',
];
yield[
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i')
->innerJoin('i.dolor', 'd'),
'ipsum1',
null,
];
yield[
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i')
->innerJoin('i.dolor', 'd'),
'ipsum',
'i',
];
yield[
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i')
->innerJoin('i.dolor', 'd'),
'dolor',
'd',
];
}
/** /**
* Provides query builder and criteria used in WHERE clause * Provides query builder and criteria used in WHERE clause
* *
@@ -272,8 +41,7 @@ class QueryBuilderUtilityTest extends BaseTestCase
->getMockBuilder(EntityManager::class) ->getMockBuilder(EntityManager::class)
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(['getExpressionBuilder']) ->setMethods(['getExpressionBuilder'])
->getMock() ->getMock();
;
$entityManager $entityManager
->expects(static::any()) ->expects(static::any())
@@ -357,4 +125,234 @@ class QueryBuilderUtilityTest extends BaseTestCase
]), ]),
]; ];
} }
/**
* Provides query builder, name of property and expected alias of given property
*
* @return Generator
*/
public function provideQueryBuilderAndPropertyAlias()
{
$entityManager = $this->createMock(EntityManagerInterface::class);
yield [
new QueryBuilder($entityManager),
'',
null,
];
yield [
new QueryBuilder($entityManager),
'lorem',
null,
];
yield [
(new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'),
'lm',
null,
];
yield [
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i'),
'ipsum',
'i',
];
yield [
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i')
->innerJoin('i.dolor', 'd'),
'ipsum1',
null,
];
yield [
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i')
->innerJoin('i.dolor', 'd'),
'ipsum',
'i',
];
yield [
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i')
->innerJoin('i.dolor', 'd'),
'dolor',
'd',
];
}
/**
* Provides query builder to retrieve root alias and expected root alias
*
* @return Generator
*/
public function provideQueryBuilderAndRootAlias()
{
$entityManager = $this->createMock(EntityManagerInterface::class);
yield [
new QueryBuilder($entityManager),
null,
];
yield [
(new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'),
'lm',
];
yield [
(new QueryBuilder($entityManager))
->from('lorem', 'l')
->leftJoin('l.ipsum', 'i'),
'l',
];
}
/**
* @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.
*
* @dataProvider provideQueryBuilderAndParameters
*/
public function testAddParameters(QueryBuilder $queryBuilder, $parameters)
{
$newQueryBuilder = QueryBuilderUtility::addParameters($queryBuilder, $parameters);
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount(count($parameters), $newQueryBuilder->getParameters());
}
public function testConstructor()
{
static::assertHasNoConstructor(QueryBuilderUtility::class);
}
public function testDeleteEntities()
{
$methods = [
'remove',
'flush',
];
$entityManager = $this
->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->setMethods($methods)
->getMock();
$entities1 = [];
$entities2 = [
new stdClass(),
];
static::assertFalse(QueryBuilderUtility::deleteEntities($entityManager, $entities1));
static::assertTrue(QueryBuilderUtility::deleteEntities($entityManager, $entities2));
}
public function testDeleteEntitiesWithoutFlush()
{
$methods = [
'remove',
'flush',
];
$entityManager = $this
->getMockBuilder(EntityManager::class)
->disableOriginalConstructor()
->setMethods($methods)
->getMock();
$entities1 = [];
$entities2 = [
new stdClass(),
];
static::assertFalse(QueryBuilderUtility::deleteEntities($entityManager, $entities1, false));
static::assertTrue(QueryBuilderUtility::deleteEntities($entityManager, $entities2, false));
}
/**
* @param QueryBuilder $queryBuilder The query builder to verify
* @param string $propertyName Name of property that maybe is joined
* @param null|string $propertyAlias Expected alias of given property joined in given query builder
*
* @dataProvider provideQueryBuilderAndPropertyAlias
*/
public function testGetJoinedPropertyAlias(QueryBuilder $queryBuilder, $propertyName, $propertyAlias)
{
static::assertSame($propertyAlias, QueryBuilderUtility::getJoinedPropertyAlias($queryBuilder, $propertyName));
}
/**
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias
* @param null|string $rootAlias Expected root alias of given query builder
*
* @dataProvider provideQueryBuilderAndRootAlias
*/
public function testGetRootAlias(QueryBuilder $queryBuilder, $rootAlias)
{
static::assertSame($rootAlias, QueryBuilderUtility::getRootAlias($queryBuilder));
}
/**
* @param QueryBuilder $queryBuilder The query builder
* @param array $criteria The criteria used in WHERE clause
*
* @dataProvider provideQueryBuilderAndCriteria
*/
public function testSetCriteria(QueryBuilder $queryBuilder, array $criteria)
{
$newQueryBuilder = QueryBuilderUtility::setCriteria($queryBuilder, $criteria);
$criteriaCount = count($criteria);
$nullsCount = 0;
// I have to verify count/amount of NULLs and decrease $criteriaCount, because for null parameter is not added
array_walk($criteria, function ($value) use (&$nullsCount) {
if (null === $value) {
++$nullsCount;
}
});
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount($criteriaCount - $nullsCount, $newQueryBuilder->getParameters());
static::assertNotNull($newQueryBuilder->getDQLPart('where'));
}
public function testSetCriteriaWithoutAlias()
{
$criteria = [
'lorem' => 11,
'ipsum' => 22,
];
$entityManager = $this->createMock(EntityManagerInterface::class);
$queryBuilder = new QueryBuilder($entityManager);
$newQueryBuilder = QueryBuilderUtility::setCriteria($queryBuilder, $criteria);
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount(count($criteria), $newQueryBuilder->getParameters());
static::assertNotNull($newQueryBuilder->getDQLPart('where'));
}
public function testSetCriteriaWithoutCriteria()
{
$entityManager = $this->createMock(EntityManagerInterface::class);
$queryBuilder = new QueryBuilder($entityManager);
$newQueryBuilder = QueryBuilderUtility::setCriteria($queryBuilder);
static::assertSame($queryBuilder, $newQueryBuilder);
static::assertCount(0, $newQueryBuilder->getParameters());
static::assertNull($newQueryBuilder->getDQLPart('where'));
}
} }

View File

@@ -24,13 +24,13 @@ class A
private $count = 1; private $count = 1;
protected function lorem()
{
return 'ipsum';
}
protected function getCount() protected function getCount()
{ {
return $this->count; return $this->count;
} }
protected function lorem()
{
return 'ipsum';
}
} }

View File

@@ -20,13 +20,13 @@ namespace Meritoo\Test\Common\Utilities\Reflection;
*/ */
class C extends B class C extends B
{ {
public function getPositive()
{
return true;
}
public function getNegative() public function getNegative()
{ {
return false; return false;
} }
public function getPositive()
{
return true;
}
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -23,318 +23,6 @@ use Meritoo\Common\Utilities\Uri;
*/ */
class UriTest extends BaseTestCase class UriTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(Uri::class);
}
public function testAddProtocolToUrl()
{
$http = 'http';
$https = 'https';
$url = 'my.domain/some/url';
$httpUrl = sprintf('%s://%s', $http, $url);
$httpsUrl = sprintf('%s://%s', $https, $url);
self::assertEquals($httpUrl, Uri::addProtocolToUrl($httpUrl));
self::assertEquals($httpUrl, Uri::addProtocolToUrl($url));
self::assertEquals($httpsUrl, Uri::addProtocolToUrl($url, $https));
self::assertEquals($httpsUrl, Uri::addProtocolToUrl($httpsUrl, $http));
}
/**
* @param mixed $url Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testReplenishProtocolEmptyUrl($url)
{
self::assertEquals('', Uri::replenishProtocol($url));
}
/**
* @param string $expected Expected result
* @param string $url The url to check and replenish
* @param string $protocol (optional) The protocol which is replenished. If is empty, protocol of current request
* is used.
*
* @dataProvider provideUrlToReplenishProtocol
*/
public function testReplenishProtocol($expected, $url, $protocol = '')
{
/*
* Required to get protocol when it's not provided and to void test failure:
*
* Failed asserting that two strings are identical.
* Expected :'://test'
* Actual :'http://test'
*/
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
self::assertSame($expected, Uri::replenishProtocol($url, $protocol));
}
public function testGetServerNameOrIpWithoutProtocol()
{
$_SERVER['HTTP_HOST'] = '';
self::assertEquals('', Uri::getServerNameOrIp());
$host = 'lorem.com';
$_SERVER['HTTP_HOST'] = $host;
self::assertEquals($host, Uri::getServerNameOrIp());
}
public function testGetServerNameOrIpWithProtocol()
{
$_SERVER['HTTP_HOST'] = '';
$_SERVER['SERVER_PROTOCOL'] = '';
self::assertEquals('', Uri::getServerNameOrIp(true));
$host = 'lorem.com';
$protocol = 'HTTP/1.1';
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['SERVER_PROTOCOL'] = $protocol;
self::assertEquals(sprintf('http://%s', $host), Uri::getServerNameOrIp(true));
}
public function testGetFullUriWithHost()
{
$_SERVER['HTTP_HOST'] = '';
$_SERVER['SERVER_PROTOCOL'] = '';
$_SERVER['REQUEST_URI'] = '';
self::assertEquals('', Uri::getFullUri());
$host = 'lorem.com';
$protocol = 'HTTP/1.1';
$requestedUrl = '/test/123';
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['SERVER_PROTOCOL'] = $protocol;
$_SERVER['REQUEST_URI'] = $requestedUrl;
self::assertEquals(sprintf('http://%s%s', $host, $requestedUrl), Uri::getFullUri());
}
public function testGetFullUriWithoutHost()
{
$_SERVER['HTTP_HOST'] = '';
$_SERVER['SERVER_PROTOCOL'] = '';
$_SERVER['REQUEST_URI'] = '';
self::assertEquals('', Uri::getFullUri(true));
$requestedUrl = '/test/123';
$_SERVER['REQUEST_URI'] = $requestedUrl;
self::assertEquals($requestedUrl, Uri::getFullUri(true));
}
public function testGetProtocolName()
{
$_SERVER['SERVER_PROTOCOL'] = '';
self::assertEquals('', Uri::getProtocolName());
$protocol = 'HTTP/1.1';
$_SERVER['SERVER_PROTOCOL'] = $protocol;
self::assertEquals('http', Uri::getProtocolName());
}
public function testGetRefererUri()
{
$_SERVER['HTTP_REFERER'] = '';
self::assertEquals('', Uri::getRefererUri());
$refererUrl = 'http://lorem.com/test/123';
$_SERVER['HTTP_REFERER'] = $refererUrl;
self::assertEquals($refererUrl, Uri::getRefererUri());
}
public function testGetUserAddressIp()
{
$_SERVER['REMOTE_ADDR'] = '';
self::assertEquals('', Uri::getUserAddressIp());
$userAddressIp = '1.2.3.4';
$_SERVER['REMOTE_ADDR'] = $userAddressIp;
self::assertEquals($userAddressIp, Uri::getUserAddressIp());
}
public function testGetUserWebBrowserInfo()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserWebBrowserInfo());
$browserInfo = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like Gecko)'
. ' Version/8.0.2 Safari/600.2.5';
$_SERVER['HTTP_USER_AGENT'] = $browserInfo;
self::assertEquals($browserInfo, Uri::getUserWebBrowserInfo());
}
public function testGetUserWebBrowserNameWithoutVersion()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserWebBrowserName());
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like'
. ' Gecko) Version/8.0.2 Safari/600.2.5';
self::assertEquals('Apple Safari', Uri::getUserWebBrowserName());
}
public function testGetUserWebBrowserNameWithVersion()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserWebBrowserName(true));
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like'
. ' Gecko) Version/8.0.2 Safari/600.2.5';
self::assertEquals('Apple Safari 600.2.5', Uri::getUserWebBrowserName(true));
}
public function testGetUserOperatingSystemName()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserOperatingSystemName());
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like'
. ' Gecko) Version/8.0.2 Safari/600.2.5';
self::assertEquals('Mac OS', Uri::getUserOperatingSystemName());
}
public function testIsServerLocalhost()
{
$_SERVER['HTTP_HOST'] = '';
self::assertFalse(Uri::isServerLocalhost());
$_SERVER['HTTP_HOST'] = '127.0.0.1';
self::assertTrue(Uri::isServerLocalhost());
}
/**
* @param string $url The url to check
* @param bool $expected Information if verified url is external
*
* @dataProvider provideUrlToVerifyIfIsExternal
*/
public function testIsExternalUrl($url, $expected)
{
$host = 'lorem.com';
$protocol = 'HTTP/1.1';
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['SERVER_PROTOCOL'] = $protocol;
self::assertEquals($expected, Uri::isExternalUrl($url));
}
/**
* @param string $url A path / url to some resource, e.g. page, image, css file
* @param string $user User name used to log in
* @param string $password User password used to log in
* @param string $expectedUrl Expected, secured url
*
* @dataProvider provideDataForSecuredUrl
*/
public function testGetSecuredUrl($url, $user, $password, $expectedUrl)
{
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
$_SERVER['HTTP_HOST'] = 'lorem.com';
self::assertEquals($expectedUrl, Uri::getSecuredUrl($url, $user, $password));
}
/**
* @param string $expected
* @param string $rootUrl
* @param string ...$urlParts
*
* @dataProvider provideRootUrlAndUrlParts
*/
public function testBuildUrl(string $expected, string $rootUrl, string ...$urlParts): void
{
static::assertSame($expected, Uri::buildUrl($rootUrl, ...$urlParts));
}
/**
* Provides url to replenish protocol
*
* @return Generator
*/
public function provideUrlToReplenishProtocol()
{
yield[
'http://test',
'test',
'',
];
yield[
'ftp://lorem.ipsum',
'lorem.ipsum',
'ftp',
];
}
/**
* Provides url used to verify if it's external, from another server / domain
*
* @return Generator
*/
public function provideUrlToVerifyIfIsExternal()
{
yield[
'',
false,
];
yield[
'/',
false,
];
yield[
'http://something.different/first-page',
true,
];
yield[
'something.different/first-page',
true,
];
yield[
'http://lorem.com',
false,
];
yield[
'http://lorem.com/contact',
false,
];
yield[
'lorem.com',
false,
];
yield[
'lorem.com/contact',
false,
];
}
/** /**
* Provides data used to build secured url * Provides data used to build secured url
* *
@@ -436,4 +124,316 @@ class UriTest extends BaseTestCase
'', '',
]; ];
} }
/**
* Provides url to replenish protocol
*
* @return Generator
*/
public function provideUrlToReplenishProtocol()
{
yield [
'http://test',
'test',
'',
];
yield [
'ftp://lorem.ipsum',
'lorem.ipsum',
'ftp',
];
}
/**
* Provides url used to verify if it's external, from another server / domain
*
* @return Generator
*/
public function provideUrlToVerifyIfIsExternal()
{
yield [
'',
false,
];
yield [
'/',
false,
];
yield [
'http://something.different/first-page',
true,
];
yield [
'something.different/first-page',
true,
];
yield [
'http://lorem.com',
false,
];
yield [
'http://lorem.com/contact',
false,
];
yield [
'lorem.com',
false,
];
yield [
'lorem.com/contact',
false,
];
}
public function testAddProtocolToUrl()
{
$http = 'http';
$https = 'https';
$url = 'my.domain/some/url';
$httpUrl = sprintf('%s://%s', $http, $url);
$httpsUrl = sprintf('%s://%s', $https, $url);
self::assertEquals($httpUrl, Uri::addProtocolToUrl($httpUrl));
self::assertEquals($httpUrl, Uri::addProtocolToUrl($url));
self::assertEquals($httpsUrl, Uri::addProtocolToUrl($url, $https));
self::assertEquals($httpsUrl, Uri::addProtocolToUrl($httpsUrl, $http));
}
/**
* @param string $expected
* @param string $rootUrl
* @param string ...$urlParts
*
* @dataProvider provideRootUrlAndUrlParts
*/
public function testBuildUrl(string $expected, string $rootUrl, string ...$urlParts): void
{
static::assertSame($expected, Uri::buildUrl($rootUrl, ...$urlParts));
}
public function testConstructor()
{
static::assertHasNoConstructor(Uri::class);
}
public function testGetFullUriWithHost()
{
$_SERVER['HTTP_HOST'] = '';
$_SERVER['SERVER_PROTOCOL'] = '';
$_SERVER['REQUEST_URI'] = '';
self::assertEquals('', Uri::getFullUri());
$host = 'lorem.com';
$protocol = 'HTTP/1.1';
$requestedUrl = '/test/123';
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['SERVER_PROTOCOL'] = $protocol;
$_SERVER['REQUEST_URI'] = $requestedUrl;
self::assertEquals(sprintf('http://%s%s', $host, $requestedUrl), Uri::getFullUri());
}
public function testGetFullUriWithoutHost()
{
$_SERVER['HTTP_HOST'] = '';
$_SERVER['SERVER_PROTOCOL'] = '';
$_SERVER['REQUEST_URI'] = '';
self::assertEquals('', Uri::getFullUri(true));
$requestedUrl = '/test/123';
$_SERVER['REQUEST_URI'] = $requestedUrl;
self::assertEquals($requestedUrl, Uri::getFullUri(true));
}
public function testGetProtocolName()
{
$_SERVER['SERVER_PROTOCOL'] = '';
self::assertEquals('', Uri::getProtocolName());
$protocol = 'HTTP/1.1';
$_SERVER['SERVER_PROTOCOL'] = $protocol;
self::assertEquals('http', Uri::getProtocolName());
}
public function testGetRefererUri()
{
$_SERVER['HTTP_REFERER'] = '';
self::assertEquals('', Uri::getRefererUri());
$refererUrl = 'http://lorem.com/test/123';
$_SERVER['HTTP_REFERER'] = $refererUrl;
self::assertEquals($refererUrl, Uri::getRefererUri());
}
/**
* @param string $url A path / url to some resource, e.g. page, image, css file
* @param string $user User name used to log in
* @param string $password User password used to log in
* @param string $expectedUrl Expected, secured url
*
* @dataProvider provideDataForSecuredUrl
*/
public function testGetSecuredUrl($url, $user, $password, $expectedUrl)
{
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
$_SERVER['HTTP_HOST'] = 'lorem.com';
self::assertEquals($expectedUrl, Uri::getSecuredUrl($url, $user, $password));
}
public function testGetServerNameOrIpWithProtocol()
{
$_SERVER['HTTP_HOST'] = '';
$_SERVER['SERVER_PROTOCOL'] = '';
self::assertEquals('', Uri::getServerNameOrIp(true));
$host = 'lorem.com';
$protocol = 'HTTP/1.1';
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['SERVER_PROTOCOL'] = $protocol;
self::assertEquals(sprintf('http://%s', $host), Uri::getServerNameOrIp(true));
}
public function testGetServerNameOrIpWithoutProtocol()
{
$_SERVER['HTTP_HOST'] = '';
self::assertEquals('', Uri::getServerNameOrIp());
$host = 'lorem.com';
$_SERVER['HTTP_HOST'] = $host;
self::assertEquals($host, Uri::getServerNameOrIp());
}
public function testGetUserAddressIp()
{
$_SERVER['REMOTE_ADDR'] = '';
self::assertEquals('', Uri::getUserAddressIp());
$userAddressIp = '1.2.3.4';
$_SERVER['REMOTE_ADDR'] = $userAddressIp;
self::assertEquals($userAddressIp, Uri::getUserAddressIp());
}
public function testGetUserOperatingSystemName()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserOperatingSystemName());
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like'
.' Gecko) Version/8.0.2 Safari/600.2.5';
self::assertEquals('Mac OS', Uri::getUserOperatingSystemName());
}
public function testGetUserWebBrowserInfo()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserWebBrowserInfo());
$browserInfo = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like Gecko)'
.' Version/8.0.2 Safari/600.2.5';
$_SERVER['HTTP_USER_AGENT'] = $browserInfo;
self::assertEquals($browserInfo, Uri::getUserWebBrowserInfo());
}
public function testGetUserWebBrowserNameWithVersion()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserWebBrowserName(true));
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like'
.' Gecko) Version/8.0.2 Safari/600.2.5';
self::assertEquals('Apple Safari 600.2.5', Uri::getUserWebBrowserName(true));
}
public function testGetUserWebBrowserNameWithoutVersion()
{
$_SERVER['HTTP_USER_AGENT'] = '';
self::assertEquals('', Uri::getUserWebBrowserName());
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/600.2.5 (KHTML, like'
.' Gecko) Version/8.0.2 Safari/600.2.5';
self::assertEquals('Apple Safari', Uri::getUserWebBrowserName());
}
/**
* @param string $url The url to check
* @param bool $expected Information if verified url is external
*
* @dataProvider provideUrlToVerifyIfIsExternal
*/
public function testIsExternalUrl($url, $expected)
{
$host = 'lorem.com';
$protocol = 'HTTP/1.1';
$_SERVER['HTTP_HOST'] = $host;
$_SERVER['SERVER_PROTOCOL'] = $protocol;
self::assertEquals($expected, Uri::isExternalUrl($url));
}
public function testIsServerLocalhost()
{
$_SERVER['HTTP_HOST'] = '';
self::assertFalse(Uri::isServerLocalhost());
$_SERVER['HTTP_HOST'] = '127.0.0.1';
self::assertTrue(Uri::isServerLocalhost());
}
/**
* @param string $expected Expected result
* @param string $url The url to check and replenish
* @param string $protocol (optional) The protocol which is replenished. If is empty, protocol of current request
* is used.
*
* @dataProvider provideUrlToReplenishProtocol
*/
public function testReplenishProtocol($expected, $url, $protocol = '')
{
/*
* Required to get protocol when it's not provided and to void test failure:
*
* Failed asserting that two strings are identical.
* Expected :'://test'
* Actual :'http://test'
*/
$_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
self::assertSame($expected, Uri::replenishProtocol($url, $protocol));
}
/**
* @param mixed $url Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testReplenishProtocolEmptyUrl($url)
{
self::assertEquals('', Uri::replenishProtocol($url));
}
} }

View File

@@ -48,13 +48,6 @@ class AddressTest extends BaseTestCase
); );
} }
public function testGetFlatNumber()
{
static::assertSame('200', $this->address->getFlatNumber());
static::assertSame('', $this->addressWithoutFlat->getFlatNumber());
static::assertSame('300', $this->addressWithoutStreet->getFlatNumber());
}
public function testGetBuildingNumber() public function testGetBuildingNumber()
{ {
static::assertSame('10', $this->address->getBuildingNumber()); static::assertSame('10', $this->address->getBuildingNumber());
@@ -62,11 +55,18 @@ class AddressTest extends BaseTestCase
static::assertSame('1', $this->addressWithoutStreet->getBuildingNumber()); static::assertSame('1', $this->addressWithoutStreet->getBuildingNumber());
} }
public function testGetStreet() public function testGetCity()
{ {
static::assertSame('4th Avenue', $this->address->getStreet()); static::assertSame('New York', $this->address->getCity());
static::assertSame('Green Street', $this->addressWithoutFlat->getStreet()); static::assertSame('San Francisco', $this->addressWithoutFlat->getCity());
static::assertSame('', $this->addressWithoutStreet->getStreet()); static::assertSame('Saint Louis', $this->addressWithoutStreet->getCity());
}
public function testGetFlatNumber()
{
static::assertSame('200', $this->address->getFlatNumber());
static::assertSame('', $this->addressWithoutFlat->getFlatNumber());
static::assertSame('300', $this->addressWithoutStreet->getFlatNumber());
} }
public function testGetFullStreet() public function testGetFullStreet()
@@ -76,11 +76,11 @@ class AddressTest extends BaseTestCase
static::assertSame('', $this->addressWithoutStreet->getFullStreet()); static::assertSame('', $this->addressWithoutStreet->getFullStreet());
} }
public function testGetCity() public function testGetStreet()
{ {
static::assertSame('New York', $this->address->getCity()); static::assertSame('4th Avenue', $this->address->getStreet());
static::assertSame('San Francisco', $this->addressWithoutFlat->getCity()); static::assertSame('Green Street', $this->addressWithoutFlat->getStreet());
static::assertSame('Saint Louis', $this->addressWithoutStreet->getCity()); static::assertSame('', $this->addressWithoutStreet->getStreet());
} }
public function testGetZipCode() public function testGetZipCode()

View File

@@ -45,12 +45,6 @@ class CompanyTest extends BaseTestCase
); );
} }
public function testGetName()
{
static::assertSame('Test 1', $this->company->getName());
static::assertSame('Test 2', $this->companyWithoutBankAccount->getName());
}
public function testGetAddress() public function testGetAddress()
{ {
static::assertEquals( static::assertEquals(
@@ -74,6 +68,12 @@ class CompanyTest extends BaseTestCase
static::assertNull($this->companyWithoutBankAccount->getBankAccount()); static::assertNull($this->companyWithoutBankAccount->getBankAccount());
} }
public function testGetName()
{
static::assertSame('Test 1', $this->company->getName());
static::assertSame('Test 2', $this->companyWithoutBankAccount->getName());
}
public function testToString() public function testToString()
{ {
static::assertSame('Test 1, 4th Avenue 10/200, 00123, New York, Bank 1, 12345', (string) $this->company); static::assertSame('Test 1, 4th Avenue 10/200, 00123, New York, Bank 1, 12345', (string) $this->company);

View File

@@ -8,6 +8,7 @@
namespace Meritoo\Test\Common\ValueObject; namespace Meritoo\Test\Common\ValueObject;
use DateTime;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\ValueObject\Human; use Meritoo\Common\ValueObject\Human;
@@ -23,73 +24,6 @@ use Meritoo\Common\ValueObject\Human;
*/ */
class HumanTest extends BaseTestCase class HumanTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertConstructorVisibilityAndArguments(
Human::class,
OopVisibilityType::IS_PUBLIC,
4,
2
);
}
/**
* @param string $description Description of test
* @param Human $human Human to verify
* @param string $expected Expected string
*
* @dataProvider provideHuman
*/
public function testToString($description, Human $human, $expected)
{
static::assertSame($expected, (string)$human, $description);
}
public function testGetFirstName()
{
$empty = new Human('', '');
static::assertSame('', $empty->getFirstName());
$human = new Human('John', 'Scott');
static::assertSame('John', $human->getFirstName());
}
public function testGetLastName()
{
$empty = new Human('', '');
static::assertSame('', $empty->getLastName());
$human = new Human('John', 'Scott');
static::assertSame('Scott', $human->getLastName());
}
public function testGetBirthDate()
{
$empty = new Human('', '');
static::assertNull($empty->getBirthDate());
$human = new Human('John', 'Scott', '', new \DateTime('2001-01-01'));
static::assertEquals(new \DateTime('2001-01-01'), $human->getBirthDate());
}
public function testGetFullName()
{
$empty = new Human('', '');
static::assertSame('', $empty->getFullName());
$human = new Human('John', 'Scott', '', new \DateTime('2001-01-01'));
static::assertSame('John Scott', $human->getFullName());
}
public function testGetEmail()
{
$empty = new Human('', '');
static::assertNull($empty->getEmail());
$human = new Human('John', 'Scott', 'john@scott.com');
static::assertSame('john@scott.com', $human->getEmail());
}
public function provideHuman() public function provideHuman()
{ {
yield [ yield [
@@ -112,8 +46,75 @@ class HumanTest extends BaseTestCase
yield [ yield [
'With whole/complete data', 'With whole/complete data',
new Human('John', 'Scott', 'john@scott.com', new \DateTime('2001-01-01')), new Human('John', 'Scott', 'john@scott.com', new DateTime('2001-01-01')),
'John Scott <john@scott.com>', 'John Scott <john@scott.com>',
]; ];
} }
public function testConstructor()
{
static::assertConstructorVisibilityAndArguments(
Human::class,
OopVisibilityType::IS_PUBLIC,
4,
2
);
}
public function testGetBirthDate()
{
$empty = new Human('', '');
static::assertNull($empty->getBirthDate());
$human = new Human('John', 'Scott', '', new DateTime('2001-01-01'));
static::assertEquals(new DateTime('2001-01-01'), $human->getBirthDate());
}
public function testGetEmail()
{
$empty = new Human('', '');
static::assertNull($empty->getEmail());
$human = new Human('John', 'Scott', 'john@scott.com');
static::assertSame('john@scott.com', $human->getEmail());
}
public function testGetFirstName()
{
$empty = new Human('', '');
static::assertSame('', $empty->getFirstName());
$human = new Human('John', 'Scott');
static::assertSame('John', $human->getFirstName());
}
public function testGetFullName()
{
$empty = new Human('', '');
static::assertSame('', $empty->getFullName());
$human = new Human('John', 'Scott', '', new DateTime('2001-01-01'));
static::assertSame('John Scott', $human->getFullName());
}
public function testGetLastName()
{
$empty = new Human('', '');
static::assertSame('', $empty->getLastName());
$human = new Human('John', 'Scott');
static::assertSame('Scott', $human->getLastName());
}
/**
* @param string $description Description of test
* @param Human $human Human to verify
* @param string $expected Expected string
*
* @dataProvider provideHuman
*/
public function testToString($description, Human $human, $expected)
{
static::assertSame($expected, (string) $human, $description);
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -27,72 +27,6 @@ use Meritoo\Common\ValueObject\Template;
*/ */
class TemplateTest extends BaseTestCase class TemplateTest extends BaseTestCase
{ {
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
Template::class,
OopVisibilityType::IS_PUBLIC,
1,
1
);
}
/**
* @param string $content Raw string with placeholders (content of the template)
* @param string $exceptionMessage Expected message of exception
*
* @dataProvider provideInvalidContent
*/
public function testIsValidUsingInvalidContent(string $content, string $exceptionMessage): void
{
$this->expectException(InvalidContentException::class);
$this->expectExceptionMessage($exceptionMessage);
new Template($content);
}
/**
* @param string $description Description of test
* @param string $content Raw string with placeholders (content of the template)
*
* @dataProvider provideValidContent
*/
public function testIsValidUsingValidContent(string $description, string $content): void
{
$template = new Template($content);
static::assertSame($content, Reflection::getPropertyValue($template, 'content', true), $description);
}
/**
* @param Template $template Template to fill
* @param array $values Pairs of key-value where: key - name of placeholder, value - value of the
* placeholder
* @param string $exceptionMessage Expected message of exception
*
* @dataProvider provideTemplateToFillUsingIncorrectValues
*/
public function testFillUsingIncorrectValues(Template $template, array $values, string $exceptionMessage): void
{
$this->expectException(MissingPlaceholdersInValuesException::class);
$this->expectExceptionMessage($exceptionMessage);
$template->fill($values);
}
/**
* @param string $description Description of test
* @param Template $template Template to fill
* @param array $values Pairs of key-value where: key - name of placeholder, value - value of the
* placeholder
* @param string $expected Expected result
*
* @dataProvider provideTemplateToFill
*/
public function testFill(string $description, Template $template, array $values, string $expected): void
{
static::assertSame($expected, $template->fill($values), $description);
}
public function provideInvalidContent(): ?Generator public function provideInvalidContent(): ?Generator
{ {
$template = 'Content of template \'%s\' is invalid. Did you use string with 1 placeholder at least?'; $template = 'Content of template \'%s\' is invalid. Did you use string with 1 placeholder at least?';
@@ -118,71 +52,6 @@ class TemplateTest extends BaseTestCase
]; ];
} }
public function provideTemplateToFillUsingIncorrectValues(): ?Generator
{
$template = 'Cannot fill template \'%s\', because of missing values for placeholder(s): %s. Did you provide all'
. ' required values?';
yield[
new Template('%test%'),
[
'something' => 123,
],
sprintf(
$template,
'%test%',
'test'
),
];
yield[
new Template('%test%'),
[],
sprintf(
$template,
'%test%',
'test'
),
];
yield[
new Template('%test1% - %test2%'),
[
'test1' => 123,
],
sprintf(
$template,
'%test1% - %test2%',
'test2'
),
];
yield[
new Template('%test1% - %test2%'),
[
'test1' => 123,
'test3' => 456,
],
sprintf(
$template,
'%test1% - %test2%',
'test2'
),
];
yield[
new Template('%test1% / %test2% / %test3%'),
[
'test1' => 123,
],
sprintf(
$template,
'%test1% / %test2% / %test3%',
'test2, test3'
),
];
}
public function provideTemplateToFill(): ?Generator public function provideTemplateToFill(): ?Generator
{ {
yield [ yield [
@@ -252,6 +121,71 @@ class TemplateTest extends BaseTestCase
]; ];
} }
public function provideTemplateToFillUsingIncorrectValues(): ?Generator
{
$template = 'Cannot fill template \'%s\', because of missing values for placeholder(s): %s. Did you provide all'
.' required values?';
yield [
new Template('%test%'),
[
'something' => 123,
],
sprintf(
$template,
'%test%',
'test'
),
];
yield [
new Template('%test%'),
[],
sprintf(
$template,
'%test%',
'test'
),
];
yield [
new Template('%test1% - %test2%'),
[
'test1' => 123,
],
sprintf(
$template,
'%test1% - %test2%',
'test2'
),
];
yield [
new Template('%test1% - %test2%'),
[
'test1' => 123,
'test3' => 456,
],
sprintf(
$template,
'%test1% - %test2%',
'test2'
),
];
yield [
new Template('%test1% / %test2% / %test3%'),
[
'test1' => 123,
],
sprintf(
$template,
'%test1% / %test2% / %test3%',
'test2, test3'
),
];
}
public function provideValidContent(): ?Generator public function provideValidContent(): ?Generator
{ {
yield [ yield [
@@ -269,4 +203,70 @@ class TemplateTest extends BaseTestCase
'My name is %first name% %last name% and I live in %current location%', 'My name is %first name% %last name% and I live in %current location%',
]; ];
} }
public function testConstructor(): void
{
static::assertConstructorVisibilityAndArguments(
Template::class,
OopVisibilityType::IS_PUBLIC,
1,
1
);
}
/**
* @param string $description Description of test
* @param Template $template Template to fill
* @param array $values Pairs of key-value where: key - name of placeholder, value - value of the
* placeholder
* @param string $expected Expected result
*
* @dataProvider provideTemplateToFill
*/
public function testFill(string $description, Template $template, array $values, string $expected): void
{
static::assertSame($expected, $template->fill($values), $description);
}
/**
* @param Template $template Template to fill
* @param array $values Pairs of key-value where: key - name of placeholder, value - value of the
* placeholder
* @param string $exceptionMessage Expected message of exception
*
* @dataProvider provideTemplateToFillUsingIncorrectValues
*/
public function testFillUsingIncorrectValues(Template $template, array $values, string $exceptionMessage): void
{
$this->expectException(MissingPlaceholdersInValuesException::class);
$this->expectExceptionMessage($exceptionMessage);
$template->fill($values);
}
/**
* @param string $content Raw string with placeholders (content of the template)
* @param string $exceptionMessage Expected message of exception
*
* @dataProvider provideInvalidContent
*/
public function testIsValidUsingInvalidContent(string $content, string $exceptionMessage): void
{
$this->expectException(InvalidContentException::class);
$this->expectExceptionMessage($exceptionMessage);
new Template($content);
}
/**
* @param string $description Description of test
* @param string $content Raw string with placeholders (content of the template)
*
* @dataProvider provideValidContent
*/
public function testIsValidUsingValidContent(string $description, string $content): void
{
$template = new Template($content);
static::assertSame($content, Reflection::getPropertyValue($template, 'content', true), $description);
}
} }

View File

@@ -25,115 +25,6 @@ use Meritoo\Common\ValueObject\Version;
*/ */
class VersionTest extends BaseTestCase class VersionTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertConstructorVisibilityAndArguments(Version::class, OopVisibilityType::IS_PUBLIC, 3, 3);
}
public function testNewInstance()
{
$version = new Version(1, 0, 2);
static::assertInstanceOf(Version::class, $version);
static::assertSame(1, Reflection::getPropertyValue($version, 'majorPart'));
static::assertSame(0, Reflection::getPropertyValue($version, 'minorPart'));
static::assertSame(2, Reflection::getPropertyValue($version, 'patchPart'));
}
/**
* @param Version $version The version
* @param string $expected Expected string
*
* @dataProvider provideConvertedToString
*/
public function testToString(Version $version, $expected)
{
static::assertSame($expected, (string)$version);
}
/**
* @param string $version The version
* @param Version $expected (optional) Expected version
*
* @dataProvider provideAsString
*/
public function testFromString($version, Version $expected = null)
{
static::assertEquals($expected, Version::fromString($version));
}
/**
* @param array $version The version
* @param Version $expected (optional) Expected version
*
* @dataProvider provideAsArray
*/
public function testFromArray(array $version, Version $expected = null)
{
static::assertEquals($expected, Version::fromArray($version));
}
/**
* Provide instance of version and expected version converted to string
*
* @return Generator
*/
public function provideConvertedToString()
{
yield[
new Version(0, 0, 0),
'0.0.0',
];
yield[
new Version(1, 0, 2),
'1.0.2',
];
yield[
new Version(10, 5, 41),
'10.5.41',
];
}
/**
* Provide version as string and expected instance of version
*
* @return Generator
*/
public function provideAsString()
{
yield[
'',
null,
];
yield[
'1.0',
null,
];
yield[
'10',
null,
];
yield[
'0.0.0',
new Version(0, 0, 0),
];
yield[
'1.0.2',
new Version(1, 0, 2),
];
yield[
'10.5.41',
new Version(10, 5, 41),
];
}
/** /**
* Provide version as array and expected instance of version * Provide version as array and expected instance of version
* *
@@ -188,4 +79,113 @@ class VersionTest extends BaseTestCase
new Version(10, 5, 41), new Version(10, 5, 41),
]; ];
} }
/**
* Provide version as string and expected instance of version
*
* @return Generator
*/
public function provideAsString()
{
yield [
'',
null,
];
yield [
'1.0',
null,
];
yield [
'10',
null,
];
yield [
'0.0.0',
new Version(0, 0, 0),
];
yield [
'1.0.2',
new Version(1, 0, 2),
];
yield [
'10.5.41',
new Version(10, 5, 41),
];
}
/**
* Provide instance of version and expected version converted to string
*
* @return Generator
*/
public function provideConvertedToString()
{
yield [
new Version(0, 0, 0),
'0.0.0',
];
yield [
new Version(1, 0, 2),
'1.0.2',
];
yield [
new Version(10, 5, 41),
'10.5.41',
];
}
public function testConstructor()
{
static::assertConstructorVisibilityAndArguments(Version::class, OopVisibilityType::IS_PUBLIC, 3, 3);
}
/**
* @param array $version The version
* @param Version $expected (optional) Expected version
*
* @dataProvider provideAsArray
*/
public function testFromArray(array $version, Version $expected = null)
{
static::assertEquals($expected, Version::fromArray($version));
}
/**
* @param string $version The version
* @param Version $expected (optional) Expected version
*
* @dataProvider provideAsString
*/
public function testFromString($version, Version $expected = null)
{
static::assertEquals($expected, Version::fromString($version));
}
public function testNewInstance()
{
$version = new Version(1, 0, 2);
static::assertInstanceOf(Version::class, $version);
static::assertSame(1, Reflection::getPropertyValue($version, 'majorPart'));
static::assertSame(0, Reflection::getPropertyValue($version, 'minorPart'));
static::assertSame(2, Reflection::getPropertyValue($version, 'patchPart'));
}
/**
* @param Version $version The version
* @param string $expected Expected string
*
* @dataProvider provideConvertedToString
*/
public function testToString(Version $version, $expected)
{
static::assertSame($expected, (string) $version);
}
} }