33 Commits

Author SHA1 Message Date
Meritoo
8bcf006e02 Tests - increase code coverage 2017-11-05 19:35:13 +01:00
Meritoo
edc51aeee1 DatePeriod - change namespace (Meritoo\Common\Utilities -> Meritoo\Common\Type) & extend BaseType 2017-11-03 20:21:08 +01:00
Meritoo
6d4e422165 BaseTestCase & BaseTypeTestCase - add traits to use in other test cases (e.g. in Symfony's kernel-related test case) 2017-11-02 22:00:38 +01:00
Meritoo
6f441bb9ea Tests - BaseTestCaseTest - fix bug while there is a difference (split second) 2017-11-02 13:58:24 +01:00
Meritoo
73030d703b composer.json - bump version 2017-11-02 12:25:39 +01:00
Meritoo
36ddb326b9 Tests - increase code coverage 2017-10-31 21:27:42 +01:00
Meritoo
452a4ec458 Tests - BaseTestCase - rename method getFilePathToTests() -> getFilePathForTesting() 2017-10-31 21:26:39 +01:00
Meritoo
325fe6b141 Support PHP 5.5.9+ 2017-10-31 20:28:55 +01:00
Meritoo
a1c26b3812 Phing - tests - phpcodesniffer task - fix "This task requires the PHP_CodeSniffer package installed and available on the include path" bug
Details: https://github.com/phingofficial/phing/issues/716
2017-10-26 20:04:05 +02:00
Meritoo
67d93036cf Phing - update properties.dist file 2017-10-22 21:40:23 +02:00
Meritoo
9368616dfe composer.json - update versions of the "dev" packages 2017-10-22 20:09:02 +02:00
Meritoo
5ab68d3667 Tests - Docker - update Xdebug configuration
Required to fix problem "Connection with XDebug 2.5.1 was not established. Validate installation."
2017-10-22 17:55:49 +02:00
Meritoo
4613a63f02 Tests - Docker - install vim, add custom php.ini, add "vendor/bin" to the $PATH global variable 2017-10-20 00:03:38 +02:00
Meritoo
9dac5bd11c Tests - Docker - update name of image and container 2017-10-18 21:50:02 +02:00
Meritoo
12100db058 Tests - Docker - update port 2017-10-18 20:02:09 +02:00
Meritoo
f9ab0a6194 Tests - Docker - add required libraries, PHP extensions & optimize size of Docker's image 2017-10-18 17:01:13 +02:00
Meritoo
b824808cd4 Tests - use Docker (as environment guard) 2017-10-18 00:31:18 +02:00
Meritoo
71e1eeb81b Start names of special directories with dot
BaseTestCase - add setter for path of directory with data used by test cases
2017-10-17 20:49:13 +02:00
Meritoo
70c273750d .gitignore update 2017-10-10 20:09:40 +02:00
Meritoo
e5e39651f3 Tests - fix names of constructors' tests 2017-10-02 15:56:53 +02:00
Meritoo
4683970c87 composer.json - update versions of the "dev" packages & sort them 2017-10-02 14:06:57 +02:00
Meritoo
559466c0ce composer.json - move tests-related classes to "autoload-dev" section (used for development purposes only and avoid polluting the autoloader in production) 2017-09-29 09:19:03 +02:00
Meritoo
bfd69c1098 Minor fix of coding standard 2017-09-27 21:52:10 +02:00
Meritoo
45493b37b0 Remove composer.lock 2017-09-27 21:51:48 +02:00
Meritoo
37e7b14ae2 Minor fix of coding standard 2017-09-27 20:09:51 +02:00
Meritoo
a12aaf4bc0 Tests - increase code coverage 2017-09-27 17:08:39 +02:00
Meritoo
f9c480aa19 Reflection - getPropertyValue() method - verify if getter is accessible publicly 2017-09-27 17:00:25 +02:00
Meritoo
ffa3fbffe7 Exception - DisabledMethodException - an exception used while method cannot be called, because is disabled 2017-09-22 23:27:21 +02:00
Meritoo
48aa27fb86 Tests - test cases of exceptions 2017-09-22 23:26:30 +02:00
Meritoo
86cc5ff79b Refactor & fix coding standard 2017-09-22 23:25:16 +02:00
Meritoo
633696ebc0 Reflection - getProperties() method - allow to include properties of parent classes 2017-09-21 22:38:50 +02:00
Meritoo
a0d28b326e BaseTestCase - make static and rename methods (start names of methods with "assert" instead of "verify") 2017-09-21 16:52:15 +02:00
Meritoo
318a635ffd BaseTestCase - assertHasNoConstructor() method - asserts that class with given namespace has no constructor 2017-09-21 16:47:41 +02:00
94 changed files with 2755 additions and 4064 deletions

View File

Before

Width:  |  Height:  |  Size: 29 KiB

After

Width:  |  Height:  |  Size: 29 KiB

64
.docker/config/Dockerfile Normal file
View File

@@ -0,0 +1,64 @@
FROM php:5.5-cli
#
# Tools & libraries
#
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
vim \
git \
zip \
unzip \
zlib1g-dev \
libicu-dev \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
#
# PHP extensions
#
RUN docker-php-ext-install \
zip \
intl \
mbstring
#
# PHP configuration:
# - default configuration
# - timezone
#
COPY php.ini /usr/local/etc/php/php.ini
ARG TIMEZONE
RUN echo "\n""date.timezone = $TIMEZONE""\n" >> /usr/local/etc/php/php.ini
#
# Xdebug
#
RUN pecl install xdebug \
&& docker-php-ext-enable xdebug
COPY xdebug.ini /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#
# Phing
#
RUN pear channel-discover pear.phing.info \
&& pear install [--alldeps] phing/phing
#
# Composer + https://packagist.org/packages/hirak/prestissimo package
#
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
&& php -r "if (hash_file('SHA384', 'composer-setup.php') === \
'544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo \
'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" \
&& php composer-setup.php --install-dir=/usr/local/bin --filename=composer \
&& php -r "unlink('composer-setup.php');" \
&& composer global require --no-plugins --no-scripts hirak/prestissimo \
&& rm -rf /root/.composer/cache/*
#
# Bash
#
RUN sed -i 's/^# export/export/g' /root/.bashrc \
&& sed -i 's/^# alias/alias/g' /root/.bashrc \
&& echo "\n"'export PATH=/project/vendor/bin:$PATH'"\n" >> /root/.bashrc

3
.docker/config/php.ini Normal file
View File

@@ -0,0 +1,3 @@
display_errors = On
display_startup_errors = On
error_reporting = E_ALL

View File

@@ -0,0 +1,6 @@
[xdebug]
zend_extension=xdebug.so
xdebug.remote_enable=1
xdebug.remote_port=9001
xdebug.remote_host=10.254.254.254

1
.env Normal file
View File

@@ -0,0 +1 @@
TIMEZONE=Europe/Warsaw

11
.gitignore vendored
View File

@@ -7,13 +7,14 @@
# ----------------------------------------------------------------------------------------------------------------------
### Composer
# ----------------------------------------------------------------------------------------------------------------------
/composer.lock
/composer.phar
# ----------------------------------------------------------------------------------------------------------------------
### Phing
# ----------------------------------------------------------------------------------------------------------------------
/phing/properties
/.phing/properties
# ----------------------------------------------------------------------------------------------------------------------
@@ -28,10 +29,16 @@
/.php_cs.cache
# ----------------------------------------------------------------------------------------------------------------------
### Build files
# ----------------------------------------------------------------------------------------------------------------------
/.build/
# ----------------------------------------------------------------------------------------------------------------------
### Generated databases
# ----------------------------------------------------------------------------------------------------------------------
/data/tmp
/.data/tmp
*.sql
*.sqlite

View File

@@ -2,12 +2,12 @@
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="phing/properties" property="custom.properties.available"/>
<available file=".phing/properties" property="custom.properties.available"/>
<then>
<property file="phing/properties" />
<property file=".phing/properties" />
</then>
<else>
<property file="phing/properties.dist" />
<property file=".phing/properties.dist" />
</else>
</if>

View File

@@ -28,7 +28,13 @@ assets.installWithSymlink = true
# Clear cache with the "warmup" option
#
cache.clearWithWarmup = true
# The cache:clear command should always be called with the --no-warmup option. Warmup should be done via the cache:warmup command.
# https://github.com/symfony/symfony/blob/master/UPGRADE-3.3.md#frameworkbundle
#
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
# 2017-06-06
#
cache.clearWithWarmup = false
# --------------------------------------------------------------------------------
# Composer
@@ -59,7 +65,7 @@ composer.validate = false
# System directories
#
dir.data = ${project.basedir}/data
dir.data = ${project.basedir}/.data
dir.src = ${project.basedir}/src
dir.tests = ${project.basedir}/tests
@@ -67,7 +73,7 @@ dir.tests = ${project.basedir}/tests
# Build directories
# --------------------------------------------------------------------------------
dir.build = ${project.basedir}/build
dir.build = ${project.basedir}/.build
dir.reports = ${dir.build}/logs
dir.reports.pdepend = ${dir.reports}/pdepend
dir.reports.coverage = ${dir.reports}/phpunit_coverage

View File

@@ -11,12 +11,12 @@
<!-- Properties -->
<if>
<available file="phing/properties" property="custom.properties.available"/>
<available file=".phing/properties" property="custom.properties.available"/>
<then>
<property file="phing/properties" />
<property file=".phing/properties" />
</then>
<else>
<property file="phing/properties.dist" />
<property file=".phing/properties.dist" />
</else>
</if>

View File

@@ -13,6 +13,15 @@ $ composer require meritoo/common-library
> How to install Composer: https://getcomposer.org/download
## Rebuilding project and tests running
```bash
$ docker-compose up -d
$ docker-compose exec php-cli phing
```
> What is Docker? https://www.docker.com/what-docker
## 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:

View File

@@ -2,12 +2,12 @@
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="phing/properties" property="custom.properties.available"/>
<available file=".phing/properties" property="custom.properties.available"/>
<then>
<property file="phing/properties" />
<property file=".phing/properties" />
</then>
<else>
<property file="phing/properties.dist" />
<property file=".phing/properties.dist" />
</else>
</if>
@@ -18,12 +18,12 @@
<!-- Build app -->
<target name="build:app" description="Prepares app to build and tests">
<phing phingfile="phing/app.xml" haltonfailure="true" />
<phing phingfile=".phing/app.xml" haltonfailure="true" />
</target>
<!-- Build tests -->
<target name="build:tests" description="Runs all tests, checks and creates docs">
<phing phingfile="phing/tests.xml" haltonfailure="true" />
<phing phingfile=".phing/tests.xml" haltonfailure="true" />
<!--
Conditional running of tests.
@@ -35,7 +35,7 @@
<if>
<equals arg1="${env}" arg2="test" />
<then>
<phing phingfile="phing/tests.xml" haltonfailure="true" />
<phing phingfile=".phing/tests.xml" haltonfailure="true" />
</then>
<else>
<echo message="[Skipped] Running tests, checks and creating docs, because it's a not 'test' environment..." />

View File

@@ -2,7 +2,7 @@
"name": "meritoo/common-library",
"description": "Useful classes, methods, extensions etc.",
"license": "MIT",
"version": "0.0.10",
"version": "0.0.18",
"authors": [
{
"name": "Meritoo.pl",
@@ -11,24 +11,31 @@
}
],
"require": {
"php": ">=5.6.0",
"php": ">=5.5.9",
"doctrine/orm": "^2.5",
"gedmo/doctrine-extensions": "^2.4",
"symfony/http-foundation": "^3.3"
},
"require-dev": {
"phpunit/phpunit": "^5.7",
"squizlabs/php_codesniffer": "^2.9",
"phpmd/phpmd": "^2.6",
"sebastian/phpcpd": "^3.0",
"friendsofphp/php-cs-fixer": "^2.2",
"pdepend/pdepend": "^2.5",
"phploc/phploc": "^4.0",
"friendsofphp/php-cs-fixer": "^2.6"
"phploc/phploc": "^2.1",
"phpmd/phpmd": "^2.6",
"phpunit/phpunit": "^4.8",
"sebastian/phpcpd": "^2.0",
"squizlabs/php_codesniffer": "^2.9"
},
"autoload": {
"psr-4": {
"Meritoo\\Common\\": "src/Meritoo/Common/",
"Meritoo\\Common\\Test\\": "tests/Meritoo/Common/Test/"
"Meritoo\\Common\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Meritoo\\Common\\Test\\": "tests/"
}
},
"config": {
"sort-packages": true
}
}

3494
composer.lock generated

File diff suppressed because it is too large Load Diff

15
docker-compose.yml Normal file
View File

@@ -0,0 +1,15 @@
version: '3'
services:
php-cli:
image: meritoo/common-library
container_name: meritoo-common-library
working_dir: /project
entrypoint: php
command: -S 0.0.0.0:9999
build:
context: ./.docker/config
args:
- TIMEZONE=$TIMEZONE
volumes:
- .:/project

View File

@@ -30,6 +30,6 @@
</groups>
<logging>
<log type="coverage-html" target="./build/logs/phpunit_coverage/html" />
<log type="coverage-html" target="./.build/logs/phpunit_coverage/html" />
</logging>
</phpunit>

View File

@@ -23,7 +23,7 @@ class NotExistingFileException extends \Exception
*/
public function __construct($notExistingFilePath)
{
$template = 'File with path \'%s\' does not exist (or is not readable). Did you provide proper path of file?';
$template = 'File with path \'%s\' does not exist (or is not readable). Did you provide path of proper file?';
$message = sprintf($template, $notExistingFilePath);
parent::__construct($message);

View File

@@ -0,0 +1,38 @@
<?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\Method;
use Exception;
/**
* An exception used while method cannot be called, because is disabled
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DisabledMethodException extends Exception
{
/**
* Class constructor
*
* @param string $disabledMethod Name of the disabled method
* @param string $alternativeMethod (optional) Name of the alternative method
*/
public function __construct($disabledMethod, $alternativeMethod = '')
{
$template = 'Method %s() cannot be called, because is disabled.';
if (!empty($alternativeMethod)) {
$template .= ' Use %s() instead.';
}
$message = sprintf($template, $disabledMethod, $alternativeMethod);
parent::__construct($message);
}
}

View File

@@ -21,7 +21,7 @@ class CannotResolveClassNameException extends Exception
/**
* Class constructor
*
* @param array|object|string $source Source of the class's / trait's name. It cane be an array of objects,
* @param array|object|string $source Source of the class's / trait's name. It can be an array of objects,
* namespaces, object or namespace.
* @param bool $forClass (optional) If is set to true, message of this exception for class is
* prepared. Otherwise - for trait.

View File

@@ -0,0 +1,23 @@
<?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\Test\Base;
use Meritoo\Common\Traits\Test\Base\BaseTestCaseTrait;
use PHPUnit\Framework\TestCase;
/**
* Base test case with common methods and data providers
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
abstract class BaseTestCase extends TestCase
{
use BaseTestCaseTrait;
}

View File

@@ -0,0 +1,22 @@
<?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\Test\Base;
use Meritoo\Common\Traits\Test\Base\BaseTypeTestCaseTrait;
/**
* Base test case for the type of something
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
abstract class BaseTypeTestCase extends BaseTestCase
{
use BaseTypeTestCaseTrait;
}

View File

@@ -6,25 +6,32 @@
* file that was distributed with this source code.
*/
namespace Meritoo\Common\Test\Base;
namespace Meritoo\Common\Traits\Test\Base;
use DateTime;
use Generator;
use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\Miscellaneous;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionMethod;
/**
* Base test case with common methods and data providers
* BaseTestCaseTrait
* Created on 2017-11-02
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
abstract class BaseTestCase extends TestCase
trait BaseTestCaseTrait
{
/**
* Path of directory with data used by test cases
*
* @var string
*/
private static $testsDataDirPath = '.data/tests';
/**
* Provides an empty value
*
@@ -98,19 +105,19 @@ abstract class BaseTestCase extends TestCase
/**
* Returns path of file used by tests.
* It should be placed in /data/tests directory of this project.
* 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
*/
public function getFilePathToTests($fileName, $directoryPath = '')
public function getFilePathForTesting($fileName, $directoryPath = '')
{
$rootPath = Miscellaneous::getProjectRootPath();
$paths = [
$rootPath,
'data/tests',
self::$testsDataDirPath,
$directoryPath,
$fileName,
];
@@ -135,7 +142,7 @@ abstract class BaseTestCase extends TestCase
* - string - name of the method
* - instance of ReflectionMethod - just the method (provided by ReflectionClass::getMethod() method)
*/
protected function verifyMethodVisibilityAndArguments(
protected static function assertMethodVisibilityAndArguments(
$classNamespace,
$method,
$visibilityType,
@@ -180,7 +187,7 @@ abstract class BaseTestCase extends TestCase
/**
* Verifies visibility and arguments of class constructor
*
* @param string $classNamespace Namespace of class that contains method to verify
* @param string $classNamespace Namespace of class that contains constructor to verify
* @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType class
* constants.
* @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method
@@ -188,7 +195,7 @@ abstract class BaseTestCase extends TestCase
* method
* @throws UnknownOopVisibilityTypeException
*/
protected function verifyConstructorVisibilityAndArguments(
protected static function assertConstructorVisibilityAndArguments(
$classNamespace,
$visibilityType,
$argumentsCount = 0,
@@ -200,6 +207,32 @@ abstract class BaseTestCase extends TestCase
$reflection = new ReflectionClass($classNamespace);
$method = $reflection->getConstructor();
return $this->verifyMethodVisibilityAndArguments($classNamespace, $method, $visibilityType, $argumentsCount, $requiredArgumentsCount);
static::assertMethodVisibilityAndArguments($classNamespace, $method, $visibilityType, $argumentsCount, $requiredArgumentsCount);
}
/**
* Asserts that class with given namespace has no constructor
*
* @param string $classNamespace Namespace of class that contains constructor to verify
*/
protected static function assertHasNoConstructor($classNamespace)
{
/*
* Let's grab the constructor
*/
$reflection = new ReflectionClass($classNamespace);
$constructor = $reflection->getConstructor();
static::assertNull($constructor);
}
/**
* Sets path of directory with data used by test cases
*
* @param string $testsDataDirPath Path of directory with data used by test cases
*/
protected static function setTestsDataDirPath($testsDataDirPath)
{
static::$testsDataDirPath = $testsDataDirPath;
}
}

View File

@@ -1,17 +1,23 @@
<?php
namespace Meritoo\Common\Test\Base;
/**
* (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\Traits\Test\Base;
use Generator;
use Meritoo\Common\Type\Base\BaseType;
/**
* Base test case for the type of something
* Trait for the base test case for the type of something
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
abstract class BaseTypeTestCase extends BaseTestCase
trait BaseTypeTestCaseTrait
{
/**
* Verifies availability of all types

View File

@@ -6,18 +6,20 @@
* file that was distributed with this source code.
*/
namespace Meritoo\Common\Utilities;
namespace Meritoo\Common\Type;
use DateTime;
use Meritoo\Common\Type\Base\BaseType;
use Meritoo\Common\Utilities\Date;
/**
* A date's period.
* Contains start and end date of the period.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DatePeriod
class DatePeriod extends BaseType
{
/**
* The period constant: last month
@@ -108,17 +110,6 @@ class DatePeriod
$this->endDate = $endDate;
}
/**
* Returns information if given period is correct
*
* @param int $period The period to verify
* @return bool
*/
public static function isCorrectPeriod($period)
{
return in_array($period, Reflection::getConstants(__CLASS__));
}
/**
* Returns formatted one of the period's date: start date or end date
*

View File

@@ -11,8 +11,8 @@ namespace Meritoo\Common\Utilities;
/**
* Useful arrays methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Arrays
{

View File

@@ -11,8 +11,8 @@ namespace Meritoo\Common\Utilities;
/**
* Useful methods for bundle
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Bundle
{

View File

@@ -12,12 +12,13 @@ use DateInterval;
use DateTime;
use Meritoo\Common\Exception\Date\UnknownDatePartTypeException;
use Meritoo\Common\Type\DatePartType;
use Meritoo\Common\Type\DatePeriod;
/**
* Useful date methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Date
{
@@ -66,97 +67,105 @@ class Date
* The dates are returned in an array with indexes 'start' and 'end'.
*
* @param int $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK.
* @return DatePeriod
* @return null|DatePeriod
*/
public static function getDatesForPeriod($period)
{
$datePeriod = null;
if (DatePeriod::isCorrectPeriod($period)) {
$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);
$dateStart = $lastMonth->getEndDate();
$dateStart->add(new DateInterval('P1D'));
$dateEnd = $nextMonth->getStartDate();
$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();
if (DatePeriod::LAST_YEAR == $period || DatePeriod::NEXT_YEAR == $period) {
$yearDifference = 1;
if (DatePeriod::LAST_YEAR == $period) {
$yearDifference *= -1;
}
$modifyString = sprintf('%s year', $yearDifference);
$dateStart->modify($modifyString);
$dateEnd->modify($modifyString);
}
$year = $dateStart->format('Y');
$dateStart->setDate($year, 1, 1);
$dateEnd->setDate($year, 12, 31);
break;
}
if (null !== $dateStart && null !== $dateEnd) {
$dateStart->setTime(0, 0, 0);
$dateEnd->setTime(23, 59, 59);
$datePeriod = new DatePeriod($dateStart, $dateEnd);
}
/*
* Type of period is incorrect?
* Nothing to do
*/
if (!(new DatePeriod())->isCorrectType($period)) {
return null;
}
return $datePeriod;
$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);
$dateStart = $lastMonth->getEndDate();
$dateStart->add(new DateInterval('P1D'));
$dateEnd = $nextMonth->getStartDate();
$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();
if (DatePeriod::LAST_YEAR == $period || DatePeriod::NEXT_YEAR == $period) {
$yearDifference = 1;
if (DatePeriod::LAST_YEAR == $period) {
$yearDifference *= -1;
}
$modifyString = sprintf('%s year', $yearDifference);
$dateStart->modify($modifyString);
$dateEnd->modify($modifyString);
}
$year = $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, 0);
$dateEnd->setTime(23, 59, 59);
return new DatePeriod($dateStart, $dateEnd);
}
/**

View File

@@ -11,8 +11,8 @@ namespace Meritoo\Common\Utilities;
/**
* Useful locale methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Locale
{

View File

@@ -11,8 +11,8 @@ namespace Meritoo\Common\Utilities;
/**
* Useful methods for mime types of files
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MimeTypes
{

View File

@@ -15,8 +15,8 @@ use Transliterator;
/**
* Miscellaneous methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Miscellaneous
{

View File

@@ -17,8 +17,8 @@ use Doctrine\ORM\QueryBuilder;
/**
* Useful methods for query builder (the Doctrine's QueryBuilder class)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class QueryBuilderUtility
{
@@ -33,6 +33,10 @@ class QueryBuilderUtility
{
$aliases = $queryBuilder->getRootAliases();
/*
* No aliases?
* Nothing to do
*/
if (empty($aliases)) {
return null;
}
@@ -42,7 +46,8 @@ class QueryBuilderUtility
/**
* Returns alias of given property joined in given query builder
* If the join does not exist, null is returned.
*
* If there are no joins or the join does not exist, null is returned.
* It's also information if given property is already joined in given query builder.
*
* @param QueryBuilder $queryBuilder The query builder to verify
@@ -53,6 +58,10 @@ class QueryBuilderUtility
{
$joins = $queryBuilder->getDQLPart('join');
/*
* No joins?
* Nothing to do
*/
if (empty($joins)) {
return null;
}
@@ -99,33 +108,43 @@ class QueryBuilderUtility
*/
public static function setCriteria(QueryBuilder $queryBuilder, array $criteria = [], $alias = '')
{
if (!empty($criteria)) {
if (empty($alias)) {
$alias = self::getRootAlias($queryBuilder);
}
/*
* No criteria used in WHERE clause?
* Nothing to do
*/
if (empty($criteria)) {
return $queryBuilder;
}
foreach ($criteria as $column => $value) {
$compareOperator = '=';
/*
* No alias provided?
* Let's use root alias
*/
if (empty($alias)) {
$alias = self::getRootAlias($queryBuilder);
}
if (is_array($value) && !empty($value)) {
if (2 == count($value)) {
$compareOperator = $value[1];
}
foreach ($criteria as $column => $value) {
$compareOperator = '=';
$value = $value[0];
if (is_array($value) && !empty($value)) {
if (2 == count($value)) {
$compareOperator = $value[1];
}
$predicate = sprintf('%s.%s %s :%s', $alias, $column, $compareOperator, $column);
if (null === $value) {
$predicate = $queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $column));
unset($criteria[$column]);
} else {
$queryBuilder->setParameter($column, $value);
}
$queryBuilder = $queryBuilder->andWhere($predicate);
$value = $value[0];
}
$predicate = sprintf('%s.%s %s :%s', $alias, $column, $compareOperator, $column);
if (null === $value) {
$predicate = $queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $column));
unset($criteria[$column]);
} else {
$queryBuilder->setParameter($column, $value);
}
$queryBuilder = $queryBuilder->andWhere($predicate);
}
return $queryBuilder;
@@ -143,7 +162,7 @@ class QueryBuilderUtility
public static function deleteEntities(EntityManager $entityManager, $entities, $flushDeleted = true)
{
/*
* No entities found?
* No entities provided?
* Nothing to do
*/
if (empty($entities)) {
@@ -169,24 +188,30 @@ class QueryBuilderUtility
* Attention. Existing parameters will be overridden.
*
* @param QueryBuilder $queryBuilder The query builder
* @param array|ArrayCollection $parameters Parameters to add. Collection of instances of
* Doctrine\ORM\Query\Parameter class or an array with key-value pairs.
* @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)
{
if (!empty($parameters)) {
foreach ($parameters as $key => $parameter) {
$name = $key;
$value = $parameter;
/*
* No parameters?
* Nothing to do
*/
if (empty($parameters)) {
return $queryBuilder;
}
if ($parameter instanceof Parameter) {
$name = $parameter->getName();
$value = $parameter->getValue();
}
foreach ($parameters as $key => $parameter) {
$name = $key;
$value = $parameter;
$queryBuilder->setParameter($name, $value);
if ($parameter instanceof Parameter) {
$name = $parameter->getName();
$value = $parameter->getValue();
}
$queryBuilder->setParameter($name, $value);
}
return $queryBuilder;

View File

@@ -8,9 +8,9 @@
namespace Meritoo\Common\Utilities;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Util\ClassUtils;
use Doctrine\Common\Util\Inflector;
use Meritoo\Common\Collection\Collection;
use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
@@ -23,8 +23,8 @@ use ReflectionProperty;
/**
* Useful reflection methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Reflection
{
@@ -74,8 +74,8 @@ class Reflection
}
/**
* Returns maximum constant from all constants of given class / object.
* Values of constants should be integers.
* Returns maximum integer value of constant of given class / object.
* Constants whose values are integers are considered only.
*
* @param object|string $class The object or name of object's class
* @return int|null
@@ -229,17 +229,29 @@ class Reflection
if ($class->hasProperty($property) || $force) {
$property = Inflector::classify($property);
$methodPrefixes = [
$getterPrefixes = [
'get',
'has',
'is',
];
foreach ($methodPrefixes as $prefix) {
$method = sprintf('%s%s', $prefix, $property);
foreach ($getterPrefixes as $prefix) {
$getterName = sprintf('%s%s', $prefix, $property);
if ($class->hasMethod($method)) {
$value = $object->{$method}();
if ($class->hasMethod($getterName)) {
$method = new ReflectionMethod($object, $getterName);
/*
* Getter is not accessible publicly?
* I have to skip it, to avoid an error like this:
*
* Call to protected method My\ExtraClass::getExtraProperty() from context 'My\ExtraClass'
*/
if ($method->isProtected() || $method->isPrivate()) {
continue;
}
$value = $object->{$getterName}();
$valueFound = true;
break;
}
@@ -248,13 +260,14 @@ class Reflection
if (!$valueFound && null !== $reflectionProperty) {
/*
* Oops, we have got exception.
* Oops, value of the property is still unknown
*
* 3rd try:
* Let's try modify accessibility of the property and try again to get value.
* Let's modify accessibility of the property and try again to get value
*/
$reflectionProperty->setAccessible(true);
$value = $reflectionProperty->getValue($object);
$reflectionProperty->setAccessible(false);
}
}
}
@@ -275,6 +288,14 @@ class Reflection
*/
public static function getPropertyValues($objects, $property, $force = false)
{
/*
* No objects?
* Nothing to do
*/
if (empty($objects)) {
return [];
}
if ($objects instanceof Collection) {
$objects = $objects->toArray();
}
@@ -417,12 +438,14 @@ class Reflection
/**
* 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 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 array|ReflectionProperty
*/
public static function getProperties($source, $filter = null)
public static function getProperties($source, $filter = null, $includeParents = false)
{
$className = self::getClassName($source);
$reflection = new ReflectionClass($className);
@@ -434,14 +457,26 @@ class Reflection
+ ReflectionProperty::IS_STATIC;
}
return $reflection->getProperties($filter);
$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
* 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 ReflectionClass
* @return ReflectionClass|bool
*/
public static function getParentClass($source)
{

View File

@@ -14,8 +14,8 @@ use Meritoo\Common\Exception\Regex\InvalidColorHexValueException;
/**
* Useful regular expressions methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Regex
{

View File

@@ -14,8 +14,8 @@ use Doctrine\ORM\QueryBuilder;
/**
* Useful methods for repository
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Repository
{

View File

@@ -11,8 +11,8 @@ namespace Meritoo\Common\Utilities;
/**
* Useful uri methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Uri
{

View File

@@ -15,8 +15,8 @@ use SimpleXMLElement;
/**
* Useful XML-related methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Xml
{

View File

@@ -14,7 +14,7 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Tests of the collection of elements
* Test case of the collection of elements
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
@@ -306,7 +306,7 @@ class CollectionTest extends BaseTestCase
public function testExistsVisibilityAndArguments()
{
$this->verifyMethodVisibilityAndArguments(Collection::class, 'exists', OopVisibilityType::IS_PRIVATE, 1, 1);
static::assertMethodVisibilityAndArguments(Collection::class, 'exists', OopVisibilityType::IS_PRIVATE, 1, 1);
}
/**

View File

@@ -9,17 +9,23 @@
namespace Meritoo\Common\Test\Exception\Base;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\Base\BaseType;
use PHPUnit\Framework\TestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Tests of the exception used while type of something is unknown
* Test case of the exception used while type of something is unknown
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownTypeExceptionTest extends TestCase
class UnknownTypeExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownTestTypeException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
public function testWithoutException()
{
self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2'));
@@ -27,7 +33,7 @@ class UnknownTypeExceptionTest extends TestCase
public function testTheException()
{
$this->expectException(UnknownTestTypeException::class);
$this->setExpectedException(UnknownTestTypeException::class);
self::assertEmpty((new TestService())->getTranslatedType('test_3'));
}
}

View File

@@ -0,0 +1,71 @@
<?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\Test\Exception\Date;
use Generator;
use Meritoo\Common\Exception\Date\UnknownDatePartTypeException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\DatePartType;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while type of date part, e.g. "year", is unknown
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownDatePartTypeExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownDatePartTypeException::class, OopVisibilityType::IS_PUBLIC, 2, 2);
}
/**
* @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 testConstructorMessage($unknownDatePart, $value, $expectedMessage)
{
$exception = new UnknownDatePartTypeException($unknownDatePart, $value);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides type of date part, incorrect value and expected exception's message
*
* @return Generator
*/
public function provideDatePartAndValue()
{
$template = 'The \'%s\' type of date part (with value %s) is unknown. Probably doesn\'t exist or there is a'
. ' typo. You should use one of these types: day, hour, minute, month, second, year.';
yield[
DatePartType::DAY,
'44',
sprintf($template, DatePartType::DAY, '44'),
];
yield[
DatePartType::MONTH,
'22',
sprintf($template, DatePartType::MONTH, '22'),
];
yield[
DatePartType::MINUTE,
'77',
sprintf($template, DatePartType::MINUTE, '77'),
];
}
}

View File

@@ -0,0 +1,60 @@
<?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\Test\Exception\File;
use Generator;
use Meritoo\Common\Exception\File\EmptyFileException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while file with given path is empty (has no content)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class EmptyFileExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFileException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @param string $emptyFilePath Path of the empty file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testConstructorMessage($emptyFilePath, $expectedMessage)
{
$exception = new EmptyFileException($emptyFilePath);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides path of the empty file and expected exception's message
*
* @return Generator
*/
public function providePathOfFile()
{
$template = 'File with path \'%s\' is empty (has no content). Did you provide path of proper file?';
yield[
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield[
'images/show/car.jpg',
sprintf($template, 'images/show/car.jpg'),
];
}
}

View File

@@ -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\Test\Exception\File;
use Meritoo\Common\Exception\File\EmptyFilePathException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while path of given file is empty
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class EmptyFilePathExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFilePathException::class, OopVisibilityType::IS_PUBLIC);
}
public function testConstructorMessage()
{
$exception = new EmptyFilePathException();
static::assertEquals('Path of the file is empty. Did you provide path of proper file?', $exception->getMessage());
}
}

View File

@@ -0,0 +1,60 @@
<?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\Test\Exception\File;
use Generator;
use Meritoo\Common\Exception\File\NotExistingFileException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while file with given path does not exist
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class NotExistingFileExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(NotExistingFileException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @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 = new NotExistingFileException($notExistingFilePath);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides path of not existing file and expected exception's message
*
* @return Generator
*/
public function providePathOfFile()
{
$template = 'File with path \'%s\' does not exist (or is not readable). Did you provide path of proper file?';
yield[
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield[
'images/show/car.jpg',
sprintf($template, 'images/show/car.jpg'),
];
}
}

View File

@@ -0,0 +1,65 @@
<?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\Test\Exception\Method;
use Generator;
use Meritoo\Common\Exception\Method\DisabledMethodException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while method cannot be called, because is disabled
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DisabledMethodExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(DisabledMethodException::class, OopVisibilityType::IS_PUBLIC, 2, 1);
}
/**
* @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 = new DisabledMethodException($disabledMethod, $alternativeMethod);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides name of the disabled method, name of the alternative method and expected exception's message
*
* @return Generator
*/
public function provideMethodsNames()
{
$templateShort = 'Method %s() cannot be called, because is disabled.';
$templateLong = $templateShort . ' Use %s() instead.';
yield[
'FooBar::loremIpsum',
'',
sprintf($templateShort, 'FooBar::loremIpsum'),
];
yield[
'FooBar::loremIpsum',
'AnotherClass::alternativeMethod',
sprintf($templateLong, 'FooBar::loremIpsum', 'AnotherClass::alternativeMethod'),
];
}
}

View File

@@ -0,0 +1,73 @@
<?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\Test\Exception\Reflection;
use Generator;
use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while name of class or trait cannot be resolved
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class CannotResolveClassNameExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(CannotResolveClassNameException::class, OopVisibilityType::IS_PUBLIC, 2, 1);
}
/**
* @param array|object|string $source Source of the class's / trait's name. It can be an array of objects,
* namespaces, object or namespace.
* @param bool $forClass 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 testConstructorMessage($source, $forClass, $expectedMessage)
{
$exception = new CannotResolveClassNameException($source, $forClass);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides source of the class's / trait's name, information if message of this exception should be prepared for
* class and the expected exception's message
*
* @return Generator
*/
public function provideClassName()
{
yield[
'Not\Existing\Class',
true,
'Name of class from given \'string\' Not\Existing\Class cannot be resolved. Is there everything ok?',
];
yield[
'Not\Existing\Trait',
false,
'Name of trait from given \'string\' Not\Existing\Trait cannot be resolved. Is there everything ok?',
];
yield[
[
new \stdClass(),
new \stdClass(),
],
true,
'Name of class from given \'array\' cannot be resolved. Is there everything ok?',
];
}
}

View File

@@ -0,0 +1,65 @@
<?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\Test\Exception\Reflection;
use Generator;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while given class has no child classes
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MissingChildClassesExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(MissingChildClassesException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @param array|object|string $parentClass Class that hasn't child classes, but it should. An array of objects,
* strings, object or string.
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideParentClass
*/
public function testConstructorMessage($parentClass, $expectedMessage)
{
$exception = new MissingChildClassesException($parentClass);
static::assertEquals($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()
{
$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

@@ -0,0 +1,74 @@
<?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\Test\Exception\Reflection;
use Generator;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while given class has more than one child class
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class TooManyChildClassesExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(TooManyChildClassesException::class, OopVisibilityType::IS_PUBLIC, 2, 2);
}
/**
* @param array|object|string $parentClass Class that has more than one child class, but it shouldn't. An array
* of objects, strings, object or string.
* @param array $childClasses Child classes
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideParentAndChildClasses
*/
public function testConstructorMessage($parentClass, array $childClasses, $expectedMessage)
{
$exception = new TooManyChildClassesException($parentClass, $childClasses);
static::assertEquals($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()
{
$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

@@ -0,0 +1,60 @@
<?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\Test\Exception\Regex;
use Generator;
use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while length of given hexadecimal value of color is incorrect
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class IncorrectColorHexLengthExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(IncorrectColorHexLengthException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @param string $color Incorrect hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = new IncorrectColorHexLengthException($color);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides incorrect hexadecimal value of color and expected exception's message
*
* @return Generator
*/
public function provideColor()
{
$template = 'Length of hexadecimal value of color \'%s\' is incorrect. It\'s %d, but it should be 3 or 6. Is there everything ok?';
yield[
'',
sprintf($template, '', strlen('')),
];
yield[
'aa-bb-cc',
sprintf($template, 'aa-bb-cc', strlen('aa-bb-cc')),
];
}
}

View File

@@ -0,0 +1,60 @@
<?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\Test\Exception\Regex;
use Generator;
use Meritoo\Common\Exception\Regex\InvalidColorHexValueException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while given hexadecimal value of color is invalid
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class InvalidColorHexValueExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidColorHexValueException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @param string $color Invalid hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = new InvalidColorHexValueException($color);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides invalid hexadecimal value of color and expected exception's message
*
* @return Generator
*/
public function provideColor()
{
$template = 'Hexadecimal value of color \'%s\' is invalid. Is there everything ok?';
yield[
'',
sprintf($template, ''),
];
yield[
'aa-bb-cc',
sprintf($template, 'aa-bb-cc'),
];
}
}

View File

@@ -0,0 +1,60 @@
<?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\Test\Exception\Regex;
use Generator;
use Meritoo\Common\Exception\Regex\InvalidUrlException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while url is invalid
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class InvalidUrlExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidUrlException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @param string $url Invalid url
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUrl
*/
public function testConstructorMessage($url, $expectedMessage)
{
$exception = new InvalidUrlException($url);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides invalid url and expected exception's message
*
* @return Generator
*/
public function provideUrl()
{
$template = 'Url \'%s\' is invalid. Is there everything ok?';
yield[
'aa/bb/cc',
sprintf($template, 'aa/bb/cc'),
];
yield[
'http:/images\show\car.jpg',
sprintf($template, 'http:/images\show\car.jpg'),
];
}
}

View File

@@ -0,0 +1,64 @@
<?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\Test\Exception\Type;
use Generator;
use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while the visibility of a property, a method or (as of PHP 7.1.0) a constant is
* unknown
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownOopVisibilityTypeException::class, OopVisibilityType::IS_PUBLIC, 1, 1);
}
/**
* @param string $unknownType Unknown OOP-related visibility
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUnknownType
*/
public function testConstructorMessage($unknownType, $expectedMessage)
{
$exception = new UnknownOopVisibilityTypeException($unknownType);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides path of the empty file and expected exception's message
*
* @return Generator
*/
public function provideUnknownType()
{
$allTypes = (new OopVisibilityType())->getAll();
$template = 'The \'%s\' type of OOP-related visibility is unknown. Probably doesn\'t exist or there is a typo.'
. ' You should use one of these types: %s.';
yield[
'',
sprintf($template, '', implode(', ', $allTypes)),
];
yield[
123,
sprintf($template, 123, implode(', ', $allTypes)),
];
}
}

View File

@@ -1,246 +0,0 @@
<?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\Test\Utilities;
use DateTime;
use Generator;
use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Test\Utilities\Reflection\A;
use Meritoo\Common\Test\Utilities\Reflection\B;
use Meritoo\Common\Test\Utilities\Reflection\C;
use Meritoo\Common\Test\Utilities\Reflection\D;
use Meritoo\Common\Test\Utilities\Reflection\E;
use Meritoo\Common\Utilities\Reflection;
/**
* Tests of the useful reflection methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ReflectionTest extends BaseTestCase
{
/**
* @param mixed $invalidClass Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetClassNameInvalidClass($invalidClass)
{
self::assertNull(Reflection::getClassName($invalidClass));
self::assertNull(Reflection::getClassName(123));
}
public function testGetClassNameNotExistingClass()
{
/*
* Not existing class
*/
self::assertEquals('', Reflection::getClassName('xyz'));
self::assertEquals('', Reflection::getClassName('xyz', true));
}
public function testGetClassNameExistingClass()
{
/*
* Existing class
*/
self::assertEquals(self::class, Reflection::getClassName(self::class));
self::assertEquals('ReflectionTest', Reflection::getClassName(self::class, true));
self::assertEquals(DateTime::class, Reflection::getClassName(new DateTime()));
self::assertEquals(DateTime::class, Reflection::getClassName(new DateTime(), true));
self::assertEquals(DateTime::class, Reflection::getClassName([
new DateTime(),
new DateTime('yesterday'),
]));
}
public function testGetClassNameDuplicatedName()
{
/*
* Class with namespace containing name of class (duplicated string)
*/
if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) {
self::assertEquals('Symfony\Bundle\SecurityBundle\SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle'));
self::assertEquals('SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle', true));
}
}
public function testGetClassNamespaceNotExistingClass()
{
/*
* Not existing class
*/
self::assertEquals('', Reflection::getClassNamespace('xyz'));
}
public function testGetClassNamespaceExistingClass()
{
/*
* Existing class
*/
self::assertEquals('Meritoo\Common\Test\Utilities', Reflection::getClassNamespace(self::class));
self::assertEquals(DateTime::class, Reflection::getClassNamespace(new DateTime()));
self::assertEquals(DateTime::class, Reflection::getClassNamespace([
new DateTime(),
new DateTime('yesterday'),
]));
}
public function testGetClassNamespaceDuplicatedName()
{
/*
* Class with namespace containing name of class (duplicated string)
*/
if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) {
self::assertEquals('Symfony\Bundle\SecurityBundle', Reflection::getClassNamespace('Symfony\Bundle\SecurityBundle\SecurityBundle'));
}
}
/**
* @param mixed $invalidClass Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetChildClassesInvalidClass($invalidClass)
{
$this->expectException(CannotResolveClassNameException::class);
self::assertNull(Reflection::getChildClasses($invalidClass));
self::assertNull(Reflection::getChildClasses(123));
}
public function testGetChildClassesNotExistingClass()
{
$this->expectException(CannotResolveClassNameException::class);
self::assertEquals('', Reflection::getChildClasses('xyz'));
}
public function testGetChildClassesExistingClass()
{
/*
* Attention. I have to create instances of these classes to load them and be available while using
* get_declared_classes() function in the Reflection::getChildClasses() method. Without these instances the
* Reflection::getChildClasses() method returns an empty array even if given class has child classes.
*/
new A();
new B();
new C();
$effect = [
C::class,
];
self::assertEquals($effect, Reflection::getChildClasses(B::class));
$effect = [
B::class,
C::class,
];
self::assertEquals($effect, Reflection::getChildClasses(A::class));
}
public function testGetOneChildClassWithMissingChildClasses()
{
$this->expectException(MissingChildClassesException::class);
self::assertEquals('LoremIpsum', Reflection::getOneChildClass(C::class));
}
public function testGetOneChildClassWithTooManyChildClasses()
{
$this->expectException(TooManyChildClassesException::class);
self::assertEquals(B::class, Reflection::getOneChildClass(A::class));
self::assertEquals(C::class, Reflection::getOneChildClass(A::class));
}
public function testGetOneChildClass()
{
self::assertEquals(C::class, Reflection::getOneChildClass(B::class));
}
public function testGetMethods()
{
self::assertEquals(0, count(Reflection::getMethods(B::class, true)));
self::assertEquals(1, count(Reflection::getMethods(B::class)));
self::assertEquals(1, count(Reflection::getMethods(A::class)));
self::assertEquals(2, count(Reflection::getMethods(C::class, true)));
self::assertEquals(3, count(Reflection::getMethods(C::class)));
}
/**
* @param array|object|string $class An array of objects, namespaces, object or namespace
* @param array|string $trait An array of strings or string
*
* @dataProvider provideInvalidClassAndTrait
*/
public function testUsesTraitInvalidClass($class, $trait)
{
$this->expectException(CannotResolveClassNameException::class);
self::assertNull(Reflection::usesTrait($class, $trait));
}
/**
* @param mixed $trait Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testUsesTraitInvalidTrait($trait)
{
$this->expectException(CannotResolveClassNameException::class);
self::assertNull(Reflection::usesTrait(DateTime::class, $trait));
}
public function testUsesTraitExistingClass()
{
self::assertTrue(Reflection::usesTrait(A::class, E::class));
self::assertFalse(Reflection::usesTrait(B::class, E::class));
self::assertFalse(Reflection::usesTrait(C::class, E::class));
self::assertFalse(Reflection::usesTrait(D::class, E::class));
}
public function testUsesTraitExistingClassAndVerifyParents()
{
self::assertTrue(Reflection::usesTrait(A::class, E::class, true));
self::assertTrue(Reflection::usesTrait(B::class, E::class, true));
self::assertTrue(Reflection::usesTrait(C::class, E::class, true));
self::assertFalse(Reflection::usesTrait(D::class, E::class, true));
}
/**
* Provides invalid class and trait
*
* @return Generator
*/
public function provideInvalidClassAndTrait()
{
yield[
'',
'',
];
yield[
null,
null,
];
yield[
0,
0,
];
yield[
[],
[],
];
}
}

View File

@@ -0,0 +1,176 @@
<?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\Test\Test\Base;
use DateTime;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\GeneratorUtility;
/**
* Test case of the base test case with common methods and data providers
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class BaseTestCaseTest extends BaseTestCase
{
public function testConstructor()
{
static::assertConstructorVisibilityAndArguments(BaseTestCase::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testProvideEmptyValue()
{
$elements = [
[''],
[' '],
[null],
[0],
[false],
[[]],
];
$generator = (new SimpleTestCase())->provideEmptyValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
public function testProvideBooleanValue()
{
$elements = [
[false],
[true],
];
$generator = (new SimpleTestCase())->provideBooleanValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
public function testProvideDateTimeInstance()
{
$dateFormat = 'Y-m-d H:i';
$expectedElements = [
[new DateTime()],
[new DateTime('yesterday')],
[new DateTime('now')],
[new DateTime('tomorrow')],
];
$generator = (new SimpleTestCase())->provideDateTimeInstance();
$generatedElements = GeneratorUtility::getGeneratorElements($generator);
/* @var DateTime $instance1 */
$instance1 = $generatedElements[0][0];
/* @var DateTime $instance2 */
$instance2 = $generatedElements[1][0];
/* @var DateTime $instance3 */
$instance3 = $generatedElements[2][0];
/* @var DateTime $instance4 */
$instance4 = $generatedElements[3][0];
self::assertCount(count($expectedElements), $generatedElements);
self::assertEquals($instance1->format($dateFormat), (new DateTime())->format($dateFormat));
self::assertEquals($instance2->format($dateFormat), (new DateTime('yesterday'))->format($dateFormat));
self::assertEquals($instance3->format($dateFormat), (new DateTime('now'))->format($dateFormat));
self::assertEquals($instance4->format($dateFormat), (new DateTime('tomorrow'))->format($dateFormat));
}
public function testProvideDateTimeRelativeFormat()
{
$elements = [
['now'],
['yesterday'],
['tomorrow'],
['back of 10'],
['front of 10'],
['last day of February'],
['first day of next month'],
['last day of previous month'],
['last day of next month'],
['Y-m-d'],
['Y-m-d 10:00'],
];
$generator = (new SimpleTestCase())->provideDateTimeRelativeFormat();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
public function testProvideNotExistingFilePath()
{
$elements = [
['lets-test.doc'],
['lorem/ipsum.jpg'],
['surprise/me/one/more/time.txt'],
];
$generator = (new SimpleTestCase())->provideNotExistingFilePath();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
}
/**
* @param string $fileName Name of file
* @param string $directoryPath Path of directory containing the file
*
* @dataProvider provideFileNameAndDirectoryPath
*/
public function testGetFilePathForTesting($fileName, $directoryPath)
{
$path = (new SimpleTestCase())->getFilePathForTesting($fileName, $directoryPath);
if (!empty($directoryPath)) {
$directoryPath .= '/';
}
$expectedContains = sprintf('/.data/tests/%s%s', $directoryPath, $fileName);
static::assertContains($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',
];
}
}
/**
* Simple test case
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class SimpleTestCase extends BaseTestCase
{
}

View File

@@ -9,17 +9,22 @@
namespace Meritoo\Common\Test\Type\Base;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\Base\BaseType;
use PHPUnit\Framework\TestCase;
/**
* Tests of the base / abstract type of something
* Test case of the base / abstract type of something
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class BaseTypeTest extends TestCase
class BaseTypeTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(BaseType::class);
}
/**
* @param BaseType $type Type of something
* @param array $expectedTypes Expected concrete types of given instance of type

View File

@@ -12,7 +12,7 @@ use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\Common\Type\DatePartType;
/**
* Tests of the type of date part, e.g. "year"
* Test case of the type of date part, e.g. "year"
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl

View File

@@ -6,25 +6,25 @@
* file that was distributed with this source code.
*/
namespace Meritoo\Common\Test\Utilities;
namespace Meritoo\Common\Test\Type;
use DateTime;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\Common\Type\DatePeriod;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\DatePeriod;
/**
* Tests of date's period
* Test case of date's period
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DatePeriodTest extends BaseTestCase
class DatePeriodTest extends BaseTypeTestCase
{
public function testConstructorVisibilityAndArguments()
{
$this->verifyConstructorVisibilityAndArguments(DatePeriod::class, OopVisibilityType::IS_PUBLIC, 2, 0);
static::assertConstructorVisibilityAndArguments(DatePeriod::class, OopVisibilityType::IS_PUBLIC, 2, 0);
}
/**
@@ -58,33 +58,6 @@ class DatePeriodTest extends BaseTestCase
self::assertEquals($endDate, $period->getEndDate());
}
/**
* @param mixed $period Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsCorrectPeriodEmptyPeriod($period)
{
self::assertFalse(DatePeriod::isCorrectPeriod($period));
}
/**
* @param int $period Incorrect period to verify
* @dataProvider provideIncorrectPeriod
*/
public function testIsCorrectPeriodIncorrectPeriod($period)
{
self::assertFalse(DatePeriod::isCorrectPeriod($period));
}
/**
* @param int $period The period to verify
* @dataProvider providePeriod
*/
public function testIsCorrectPeriod($period)
{
self::assertTrue(DatePeriod::isCorrectPeriod($period));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
@@ -142,36 +115,6 @@ class DatePeriodTest extends BaseTestCase
];
}
/**
* Provides incorrect period
*
* @return Generator
*/
public function provideIncorrectPeriod()
{
yield[-1];
yield[0];
yield[10];
}
/**
* Provides period to verify
*
* @return Generator
*/
public function providePeriod()
{
yield[DatePeriod::LAST_WEEK];
yield[DatePeriod::THIS_WEEK];
yield[DatePeriod::NEXT_WEEK];
yield[DatePeriod::LAST_MONTH];
yield[DatePeriod::THIS_MONTH];
yield[DatePeriod::NEXT_MONTH];
yield[DatePeriod::LAST_YEAR];
yield[DatePeriod::THIS_YEAR];
yield[DatePeriod::NEXT_YEAR];
}
/**
* Provides period and incorrect format of date to verify
*
@@ -270,4 +213,68 @@ class DatePeriodTest extends BaseTestCase
'2002-02-02 00:00',
];
}
/**
* Returns all expected types of the tested type
*
* @return array
*/
protected function getAllExpectedTypes()
{
return [
'LAST_MONTH' => DatePeriod::LAST_MONTH,
'LAST_WEEK' => DatePeriod::LAST_WEEK,
'LAST_YEAR' => DatePeriod::LAST_YEAR,
'NEXT_MONTH' => DatePeriod::NEXT_MONTH,
'NEXT_WEEK' => DatePeriod::NEXT_WEEK,
'NEXT_YEAR' => DatePeriod::NEXT_YEAR,
'THIS_MONTH' => DatePeriod::THIS_MONTH,
'THIS_WEEK' => DatePeriod::THIS_WEEK,
'THIS_YEAR' => DatePeriod::THIS_YEAR,
];
}
/**
* {@inheritdoc}
*/
protected function getTestedTypeInstance()
{
return new DatePeriod();
}
/**
* {@inheritdoc}
*/
public function provideTypeToVerify()
{
yield[
'',
false,
];
yield[
-1,
false,
];
yield[
true,
false,
];
yield[
DatePeriod::LAST_MONTH,
true,
];
yield[
DatePeriod::NEXT_WEEK,
true,
];
yield[
DatePeriod::THIS_YEAR,
true,
];
}
}

View File

@@ -8,16 +8,16 @@
namespace Meritoo\Common\Test\Utilities;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Arrays;
use PHPUnit\Framework\TestCase;
/**
* Tests of the useful arrays methods
* Test case of the useful arrays methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ArraysTest extends TestCase
class ArraysTest extends BaseTestCase
{
private $simpleArray;
private $simpleArrayWithKeys;
@@ -25,6 +25,11 @@ class ArraysTest extends TestCase
private $complexArray;
private $superComplexArray;
public function testConstructor()
{
static::assertHasNoConstructor(Arrays::class);
}
public function testValues2string()
{
/*

View File

@@ -8,17 +8,22 @@
namespace Meritoo\Common\Test\Utilities;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Bundle;
use PHPUnit\Framework\TestCase;
/**
* Tests of the useful methods for bundle
* Test case of the useful methods for bundle
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class BundleTest extends TestCase
class BundleTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(Bundle::class);
}
public function testGetBundleViewPathEmptyPathAndBundle()
{
self::assertNull(Bundle::getBundleViewPath('', ''));

View File

@@ -13,7 +13,7 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Composer;
/**
* Tests of the useful Composer-related methods
* Test case of the useful Composer-related methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
@@ -27,6 +27,11 @@ class ComposerTest extends BaseTestCase
*/
private $composerJsonPath;
public function testConstructor()
{
static::assertHasNoConstructor(Composer::class);
}
/**
* @param string $composerJsonPath Empty value, e.g. ""
* @dataProvider provideEmptyValue
@@ -83,6 +88,6 @@ class ComposerTest extends BaseTestCase
{
parent::setUp();
$this->composerJsonPath = $this->getFilePathToTests(Composer::FILE_NAME_MAIN);
$this->composerJsonPath = $this->getFilePathForTesting(Composer::FILE_NAME_MAIN);
}
}

View File

@@ -13,16 +13,22 @@ use DateTime;
use Generator;
use Meritoo\Common\Exception\Date\UnknownDatePartTypeException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\DatePeriod;
use Meritoo\Common\Utilities\Date;
/**
* Tests of the Date methods (only static functions)
* Test case of the Date methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DateTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(Date::class);
}
/**
* @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue
@@ -218,7 +224,7 @@ class DateTest extends BaseTestCase
*/
public function testGetDayOfWeekIncorrectValues($year, $month, $day)
{
$this->expectException(UnknownDatePartTypeException::class);
$this->setExpectedException(UnknownDatePartTypeException::class);
self::assertEmpty(Date::getDayOfWeek($year, $month, $day));
}
@@ -501,6 +507,35 @@ class DateTest extends BaseTestCase
self::assertTrue($randomDate >= $intervalMinDate && $randomDate <= $intervalMaxDate);
}
/**
* @param mixed $period Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetDatesForPeriodUsingEmptyPeriod($period)
{
self::assertNull(Date::getDatesForPeriod($period));
}
/**
* @param int $period Incorrect period to verify
* @dataProvider provideIncorrectPeriod
*/
public function testGetDatesForPeriodUsingIncorrectPeriod($period)
{
self::assertNull(Date::getDatesForPeriod($period));
}
/**
* @param int $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK.
* @param DatePeriod $expected Expected start and end date for given period
*
* @dataProvider provideCorrectPeriod
*/
public function testGetDatesForPeriod($period, DatePeriod $expected)
{
self::assertEquals($expected, Date::getDatesForPeriod($period));
}
/**
* Provides incorrect invalidCount of DateTime
*
@@ -753,4 +788,112 @@ class DateTest extends BaseTestCase
50,
];
}
/**
* Provides incorrect period
*
* @return Generator
*/
public function provideIncorrectPeriod()
{
yield[-1];
yield[0];
yield[10];
}
/**
* Provides correct period
*
* @return Generator
*/
public function provideCorrectPeriod()
{
yield[
DatePeriod::LAST_WEEK,
new DatePeriod(
(new DateTime('this week'))->sub(new DateInterval('P7D'))->setTime(0, 0, 0),
(new DateTime('this week'))->sub(new DateInterval('P1D'))->setTime(23, 59, 59)
),
];
yield[
DatePeriod::THIS_WEEK,
new DatePeriod(
(new DateTime('this week'))->setTime(0, 0, 0),
(new DateTime('this week'))->add(new DateInterval('P6D'))->setTime(23, 59, 59)
),
];
yield[
DatePeriod::NEXT_WEEK,
new DatePeriod(
(new DateTime('this week'))->add(new DateInterval('P7D'))->setTime(0, 0, 0),
(new DateTime('this week'))->add(new DateInterval('P7D'))->add(new DateInterval('P6D'))->setTime(23, 59, 59)
),
];
yield[
DatePeriod::LAST_MONTH,
new DatePeriod(
(new DateTime('first day of last month'))->setTime(0, 0, 0),
(new DateTime('last day of last month'))->setTime(23, 59, 59)
),
];
yield[
DatePeriod::THIS_MONTH,
new DatePeriod(
Date::getDatesForPeriod(DatePeriod::LAST_MONTH)
->getEndDate()
->add(new DateInterval('P1D'))
->setTime(0, 0, 0),
Date::getDatesForPeriod(DatePeriod::NEXT_MONTH)
->getStartDate()
->sub(new DateInterval('P1D'))
->setTime(23, 59, 59)
),
];
yield[
DatePeriod::NEXT_MONTH,
new DatePeriod(
(new DateTime('first day of next month'))->setTime(0, 0, 0),
(new DateTime('last day of next month'))->setTime(23, 59, 59)
),
];
$lastYearStart = (new DateTime())->modify('-1 year');
$lastYearEnd = (new DateTime())->modify('-1 year');
$year = $lastYearStart->format('Y');
yield[
DatePeriod::LAST_YEAR,
new DatePeriod(
$lastYearStart->setDate($year, 1, 1)->setTime(0, 0, 0),
$lastYearEnd->setDate($year, 12, 31)->setTime(23, 59, 59)
),
];
$year = (new DateTime())->format('Y');
yield[
DatePeriod::THIS_YEAR,
new DatePeriod(
(new DateTime())->setDate($year, 1, 1)->setTime(0, 0, 0),
(new DateTime())->setDate($year, 12, 31)->setTime(23, 59, 59)
),
];
$nextYearStart = (new DateTime())->modify('1 year');
$nextYearEnd = (new DateTime())->modify('1 year');
$year = $nextYearStart->format('Y');
yield[
DatePeriod::NEXT_YEAR,
new DatePeriod(
$nextYearStart->setDate($year, 1, 1)->setTime(0, 0, 0),
$nextYearEnd->setDate($year, 12, 31)->setTime(23, 59, 59)
),
];
}
}

View File

@@ -12,13 +12,18 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\GeneratorUtility;
/**
* Tests of the useful methods for the Generator class
* Test case of the useful methods for the Generator class
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class GeneratorUtilityTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(GeneratorUtility::class);
}
public function testGetGeneratorElements()
{
/*

View File

@@ -13,13 +13,18 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Locale;
/**
* Tests of the useful locale methods
* Test case of the useful locale methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class LocaleTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(Locale::class);
}
/**
* @param mixed $languageCode Empty value, e.g. ""
* @dataProvider provideEmptyValue

View File

@@ -13,13 +13,18 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\MimeTypes;
/**
* Tests of the useful methods for mime types of files
* Test case of the useful methods for mime types of files
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MimeTypesTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(MimeTypes::class);
}
/**
* @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue
@@ -442,12 +447,12 @@ class MimeTypesTest extends BaseTestCase
public function provideFilePathToGetMimeTypeOfRealFile()
{
yield[
$this->getFilePathToTests('minion.jpg'),
$this->getFilePathForTesting('minion.jpg'),
'image/jpeg',
];
yield[
$this->getFilePathToTests('lorem-ipsum.txt'),
$this->getFilePathForTesting('lorem-ipsum.txt'),
'text/plain',
];
}
@@ -460,12 +465,12 @@ class MimeTypesTest extends BaseTestCase
public function provideExistingFilePathToCheckIsImagePath()
{
yield[
$this->getFilePathToTests('minion.jpg'),
$this->getFilePathForTesting('minion.jpg'),
true,
];
yield[
$this->getFilePathToTests('lorem-ipsum.txt'),
$this->getFilePathForTesting('lorem-ipsum.txt'),
false,
];
}

View File

@@ -17,7 +17,7 @@ use Meritoo\Common\Utilities\Miscellaneous;
use stdClass;
/**
* Tests of the Miscellaneous methods (only static functions)
* Test case of the Miscellaneous methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
@@ -28,6 +28,11 @@ class MiscellaneousTest extends BaseTestCase
private $stringCommaSeparated;
private $stringDotSeparated;
public function testConstructor()
{
static::assertHasNoConstructor(Miscellaneous::class);
}
public function testGetDirectoryContent()
{
$directoryPath = __DIR__ . '/../';
@@ -154,8 +159,8 @@ class MiscellaneousTest extends BaseTestCase
$expected = "int(123)\n";
if ($xdebugLoaded) {
$libraryPath = realpath(sprintf('%s%s', dirname(__FILE__), '/../../../../..'));
$filePath = sprintf('%s%s', $libraryPath, '/src/Meritoo/Common/Utilities/Miscellaneous.php:');
$libraryPath = realpath(sprintf('%s%s', dirname(__FILE__), '/../..'));
$filePath = sprintf('%s%s', $libraryPath, '/src/Utilities/Miscellaneous.php:');
/*
* Attention. I have to use "\d+" at the end of $filePath, because number of line may be different if new
@@ -658,7 +663,8 @@ class MiscellaneousTest extends BaseTestCase
public function testGetInvertedColorWithIncorrectLength()
{
$this->expectException(IncorrectColorHexLengthException::class);
$this->setExpectedException(IncorrectColorHexLengthException::class);
Miscellaneous::getInvertedColor(null);
Miscellaneous::getInvertedColor('');
Miscellaneous::getInvertedColor(1);
@@ -671,7 +677,8 @@ class MiscellaneousTest extends BaseTestCase
public function testGetInvertedColorWithInvalidValue()
{
$this->expectException(InvalidColorHexValueException::class);
$this->setExpectedException(InvalidColorHexValueException::class);
Miscellaneous::getInvertedColor('0011zz');
Miscellaneous::getInvertedColor('001#zz');
Miscellaneous::getInvertedColor('001!zz');

View File

@@ -0,0 +1,341 @@
<?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\Test\Utilities;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\Expr;
use Doctrine\ORM\Query\Parameter;
use Doctrine\ORM\QueryBuilder;
use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\QueryBuilderUtility;
/**
* Test case of the useful methods for query builder (the Doctrine's QueryBuilder class)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
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->getMock(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->getMock(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->getMock(EntityManager::class, $methods, [], '', false);
$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->getMock(EntityManager::class, $methods, [], '', false);
$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->getMock(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->getMock(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
*
* @return Generator
*/
public function provideQueryBuilderAndCriteria()
{
$entityManager = $this->getMock(EntityManager::class, ['getExpressionBuilder'], [], '', false);
$entityManager
->expects(static::any())
->method('getExpressionBuilder')
->willReturn(new Expr());
yield[
(new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'),
[
'lorem' => 11,
'ipsum' => 22,
'dolor' => null,
],
];
yield[
(new QueryBuilder($entityManager))->from('lorem_ipsum', 'lm'),
[
'lorem' => [
11,
'>=',
],
'ipsum' => [
22,
'<',
],
'dolor' => null,
],
];
}
/**
* Provides query builder and parameters to add to given query builder
*
* @return Generator
*/
public function provideQueryBuilderAndParameters()
{
$entityManager = $this->getMock(EntityManagerInterface::class);
yield[
new QueryBuilder($entityManager),
[],
];
yield[
new QueryBuilder($entityManager),
new ArrayCollection(),
];
yield[
new QueryBuilder($entityManager),
[
'lorem' => 11,
'ipsum' => 22,
],
];
yield[
new QueryBuilder($entityManager),
new ArrayCollection([
'lorem' => 11,
'ipsum' => 22,
]),
];
yield[
new QueryBuilder($entityManager),
[
new Parameter('lorem', 11),
new Parameter('ipsum', 22),
],
];
yield[
new QueryBuilder($entityManager),
new ArrayCollection([
new Parameter('lorem', 11),
new Parameter('ipsum', 22),
]),
];
}
}

View File

@@ -19,8 +19,15 @@ class A
{
use E;
private $count = 1;
protected function lorem()
{
return 'ipsum';
}
protected function getCount()
{
return $this->count;
}
}

View File

@@ -0,0 +1,26 @@
<?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\Test\Utilities\Reflection;
/**
* The B class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class B extends A implements I
{
protected $name = 'Lorem Ipsum';
public function getName()
{
return $this->name;
}
}

View File

@@ -0,0 +1,54 @@
<?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\Test\Utilities\Reflection;
/**
* The F class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class F
{
protected $username;
private $accountBalance;
private $city;
private $country;
private $gInstance;
public function __construct($accountBalance, $city, $country, $username, $firstName = 'John', $lastName = 'Scott')
{
$this->accountBalance = $accountBalance;
$this->city = $city;
$this->country = $country;
$this->username = $username;
$this->gInstance = new G($firstName, $lastName);
/*
* Called to avoid "Unused private method getAccountBalance" warning only
*/
$this->getAccountBalance();
}
public function getCountry()
{
return $this->country;
}
protected function getCity()
{
return $this->city;
}
private function getAccountBalance()
{
return $this->accountBalance;
}
}

View File

@@ -0,0 +1,38 @@
<?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\Test\Utilities\Reflection;
/**
* The G class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class G
{
private $firstName;
private $lastName;
public function __construct($firstName = 'John', $lastName = 'Scott')
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
}

View File

@@ -0,0 +1,27 @@
<?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\Test\Utilities\Reflection;
/**
* The H class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class H
{
const DOLOR = 'sit';
const LOREM = 'ipsum';
const MAX_USERS = 5;
const MIN_USERS = 2;
}

View File

@@ -9,12 +9,12 @@
namespace Meritoo\Common\Test\Utilities\Reflection;
/**
* The B class.
* The H interface.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class B extends A
interface I
{
}

View File

@@ -0,0 +1,504 @@
<?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\Test\Utilities;
use DateTime;
use Generator;
use Meritoo\Common\Collection\Collection;
use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Test\Utilities\Reflection\A;
use Meritoo\Common\Test\Utilities\Reflection\B;
use Meritoo\Common\Test\Utilities\Reflection\C;
use Meritoo\Common\Test\Utilities\Reflection\D;
use Meritoo\Common\Test\Utilities\Reflection\E;
use Meritoo\Common\Test\Utilities\Reflection\F;
use Meritoo\Common\Test\Utilities\Reflection\G;
use Meritoo\Common\Test\Utilities\Reflection\H;
use Meritoo\Common\Test\Utilities\Reflection\I;
use Meritoo\Common\Utilities\Reflection;
use ReflectionProperty;
/**
* Test case of the useful reflection methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ReflectionTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(Reflection::class);
}
/**
* @param mixed $invalidClass Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetClassNameInvalidClass($invalidClass)
{
self::assertNull(Reflection::getClassName($invalidClass));
self::assertNull(Reflection::getClassName(123));
}
public function testGetClassNameNotExistingClass()
{
/*
* Not existing class
*/
self::assertEquals('', Reflection::getClassName('xyz'));
self::assertEquals('', Reflection::getClassName('xyz', true));
}
public function testGetClassNameExistingClass()
{
/*
* Existing class
*/
self::assertEquals(self::class, Reflection::getClassName(self::class));
self::assertEquals('ReflectionTest', Reflection::getClassName(self::class, true));
self::assertEquals(DateTime::class, Reflection::getClassName(new DateTime()));
self::assertEquals(DateTime::class, Reflection::getClassName(new DateTime(), true));
self::assertEquals(DateTime::class, Reflection::getClassName([
new DateTime(),
new DateTime('yesterday'),
]));
}
public function testGetClassNameDuplicatedName()
{
/*
* Class with namespace containing name of class (duplicated string)
*/
if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) {
self::assertEquals('Symfony\Bundle\SecurityBundle\SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle'));
self::assertEquals('SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle', true));
}
}
public function testGetClassNamespaceNotExistingClass()
{
/*
* Not existing class
*/
self::assertEquals('', Reflection::getClassNamespace('xyz'));
}
public function testGetClassNamespaceExistingClass()
{
/*
* Existing class
*/
self::assertEquals('Meritoo\Common\Test\Utilities', Reflection::getClassNamespace(self::class));
self::assertEquals(DateTime::class, Reflection::getClassNamespace(new DateTime()));
self::assertEquals(DateTime::class, Reflection::getClassNamespace([
new DateTime(),
new DateTime('yesterday'),
]));
}
public function testGetClassNamespaceDuplicatedName()
{
/*
* Class with namespace containing name of class (duplicated string)
*/
if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) {
self::assertEquals('Symfony\Bundle\SecurityBundle', Reflection::getClassNamespace('Symfony\Bundle\SecurityBundle\SecurityBundle'));
}
}
/**
* @param mixed $invalidClass Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetChildClassesInvalidClass($invalidClass)
{
$this->setExpectedException(CannotResolveClassNameException::class);
self::assertNull(Reflection::getChildClasses($invalidClass));
self::assertNull(Reflection::getChildClasses(123));
}
public function testGetChildClassesNotExistingClass()
{
$this->setExpectedException(CannotResolveClassNameException::class);
self::assertEquals('', Reflection::getChildClasses('xyz'));
}
public function testGetChildClassesExistingClass()
{
/*
* Attention. I have to create instances of these classes to load them and be available while using
* get_declared_classes() function in the Reflection::getChildClasses() method. Without these instances the
* Reflection::getChildClasses() method returns an empty array even if given class has child classes.
*/
new A();
new B();
new C();
$effect = [
C::class,
];
self::assertEquals($effect, Reflection::getChildClasses(B::class));
$effect = [
B::class,
C::class,
];
self::assertEquals($effect, Reflection::getChildClasses(A::class));
}
public function testGetOneChildClassWithMissingChildClasses()
{
$this->setExpectedException(MissingChildClassesException::class);
self::assertEquals('LoremIpsum', Reflection::getOneChildClass(C::class));
}
public function testGetOneChildClassWithTooManyChildClasses()
{
$this->setExpectedException(TooManyChildClassesException::class);
self::assertEquals(B::class, Reflection::getOneChildClass(A::class));
self::assertEquals(C::class, Reflection::getOneChildClass(A::class));
}
public function testGetOneChildClass()
{
self::assertEquals(C::class, Reflection::getOneChildClass(B::class));
}
public function testGetMethods()
{
self::assertEquals(1, count(Reflection::getMethods(B::class, true)));
self::assertEquals(3, count(Reflection::getMethods(B::class)));
self::assertEquals(2, count(Reflection::getMethods(A::class)));
self::assertEquals(2, count(Reflection::getMethods(C::class, true)));
self::assertEquals(5, count(Reflection::getMethods(C::class)));
}
/**
* @param array|object|string $class An array of objects, namespaces, object or namespace
* @param array|string $trait An array of strings or string
*
* @dataProvider provideInvalidClassAndTrait
*/
public function testUsesTraitInvalidClass($class, $trait)
{
$this->setExpectedException(CannotResolveClassNameException::class);
self::assertNull(Reflection::usesTrait($class, $trait));
}
/**
* @param mixed $trait Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testUsesTraitInvalidTrait($trait)
{
$this->setExpectedException(CannotResolveClassNameException::class);
self::assertNull(Reflection::usesTrait(DateTime::class, $trait));
}
public function testUsesTraitExistingClass()
{
self::assertTrue(Reflection::usesTrait(A::class, E::class));
self::assertFalse(Reflection::usesTrait(B::class, E::class));
self::assertFalse(Reflection::usesTrait(C::class, E::class));
self::assertFalse(Reflection::usesTrait(D::class, E::class));
}
public function testUsesTraitExistingClassAndVerifyParents()
{
self::assertTrue(Reflection::usesTrait(A::class, E::class, true));
self::assertTrue(Reflection::usesTrait(B::class, E::class, true));
self::assertTrue(Reflection::usesTrait(C::class, E::class, true));
self::assertFalse(Reflection::usesTrait(D::class, E::class, true));
}
public function testGetProperties()
{
self::assertCount(1, Reflection::getProperties(B::class));
}
public function testGetPropertiesUsingFilter()
{
self::assertCount(1, Reflection::getProperties(B::class, ReflectionProperty::IS_PROTECTED));
self::assertCount(0, Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE));
self::assertCount(1, Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE, true));
}
public function testGetPropertiesWithParents()
{
self::assertCount(2, Reflection::getProperties(B::class, null, true));
}
public function testGetPropertyValueOfNotExistingProperty()
{
self::assertNull(Reflection::getPropertyValue(new D(), 'something'));
self::assertNull(Reflection::getPropertyValue(new D(), 'something', true));
}
public function testGetPropertyValueFromChain()
{
$f = new F(1000, 'New York', 'USA', 'john.scott');
self::assertEquals('John', Reflection::getPropertyValue($f, 'gInstance.firstName'));
}
public function testGetPropertyValueWithPublicGetter()
{
$country = 'USA';
$f = new F(1000, 'New York', $country, 'john.scott');
self::assertEquals($country, Reflection::getPropertyValue($f, 'country'));
}
public function testGetPropertyValueWithProtectedGetter()
{
$city = 'New York';
$f = new F(1000, $city, 'USA', 'john.scott');
self::assertEquals($city, Reflection::getPropertyValue($f, 'city'));
}
public function testGetPropertyValueWithPrivateGetter()
{
$accountBalance = 1000;
$f = new F($accountBalance, 'New York', 'USA', 'john.scott');
self::assertEquals($accountBalance, Reflection::getPropertyValue($f, 'accountBalance'));
}
public function testGetPropertyValueWithoutGetter()
{
$username = 'john.scott';
$f = new F(1000, 'New York', 'USA', $username);
self::assertEquals($username, Reflection::getPropertyValue($f, 'username'));
}
public function testGetPropertyValuesFromEmptySource()
{
self::assertEquals([], Reflection::getPropertyValues([], 'something'));
self::assertEquals([], Reflection::getPropertyValues(new Collection(), 'something'));
}
public function testGetPropertyValuesOfNotExistingPropertyFromSingleObject()
{
self::assertEquals([], Reflection::getPropertyValues(new D(), 'something'));
self::assertEquals([], Reflection::getPropertyValues(new D(), 'something', true));
}
public function testGetPropertyValuesOfNotExistingPropertyFromMultipleObjects()
{
$objects = [
new A(),
new A(),
new A(),
new B(),
new B(),
new C(),
new D(),
];
self::assertEquals([], Reflection::getPropertyValues($objects, 'something'));
self::assertEquals([], Reflection::getPropertyValues($objects, 'something', true));
$collection = new Collection($objects);
self::assertEquals([], Reflection::getPropertyValues($collection, 'something'));
self::assertEquals([], Reflection::getPropertyValues($collection, 'something', true));
}
public function testGetPropertyValuesOfExistingPropertyFromSingleObject()
{
self::assertEquals(['John'], Reflection::getPropertyValues(new G(), 'firstName'));
self::assertEquals(['John'], Reflection::getPropertyValues(new G(), 'firstName', true));
}
public function testGetPropertyValuesOfExistingPropertyFromMultipleObjects()
{
$expected = [
'New York',
'London',
'Tokyo',
];
$objects = [
new F(1000, 'New York', 'USA', 'john.scott'),
new F(2000, 'London', 'GB', 'john.scott'),
new F(3000, 'Tokyo', 'Japan', 'john.scott'),
];
self::assertEquals($expected, Reflection::getPropertyValues($objects, 'city'));
self::assertEquals($expected, Reflection::getPropertyValues($objects, 'city', true));
$collection = new Collection($objects);
self::assertEquals($expected, Reflection::getPropertyValues($collection, 'city'));
self::assertEquals($expected, Reflection::getPropertyValues($collection, 'city', true));
}
public function testGetPropertyValuesFromChainAndSingleObject()
{
$f = new F(1000, 'New York', 'USA', 'john.scott');
self::assertEquals(['John'], Reflection::getPropertyValues($f, 'gInstance.firstName'));
self::assertEquals(['John'], Reflection::getPropertyValues($f, 'gInstance.firstName', true));
}
public function testGetPropertyValuesFromChainAndMultipleObjects()
{
$expected = [
'John',
'Mary',
'Peter',
];
$objects = [
new F(1000, 'New York', 'USA', 'john.scott'),
new F(2000, 'London', 'GB', 'john.scott', 'Mary', 'Jane'),
new F(3000, 'Tokyo', 'Japan', 'john.scott', 'Peter', 'Brown'),
];
self::assertEquals($expected, Reflection::getPropertyValues($objects, 'gInstance.firstName'));
self::assertEquals($expected, Reflection::getPropertyValues($objects, 'gInstance.firstName', true));
$collection = new Collection($objects);
self::assertEquals($expected, Reflection::getPropertyValues($collection, 'gInstance.firstName'));
self::assertEquals($expected, Reflection::getPropertyValues($collection, 'gInstance.firstName', true));
}
public function testGetMaxNumberConstantUsingClassWithoutConstants()
{
static::assertNull(Reflection::getMaxNumberConstant(A::class));
}
public function testGetMaxNumberConstant()
{
static::assertEquals(5, Reflection::getMaxNumberConstant(H::class));
}
public function testHasMethodUsingClassWithoutMethod()
{
static::assertFalse(Reflection::hasMethod(A::class, 'getUser'));
}
public function testHasMethod()
{
static::assertTrue(Reflection::hasMethod(A::class, 'getCount'));
}
public function testHasPropertyUsingClassWithoutProperty()
{
static::assertFalse(Reflection::hasProperty(A::class, 'users'));
}
public function testHasProperty()
{
static::assertTrue(Reflection::hasProperty(A::class, 'count'));
}
public function testHasConstantUsingClassWithoutConstant()
{
static::assertFalse(Reflection::hasConstant(H::class, 'users'));
}
public function testHasConstant()
{
static::assertTrue(Reflection::hasConstant(H::class, 'LOREM'));
}
public function testGetConstantValueUsingClassWithoutConstant()
{
static::assertNull(Reflection::getConstantValue(H::class, 'users'));
}
public function testGetConstantValue()
{
static::assertEquals(H::LOREM, Reflection::getConstantValue(H::class, 'LOREM'));
}
public function testIsInterfaceImplementedUsingClassWithoutInterface()
{
static::assertFalse(Reflection::isInterfaceImplemented(A::class, I::class));
}
public function testIsInterfaceImplemented()
{
static::assertTrue(Reflection::isInterfaceImplemented(B::class, I::class));
}
public function testIsChildOfClassUsingClassWithoutChildClass()
{
static::assertFalse(Reflection::isChildOfClass(A::class, B::class));
}
public function testIsChildOfClass()
{
static::assertTrue(Reflection::isChildOfClass(B::class, A::class));
}
public function testGetPropertyUsingClassWithoutProperty()
{
static::assertNull(Reflection::getProperty(A::class, 'lorem'));
}
public function testGetPropertyUsingClassWithPrivateProperty()
{
$property = Reflection::getProperty(A::class, 'count', ReflectionProperty::IS_PRIVATE);
static::assertInstanceOf(ReflectionProperty::class, $property);
static::assertTrue($property->isPrivate());
static::assertEquals('count', $property->getName());
}
public function testGetPropertyUsingClassWithProtectedProperty()
{
$property = Reflection::getProperty(B::class, 'name', ReflectionProperty::IS_PROTECTED);
static::assertInstanceOf(ReflectionProperty::class, $property);
static::assertTrue($property->isProtected());
static::assertEquals('name', $property->getName());
}
/**
* Provides invalid class and trait
*
* @return Generator
*/
public function provideInvalidClassAndTrait()
{
yield[
'',
'',
];
yield[
null,
null,
];
yield[
0,
0,
];
yield[
[],
[],
];
}
}

View File

@@ -8,19 +8,24 @@
namespace Meritoo\Common\Utilities;
use PHPUnit\Framework\TestCase;
use Meritoo\Common\Test\Base\BaseTestCase;
/**
* Tests of the useful regular expressions methods
* Test case of the useful regular expressions methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class RegexTest extends TestCase
class RegexTest extends BaseTestCase
{
private $simpleText;
private $camelCaseText;
public function testConstructor()
{
static::assertHasNoConstructor(Regex::class);
}
public function testGetCamelCaseParts()
{
$parts = [];

View File

@@ -12,13 +12,18 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Uri;
/**
* Tests of the useful uri methods (only static functions)
* Test case of the useful uri methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UriTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(Uri::class);
}
public function testAddProtocolToUrl()
{
$http = 'http';

View File

@@ -8,21 +8,26 @@
namespace Meritoo\Common\Test\Utilities;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Xml;
use PHPUnit\Framework\TestCase;
use SimpleXMLElement;
/**
* Tests of the useful XML-related methods (only static functions)
* Test case of the useful XML-related methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class XmlTest extends TestCase
class XmlTest extends BaseTestCase
{
private $simpleXml;
private $advancedXml;
public function testConstructor()
{
static::assertHasNoConstructor(Xml::class);
}
public function testMergeNodes()
{
/*