2 Commits
0.1.7 ... 0.1.8

Author SHA1 Message Date
Meritoo
5022efb9a3 Minor refactoring 2019-03-24 22:19:45 +01:00
Meritoo
56b058ca1d Size, e.g. of image 2019-03-24 22:15:54 +01:00
11 changed files with 1788 additions and 10 deletions

View File

@@ -2,6 +2,10 @@
Common and useful classes, methods, exceptions etc.
# 0.1.8
1. Size, e.g. of image
# 0.1.7
1. Collection > create trait (to make it more flexible)

View File

@@ -1 +1 @@
0.1.7
0.1.8

View File

@@ -177,6 +177,68 @@ $human2 = new Human('John', 'Scott', 'john@scott.com', new \DateTime('2001-01-01
$asString2 = (string)$human2; // "John Scott <john@scott.com>"
```
### Size
##### Namespace
`Meritoo\Common\ValueObject\Size`
##### Info
Size, e.g. of image. Contains properties:
1. `width` - the width
2. `height` - the height
3. `unit` - unit used when width or height should be returned with unit, default: `"px"`
4. `separator` - separator used when converting to string, default: `" x "`
##### New instance
New instance can be created using static methods:
1. `fromArray()` - creates new instance from given array
```php
// Using default "px" unit
Size::fromArray([200, 100]);
// With custom "mm" unit
Size::fromArray([200, 100], 'mm');
```
2. `fromString()` - creates new instance from given string
```php
// Using default "px" unit and default " x " separator
Size::fromString('200 x 100');
// With custom "mm" unit and " X " separator
Size::fromString('200 X 100', 'mm', ' X ');
```
##### Methods
Has:
- getters and setters for `width` and `height` properties.
- setter for `separator` property
- `toString()` and `toArray()` methods that returns size represented as string and array
##### Conversion to string (using `__toString()` method)
Instance of `Size` may be represented as string that contains width and height separated by separator (default: `" x "`).
Example:
```php
$size = Size::fromArray([200, 100]);
// With default separator
$asString1 = (string)$size; // "200 x 100"
// With custom separator
$size->setSeparator('X');
$asString2 = (string)$size; // "200X100"
```
### Version
##### Namespace
@@ -213,7 +275,11 @@ New instance can be created using:
Version::fromString('1.0.2');
```
##### Conversion to string (the `__toString()` method)
##### Methods
Has getters for each property: `getMajorPart()`, `getMinorPart()`, `getPatchPart()`.
##### Conversion to string (using `__toString()` method)
Instance of `Version` may be represented as string that contains all properties separated by `.` (`$majorPart`.`$minorPart`.`$patchPart`).

View File

@@ -0,0 +1,33 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\Common\Exception\ValueObject;
/**
* An exception used while dimensions of size, passed to the instance of Size class, are invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidSizeDimensionsException extends \Exception
{
/**
* Creates exception
*
* @param int $width The width
* @param int $height The height
* @return InvalidSizeDimensionsException
*/
public static function create($width, $height)
{
$template = 'Dimensions of size should be positive, but they are not: %d, %d. Is there everything ok?';
$message = sprintf($template, $width, $height);
return new static($message);
}
}

View File

@@ -397,8 +397,8 @@ class Arrays
$counter = 0;
$arrayCount = count($array);
$array = self::quoteStrings($array);
$isMultiDimensional = self::isMultiDimensional($array);
$arrayPrepared = self::quoteStrings($array);
$isMultiDimensional = self::isMultiDimensional($arrayPrepared);
/*
* Name of the variable was not provided and it's a multi dimensional array?
@@ -419,7 +419,7 @@ class Arrays
$result .= ');';
}
foreach ($array as $index => $value) {
foreach ($arrayPrepared as $index => $value) {
++$counter;
if (is_array($value)) {
@@ -1483,12 +1483,11 @@ class Arrays
}
$effect[$key] = $diff;
} elseif ($value !== $array2[$key]) {
/*
* Value is different than in 2nd array?
* OKay, I've got difference
*/
} elseif ($value !== $array2[$key]) {
$effect[$key] = $value;
}
} else {

View File

@@ -40,6 +40,18 @@ class Regex
'color' => '/^[a-f0-9]{6}$/i',
'bundleName' => '/^(([A-Z]{1}[a-z0-9]+)((?2))*)(Bundle)$/',
'binaryValue' => '/[^\x20-\x7E\t\r\n]/',
/*
* Matches:
* - "200x125"
* - "200 x 125"
* - "200 x 125"
* - " 200 x 125"
* - " 200 x 125 "
*
* Contains "%s" that should be replaced with separator used to split width and height.
*/
'size' => '/^[\ ]*(\d+)[\ ]*%s[\ ]*(\d+)[\ ]*$/',
];
/**
@@ -920,6 +932,56 @@ class Regex
return (bool)preg_match($pattern, $value);
}
/**
* Returns pattern used to validate / verify size
*
* @param string $separator (optional) Separator used to split width and height. Default: " x ".
* @return string
*/
public static function getSizePattern($separator = ' x ')
{
$escapeMe = [
'/',
'|',
'.',
'(',
')',
'[',
']',
];
$cleanSeparator = trim($separator);
if (in_array($cleanSeparator, $escapeMe, true)) {
// I have to escape special character of regular expression that may be used as separator
$separator = str_replace($cleanSeparator, '\\' . $cleanSeparator, $separator);
}
return sprintf(self::$patterns['size'], $separator);
}
/**
* Returns information if given value is a size value
*
* @param string $value Value to verify
* @param string $separator (optional) Separator used to split width and height. Default: " x ".
* @return bool
*/
public static function isSizeValue($value, $separator = ' x ')
{
/*
* Not a string?
* Nothing to do
*/
if (!is_string($value)) {
return false;
}
$pattern = self::getSizePattern($separator);
return (bool)preg_match($pattern, $value);
}
/**
* Returns slug for given value
*

245
src/ValueObject/Size.php Normal file
View File

@@ -0,0 +1,245 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\Common\ValueObject;
use Meritoo\Common\Exception\ValueObject\InvalidSizeDimensionsException;
use Meritoo\Common\Utilities\Regex;
/**
* Size, e.g. of image
*
* Instance of this class may be created using static methods:
* - fromString()
* - fromArray()
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class Size
{
/**
* The width
*
* @var int
*/
protected $width;
/**
* The height
*
* @var int
*/
protected $height;
/**
* Unit used when width or height should be returned with unit
*
* @var string
*/
protected $unit;
/**
* Separator used when converting to string
*
* @var string
*/
protected $separator = ' x ';
/**
* Class constructor
*
* @param int $width (optional) The width
* @param int $height (optional) The height
* @param string $unit (optional) Unit used when width or height should be returned with unit. Default: "px".
*
* @throws InvalidSizeDimensionsException
*/
private function __construct($width = null, $height = null, $unit = 'px')
{
$width = (int)$width;
$height = (int)$height;
if ($width < 0 || $height < 0) {
throw new InvalidSizeDimensionsException($width, $height);
}
$this
->setWidth($width)
->setHeight($height)
;
$this->unit = $unit;
}
/**
* Returns string representation of instance of this class in human readable format, e.g. '200 x 100'
*
* @return string
*/
public function __toString()
{
return $this->toString();
}
/**
* Sets separator used when converting to string
*
* @param string $separator The separator
* @return Size
*/
public function setSeparator($separator)
{
$this->separator = $separator;
return $this;
}
/**
* Returns the width
*
* @param bool $withUnit (optional) If is set to true, width is returned with unit ("px"). Otherwise - without
* (default behaviour).
* @return int|string
*/
public function getWidth($withUnit = false)
{
if ($withUnit) {
return sprintf('%d %s', $this->width, $this->unit);
}
return $this->width;
}
/**
* Sets the width
*
* @param int|string $width The width
* @return Size
*/
public function setWidth($width)
{
$this->width = (int)$width;
return $this;
}
/**
* Returns the height
*
* @param bool $withUnit (optional) If is set to true, height is returned with unit ("px"). Otherwise - without
* (default behaviour).
* @return int|string
*/
public function getHeight($withUnit = false)
{
if ($withUnit) {
return sprintf('%d %s', $this->height, $this->unit);
}
return $this->height;
}
/**
* Sets the height
*
* @param int $height The height
* @return Size
*/
public function setHeight($height)
{
$this->height = (int)$height;
return $this;
}
/**
* Returns string representation of instance of this class, e.g. '200 x 100' or '200x100'
*
* @param bool $withUnit (optional) If is set to true, width and height are returned with unit ("px"). Otherwise
* - without (default behaviour).
* @return string
*/
public function toString($withUnit = false)
{
$width = $this->getWidth($withUnit);
$height = $this->getHeight($withUnit);
return sprintf('%s%s%s', $width, $this->separator, $height);
}
/**
* Returns instance of this class as an array.
* Values of the array are width and height, eg. [800, 600] or ['800px', '600px'].
*
* @param bool $withUnits (optional) If is set to true, width and height are returned with unit ("px"). Otherwise
* - without (default behaviour).
* @return array
*/
public function toArray($withUnits = false)
{
return [
$this->getWidth($withUnits),
$this->getHeight($withUnits),
];
}
/**
* 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 Size|null
*/
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;
}
/**
* 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 Size|null
*/
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

@@ -22,7 +22,7 @@ class Version
*
* @var int
*/
private $majorPart;
protected $majorPart;
/**
* The "minor" part.
@@ -30,7 +30,7 @@ class Version
*
* @var int
*/
private $minorPart;
protected $minorPart;
/**
* The "patch" part.
@@ -38,7 +38,7 @@ class Version
*
* @var int
*/
private $patchPart;
protected $patchPart;
/**
* Class constructor

View File

@@ -0,0 +1,67 @@
<?php
/**
* (c) Meritoo.pl, http://www.meritoo.pl
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Meritoo\Test\Common\Exception\ValueObject;
use Meritoo\Common\Exception\ValueObject\InvalidSizeDimensionsException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while dimensions of size, passed to the instance of Size class, are invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class 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()
{
$template = 'Dimensions of size should be positive, but they are not: %d, %d. Is there everything ok?';
yield[
0,
0,
sprintf($template, 0, 0),
];
yield[
-1,
-1,
sprintf($template, -1, -1),
];
yield[
200,
100,
sprintf($template, 200, 100),
];
}
}

View File

@@ -624,6 +624,28 @@ class RegexTest extends BaseTestCase
self::assertEquals($expected, Regex::getValidColorHexValue($color));
}
/**
* @param mixed $emptyValue Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public static function testIsSizeValueUsingEmptyValue($emptyValue)
{
self::assertFalse(Regex::isSizeValue($emptyValue));
}
/**
* @param string $description Description of test
* @param string $value Value to verify
* @param string $separator Separator used to split width and height
* @param bool $expected Expected result of verification
*
* @dataProvider provideSizeToVerify
*/
public function testIsSizeValue($description, $value, $separator, $expected)
{
self::assertEquals($expected, Regex::isSizeValue($value, $separator), $description);
}
/**
* @param string $value Value that should be transformed to slug
* @param string $expected Expected slug
@@ -1788,6 +1810,191 @@ class RegexTest extends BaseTestCase
];
}
public function provideSizeToVerify()
{
yield[
'One number only',
200,
' x ',
false,
];
yield[
'One number only as string',
'200',
' x ',
false,
];
yield[
'The " " as invalid separator',
'200 100',
' x ',
false,
];
yield[
'The "|" as separator (invalid separator)',
'200 | 100',
' x ',
false,
];
yield[
'The "|" as invalid separator and no spaces around separator',
'200|100',
' x ',
false,
];
yield[
'The "X" as invalid separator',
'200 X 100',
' x ',
false,
];
yield[
'Simple, valid size',
'200 x 100',
' x ',
true,
];
yield[
'Too much spaces at the right of separator',
'200 x 100',
' x ',
true,
];
yield[
'Too much spaces at the left of separator',
'200 x 100',
' x ',
true,
];
yield[
'Too much spaces around separator',
'200 x 100',
' x ',
true,
];
yield[
'Too much spaces before width',
' 200 x 100',
' x ',
true,
];
yield[
'Too much spaces after height',
'200 x 100 ',
' x ',
true,
];
yield[
'Too much spaces before width and after height',
' 200 x 100 ',
' x ',
true,
];
yield[
'Too much spaces everywhere (1st)',
' 200 x 100 ',
' x ',
true,
];
yield[
'Too much spaces everywhere (2nd)',
' 200 x 100 ',
' x ',
true,
];
yield[
'Too much spaces everywhere (3rd)',
' 200 x 100 ',
' x ',
true,
];
yield[
'The " X " as custom separator',
'200 X 100',
' X ',
true,
];
yield[
'The "|" as custom separator',
'200|100',
'|',
true,
];
yield[
'The " | " as custom separator',
'200 | 100',
' | ',
true,
];
yield[
'The "::" as custom separator',
'200::100',
'::',
true,
];
yield[
'The " :: " as custom separator',
'200 :: 100',
' :: ',
true,
];
yield[
'The "." as custom separator',
'200.100',
'.',
true,
];
yield[
'The " . " as custom separator',
'200 . 100',
' . ',
true,
];
yield[
'The "/" as custom separator',
'200/100',
'/',
true,
];
yield[
'The " / " as custom separator',
'200 / 100',
' / ',
true,
];
yield[
'The " : " as custom separator and too much spaces everywhere',
' 200 : 100 ',
' : ',
true,
];
}
/**
* {@inheritdoc}
*/

File diff suppressed because it is too large Load Diff