First, initial commit

This commit is contained in:
Meritoo
2017-08-29 22:37:19 +02:00
commit d9ab2a082e
67 changed files with 18377 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
<?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\Tests\Exception\Base;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Type\Base\BaseType;
/**
* Tests of the exception used while type of something is unknown
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownTypeExceptionTest extends \PHPUnit_Framework_TestCase
{
public function testWithoutException()
{
self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2'));
}
public function testTheException()
{
$this->expectException(UnknownTestTypeException::class);
self::assertEmpty((new TestService())->getTranslatedType('test_3'));
}
}
/**
* Type of something (for testing purposes)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class TestType extends BaseType
{
const TEST_1 = 'test_1';
const TEST_2 = 'test_2';
}
/**
* An exception used while type of something is unknown (for testing purposes)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownTestTypeException extends UnknownTypeException
{
/**
* Class constructor
*
* @param int|string $unknownType The unknown type of something (for testing purposes)
*/
public function __construct($unknownType)
{
parent::__construct($unknownType, new TestType(), 'type of something used for testing');
}
}
/**
* Service used together with type of something (for testing purposes)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class TestService
{
/**
* Returns translated type (for testing purposes)
*
* @param string $type Type of something (for testing purposes)
* @return string
*
* @throws UnknownTestTypeException
*/
public function getTranslatedType($type)
{
if ((new TestType())->isCorrectType($type)) {
return ucfirst(str_replace('_', ' ', $type));
}
throw new UnknownTestTypeException($type);
}
}

View File

@@ -0,0 +1,199 @@
<?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\Tests\Type\Base;
use Generator;
use Meritoo\Common\Type\Base\BaseType;
/**
* Tests of the base / abstract type of something
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class BaseTypeTest extends \PHPUnit_Framework_TestCase
{
/**
* @param BaseType $type Type of something
* @param array $expectedTypes Expected concrete types of given instance of type
*
* @dataProvider provideType
*/
public function testGetAll(BaseType $type, array $expectedTypes)
{
$all = $type->getAll();
self::assertEquals($expectedTypes, $all);
}
/**
* @param BaseType $type Type of something
* @param string $toVerifyType Concrete type to verify (of given instance of type)
* @param bool $isCorrect Expected information if given type is correct
*
* @dataProvider provideTypeWithConcreteType
*/
public function testIsCorrectType(BaseType $type, $toVerifyType, $isCorrect)
{
self::assertEquals($isCorrect, $type->isCorrectType($toVerifyType));
}
/**
* Provides type of something for testing the getAll() method
*
* @return Generator
*/
public function provideType()
{
yield[
new TestEmptyType(),
[],
];
yield[
new TestType(),
[
'TEST_1' => TestType::TEST_1,
'TEST_2' => TestType::TEST_2,
],
];
}
/**
* Provides type of something for testing the isCorrectType() method
*
* @return Generator
*/
public function provideTypeWithConcreteType()
{
yield[
new TestEmptyType(),
null,
false,
];
yield[
new TestEmptyType(),
false,
false,
];
yield[
new TestEmptyType(),
true,
false,
];
yield[
new TestEmptyType(),
'',
false,
];
yield[
new TestEmptyType(),
0,
false,
];
yield[
new TestEmptyType(),
1,
false,
];
yield[
new TestEmptyType(),
'lorem',
false,
];
yield[
new TestType(),
null,
false,
];
yield[
new TestType(),
false,
false,
];
yield[
new TestType(),
true,
false,
];
yield[
new TestType(),
'',
false,
];
yield[
new TestType(),
0,
false,
];
yield[
new TestType(),
1,
false,
];
yield[
new TestType(),
'lorem',
false,
];
yield[
new TestType(),
'test',
false,
];
yield[
new TestType(),
TestType::TEST_1,
true,
];
yield[
new TestType(),
TestType::TEST_2,
true,
];
}
}
/**
* Empty type of something used for testing
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class TestEmptyType extends BaseType
{
}
/**
* Type of something used for testing
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class TestType extends BaseType
{
const TEST_1 = 'test_1';
const TEST_2 = 'test_2';
}

View File

@@ -0,0 +1,106 @@
<?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\Tests\Type;
use Generator;
use Meritoo\Common\Type\DatePartType;
/**
* Tests of the type of date part, e.g. "year"
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DatePartTypeTest extends \PHPUnit_Framework_TestCase
{
public function testGetAll()
{
$expectedTypes = [
'DAY' => DatePartType::DAY,
'HOUR' => DatePartType::HOUR,
'MINUTE' => DatePartType::MINUTE,
'MONTH' => DatePartType::MONTH,
'SECOND' => DatePartType::SECOND,
'YEAR' => DatePartType::YEAR,
];
$all = (new DatePartType())->getAll();
self::assertEquals($expectedTypes, $all);
}
/**
* @param string $toVerifyType Concrete type to verify (of given instance of type)
* @param bool $isCorrect Expected information if given type is correct
*
* @dataProvider provideConcreteType
*/
public function testIsCorrectType($toVerifyType, $isCorrect)
{
$type = new DatePartType();
self::assertEquals($isCorrect, $type->isCorrectType($toVerifyType));
}
/**
* Provides type of something for testing the isCorrectType() method
*
* @return Generator
*/
public function provideConcreteType()
{
yield[
'',
false,
];
yield[
null,
false,
];
yield[
0,
false,
];
yield[
1,
false,
];
yield[
'day',
true,
];
yield[
'hour',
true,
];
yield[
'minute',
true,
];
yield[
'month',
true,
];
yield[
'second',
true,
];
yield[
'year',
true,
];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
<?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\Tests\Utilities;
use Meritoo\Common\Utilities\Bundle;
/**
* Tests of the useful methods for bundle
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class BundleTest extends \PHPUnit_Framework_TestCase
{
public function testGetBundleViewPathEmptyPathAndBundle()
{
self::assertNull(Bundle::getBundleViewPath('', ''));
self::assertNull(Bundle::getBundleViewPath('test', ''));
self::assertNull(Bundle::getBundleViewPath('', 'test'));
}
public function testGetBundleViewPathWithDefaultExtension()
{
self::assertEquals('Lorem:Ipsum.html.twig', Bundle::getBundleViewPath('Ipsum', 'Lorem'));
self::assertEquals('LobortisTincidunt:FusceElementum.html.twig', Bundle::getBundleViewPath('FusceElementum', 'LobortisTincidunt'));
}
public function testGetBundleViewPathWithCustomExtension()
{
self::assertNull(Bundle::getBundleViewPath('Ipsum', 'Lorem', ''));
self::assertEquals('Lorem:Ipsum.js.twig', Bundle::getBundleViewPath('Ipsum', 'Lorem', 'js.twig'));
}
}

View File

@@ -0,0 +1,87 @@
<?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\Tests\Utilities;
use Meritoo\Common\Utilities\Composer;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of the useful Composer-related methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ComposerTest extends TestCase
{
/**
* Path of existing composer.json used as source of data for tests
*
* @var string
*/
private $composerJsonPath;
/**
* @param string $composerJsonPath Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetValueNotExistingComposerJson($composerJsonPath)
{
self::assertNull(Composer::getValue($composerJsonPath, ''));
self::assertNull(Composer::getValue('not/existing/composer.json', ''));
}
/**
* @param string $nodeName Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetValueNotExistingNode($nodeName)
{
self::assertNull(Composer::getValue($this->composerJsonPath, $nodeName));
self::assertNull(Composer::getValue($this->composerJsonPath, 'not_existing_node'));
}
/**
* @param string $nodeName Name of existing node
* @param string $nodeValue Value of existing node
*
* @dataProvider getExistingNode
*/
public function testGetValueExistingNode($nodeName, $nodeValue)
{
self::assertEquals($nodeValue, Composer::getValue($this->composerJsonPath, $nodeName));
}
/**
* Provides names and values of existing nodes
*
* @return \Generator
*/
public function getExistingNode()
{
yield[
'name',
'test/test',
];
yield[
'version',
'1.0.2',
];
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->composerJsonPath = $this->getFilePathToTests(Composer::FILE_NAME_MAIN);
}
}

View File

@@ -0,0 +1,261 @@
<?php
namespace Meritoo\Common\Tests\Utilities;
use DateTime;
use Generator;
use Meritoo\Common\Utilities\DatePeriod;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of date's period
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DatePeriodTest extends TestCase
{
/**
* @param DateTime $startDate (optional) Start date of period
* @param DateTime $endDate (optional) End date of period
*
* @dataProvider provideDatePeriod
*/
public function testConstruct(DateTime $startDate = null, DateTime $endDate = null)
{
$period = new DatePeriod($startDate, $endDate);
self::assertEquals($startDate, $period->getStartDate());
self::assertEquals($endDate, $period->getEndDate());
}
/**
* @param DateTime $startDate (optional) Start date of period
* @param DateTime $endDate (optional) End date of period
*
* @dataProvider provideDatePeriod
*/
public function testGettersAndSetters(DateTime $startDate = null, DateTime $endDate = null)
{
$period = new DatePeriod();
$period->setStartDate($startDate);
self::assertEquals($startDate, $period->getStartDate());
$period->setEndDate($endDate);
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
*
* @dataProvider provideDatePeriodAndIncorrectDateFormat
*/
public function testGetFormattedDateIncorrectDateFormat(DatePeriod $period, $format)
{
self::assertEquals('', $period->getFormattedDate($format));
}
/**
* @param DatePeriod $period The date period to verify
* @param string $format Format used to format the date
* @param bool $startDate If is set to true, start date is formatted. Otherwise - end date.
* @param string $expected Expected, formatted date
*
* @dataProvider provideDatePeriodAndDateFormat
*/
public function testGetFormattedDate(DatePeriod $period, $format, $startDate, $expected)
{
self::assertEquals($expected, $period->getFormattedDate($format, $startDate));
}
/**
* Provides the start and end date of date period
*
* @return Generator
*/
public function provideDatePeriod()
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield[
null,
null,
];
yield[
$startDate,
$startDate,
null,
];
yield[
null,
null,
$endDate,
];
yield[
$startDate,
$endDate,
];
}
/**
* Provides 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
*
* @return Generator
*/
public function provideDatePeriodAndIncorrectDateFormat()
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
yield[
new DatePeriod($startDate, $endDate),
'',
];
yield[
new DatePeriod($startDate, $endDate),
null,
];
yield[
new DatePeriod($startDate, $endDate),
false,
];
}
/**
* Provides period and format of date to verify
*
* @return Generator
*/
public function provideDatePeriodAndDateFormat()
{
$startDate = new DateTime('2001-01-01');
$endDate = new DateTime('2002-02-02');
/*
* For start date
*/
yield[
new DatePeriod($startDate, $endDate),
'Y',
true,
'2001',
];
yield[
new DatePeriod($startDate, $endDate),
'D',
true,
'Mon',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d',
true,
'2001-01-01',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
true,
'2001-01-01 00:00',
];
/*
* For end date
*/
yield[
new DatePeriod($startDate, $endDate),
'Y',
false,
'2002',
];
yield[
new DatePeriod($startDate, $endDate),
'D',
false,
'Sat',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d',
false,
'2002-02-02',
];
yield[
new DatePeriod($startDate, $endDate),
'Y-m-d H:i',
false,
'2002-02-02 00:00',
];
}
}

View File

@@ -0,0 +1,748 @@
<?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\Tests\Utilities;
use DateInterval;
use DateTime;
use Generator;
use Meritoo\Common\Exception\Date\IncorrectDatePartException;
use Meritoo\Common\Utilities\Date;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of the Date methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class DateTest extends TestCase
{
/**
* @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetDateTimeEmptyValue($value)
{
self::assertFalse(Date::getDateTime($value));
}
/**
* @param mixed $value Incorrect source of DateTime
* @dataProvider provideIncorrectDateTimeValue
*/
public function testGetDateTimeIncorrectValue($value)
{
self::assertFalse(Date::getDateTime($value));
}
/**
* @param bool $value The value which maybe is a date
* @dataProvider provideBooleanValue
*/
public function testGetDateTimeBoolean($value)
{
self::assertFalse(Date::getDateTime($value));
}
/**
* @param string $relativeFormat Relative / compound format of DateTime
* @dataProvider provideDateTimeRelativeFormat
*/
public function testGetDateTimeRelativeFormats($relativeFormat)
{
/*
* Values based on relative / compound formats, but... without explicitly declaring them as compound
* (2nd argument set to false by default)
*
* http://php.net/manual/en/datetime.formats.compound.php
*/
self::assertFalse(Date::getDateTime($relativeFormat));
/*
* Values based on relative / compound formats
* http://php.net/manual/en/datetime.formats.compound.php
*/
self::assertInstanceOf(DateTime::class, Date::getDateTime($relativeFormat, true));
}
/**
* @param DateTime $dateTime Instance of DateTime class
* @dataProvider provideDateTimeInstance
*/
public function testGetDateTimeInstanceDateTime(DateTime $dateTime)
{
self::assertInstanceOf(DateTime::class, Date::getDateTime($dateTime));
}
public function testGetDateTimeConcreteDates()
{
/*
* Using the standard date format provided by the tested method
*/
self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20'));
/*
* Using custom date format
*/
self::assertInstanceOf(DateTime::class, Date::getDateTime('2015-03-20 11:30', false, 'Y-m-d H:i'));
self::assertInstanceOf(DateTime::class, Date::getDateTime('20.03.2015', false, 'd.m.Y'));
}
/**
* @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsValidDateEmptyDates($value)
{
self::assertFalse(Date::isValidDate($value));
}
/**
* @param mixed $value Incorrect source of DateTime
* @dataProvider provideIncorrectDateTimeValue
*/
public function testIsValidDateIncorrectDates($value)
{
self::assertFalse(Date::isValidDate($value));
}
public function testIsValidDateValidDates()
{
self::assertTrue(Date::isValidDate('2017-01-01'));
self::assertTrue(Date::isValidDate('2017-01-01 10:30', true));
self::assertTrue(Date::isValidDate('2017-01-01 14:00', true));
self::assertTrue(Date::isValidDate(new DateTime()));
self::assertTrue(Date::isValidDate(new DateTime('now')));
self::assertTrue(Date::isValidDate(new DateTime('tomorrow')));
self::assertTrue(Date::isValidDate(new DateTime('m')));
}
/**
* @param mixed $value Empty source of date format
* @dataProvider provideEmptyValue
*/
public function testIsValidDateFormatEmptyFormats($value)
{
self::assertFalse(Date::isValidDateFormat($value));
}
/**
* @param mixed $format Invalid format of date
* @dataProvider provideInvalidDateFormats
*/
public function testIsValidDateFormatInvalidFormats($format)
{
self::assertFalse(Date::isValidDateFormat($format));
}
public function testIsValidDateFormatValidFormats()
{
self::assertTrue(Date::isValidDateFormat('Y'));
self::assertTrue(Date::isValidDateFormat('yy'));
self::assertTrue(Date::isValidDateFormat('M'));
self::assertTrue(Date::isValidDateFormat('i'));
self::assertTrue(Date::isValidDateFormat('l'));
self::assertTrue(Date::isValidDateFormat('l, d F'));
self::assertTrue(Date::isValidDateFormat('Y-m-d'));
self::assertTrue(Date::isValidDateFormat('H:i:s'));
self::assertTrue(Date::isValidDateFormat('Y/m/d H:i:s'));
}
/**
* @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGenerateRandomTimeEmptyFormat($value)
{
self::assertNull(Date::generateRandomTime($value));
}
public function testGenerateRandomTimeIncorrectFormat()
{
self::assertNull(Date::generateRandomTime(','));
self::assertNull(Date::generateRandomTime(';'));
self::assertNull(Date::generateRandomTime('|'));
self::assertNull(Date::generateRandomTime('?'));
}
public function testGenerateRandomTimeDefaultFormat()
{
self::assertRegExp('/\d{2}:\d{2}:\d{2}/', Date::generateRandomTime());
}
public function testGenerateRandomTimeCustomFormat()
{
self::assertRegExp('/^0[1-9]{1}|1[0-2]{1}$/', Date::generateRandomTime('h')); // 01 through 12
self::assertRegExp('/^[0-5]?[0-9]$/', Date::generateRandomTime('i')); // 00 through 59
self::assertRegExp('/^[0-5]?[0-9]$/', Date::generateRandomTime('s')); // 00 through 59
self::assertRegExp('/^\d{2}:\d{2}$/', Date::generateRandomTime('H:i'));
self::assertRegExp('/^[1-9]|1[0-2]:\d{2}$/', Date::generateRandomTime('g:i'));
}
public function testGetCurrentDayOfWeek()
{
self::assertRegExp('/^[0-6]{1}$/', (string)Date::getCurrentDayOfWeek());
}
public function testGetCurrentDayOfWeekName()
{
$days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
$pattern = sprintf('/^%s$/', implode('|', $days));
self::assertRegExp($pattern, Date::getCurrentDayOfWeekName());
}
/**
* @param int $year The year value
* @param int $month The month value
* @param int $day The day value
*
* @dataProvider provideIncorrectYearMonthDay
*/
public function testGetDayOfWeekIncorrectValues($year, $month, $day)
{
$this->expectException(IncorrectDatePartException::class);
self::assertEmpty(Date::getDayOfWeek($year, $month, $day));
}
/**
* @param int $year The year value
* @param int $month The month value
* @param int $day The day value
*
* @dataProvider provideYearMonthDay
*/
public function testGetDayOfWeek($year, $month, $day)
{
self::assertRegExp('/^[0-6]{1}$/', (string)Date::getDayOfWeek($year, $month, $day));
}
/**
* @param string|DateTime $dateStart The start date
* @param string|DateTime $dateEnd The end date
*
* @dataProvider provideEmptyDatesForDateDifference
*/
public function testGetDateDifferenceEmptyDates($dateStart, $dateEnd)
{
self::assertNull(Date::getDateDifference($dateStart, $dateEnd));
}
public function testGetDateDifferenceInvalidDates()
{
self::assertNull(Date::getDateDifference('2017-01-40', '2017-13-01'));
self::assertNull(Date::getDateDifference('xyz', 'lorem'));
}
public function testGetDateDifferenceOneDay()
{
/*
* Difference of 1 day
*/
$dateStart = '2017-01-01';
$dateEnd = '2017-01-02';
$effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 1,
Date::DATE_DIFFERENCE_UNIT_HOURS => 0,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 0,
];
self::assertEquals($effect, Date::getDateDifference($dateStart, $dateEnd));
self::assertEquals($effect, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd)));
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(0, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(1, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_DAYS));
self::assertEquals(1, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_DAYS));
/*
* Difference of 1 day (using the relative date format)
*/
$effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 1,
Date::DATE_DIFFERENCE_UNIT_HOURS => 0,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 0,
];
self::assertEquals($effect, Date::getDateDifference(new DateTime('yesterday'), new DateTime('midnight')));
self::assertEquals(1, Date::getDateDifference(new DateTime('yesterday'), new DateTime('midnight'), Date::DATE_DIFFERENCE_UNIT_DAYS));
self::assertEquals(0, Date::getDateDifference(new DateTime('yesterday'), new DateTime('midnight'), Date::DATE_DIFFERENCE_UNIT_HOURS));
}
public function testGetDateDifferenceOneDayTwoHours()
{
/*
* Difference of 1 day, 2 hours and 15 minutes
*/
$dateStart = '2017-01-01 12:00';
$dateEnd = '2017-01-02 14:15';
$effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 1,
Date::DATE_DIFFERENCE_UNIT_HOURS => 2,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 15,
];
self::assertEquals($effect, Date::getDateDifference($dateStart, $dateEnd));
self::assertEquals($effect, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd)));
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(0, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(2, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_HOURS));
self::assertEquals(2, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_HOURS));
self::assertEquals(15, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MINUTES));
self::assertEquals(15, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES));
}
public function testGetDateDifferenceOneMonthFortyOneDays()
{
/*
* Difference of 1 month, 41 days, 4 hours and 30 minutes
*/
$dateStart = '2017-01-01 12:00';
$dateEnd = '2017-02-11 16:30';
$effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 1,
Date::DATE_DIFFERENCE_UNIT_DAYS => 41,
Date::DATE_DIFFERENCE_UNIT_HOURS => 4,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 30,
];
self::assertEquals($effect, Date::getDateDifference($dateStart, $dateEnd));
self::assertEquals($effect, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd)));
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(0, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(1, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MONTHS));
self::assertEquals(1, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MONTHS));
self::assertEquals(41, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_DAYS));
self::assertEquals(41, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_DAYS));
self::assertEquals(30, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MINUTES));
self::assertEquals(30, Date::getDateDifference(new DateTime($dateStart), new DateTime($dateEnd), Date::DATE_DIFFERENCE_UNIT_MINUTES));
}
public function testGetDateDifferenceNoDifference()
{
/*
* No difference
*/
$dateStart = '2017-01-01 12:00';
$dateEnd = $dateStart;
$effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 0,
Date::DATE_DIFFERENCE_UNIT_HOURS => 0,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 0,
];
self::assertEquals($effect, Date::getDateDifference($dateStart, $dateEnd));
self::assertEquals($effect, Date::getDateDifference(new DateTime(), new DateTime()));
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(0, Date::getDateDifference(new DateTime(), new DateTime(), Date::DATE_DIFFERENCE_UNIT_YEARS));
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MONTHS));
self::assertEquals(0, Date::getDateDifference(new DateTime(), new DateTime(), Date::DATE_DIFFERENCE_UNIT_MONTHS));
self::assertEquals(0, Date::getDateDifference($dateStart, $dateEnd, Date::DATE_DIFFERENCE_UNIT_MINUTES));
self::assertEquals(0, Date::getDateDifference(new DateTime(), new DateTime(), Date::DATE_DIFFERENCE_UNIT_MINUTES));
}
/**
* @param mixed $invalidCount Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetDatesCollectionInvalidCount($invalidCount)
{
self::assertEquals([], Date::getDatesCollection(new DateTime(), $invalidCount));
self::assertEquals([], Date::getDatesCollection(new DateTime(), -1));
}
/**
* @param mixed $invalidInterval Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetDatesCollectionInvalidInterval($invalidInterval)
{
self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, $invalidInterval));
self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, 'lorem'));
self::assertEquals([], Date::getDatesCollection(new DateTime(), 2, '%d'));
}
public function testGetDatesCollection()
{
/*
* 1 date only
*/
$effect = [
1 => new DateTime('2017-01-02'),
];
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 1));
/*
* 3 dates with default date interval (days)
*/
$effect = [
1 => new DateTime('2017-01-02'),
2 => new DateTime('2017-01-03'),
3 => new DateTime('2017-01-04'),
];
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3));
/*
* 3 dates with custom date interval (hours)
*/
$effect = [
1 => new DateTime('2017-01-01 10:30'),
2 => new DateTime('2017-01-01 11:30'),
3 => new DateTime('2017-01-01 12:30'),
];
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01 09:30'), 3, 'PT%dH'));
/*
* 3 dates with custom date interval (months)
*/
$effect = [
1 => new DateTime('2017-02-01'),
2 => new DateTime('2017-03-01'),
3 => new DateTime('2017-04-01'),
];
self::assertEquals($effect, Date::getDatesCollection(new DateTime('2017-01-01'), 3, 'P%dM'));
}
public function testGetRandomDateUsingDefaults()
{
$startDate = new DateTime();
$start = 1;
$end = 100;
$intervalMinDate = (clone $startDate)->add(new DateInterval(sprintf('P%dD', $start)));
$intervalMaxDate = (clone $startDate)->add(new DateInterval(sprintf('P%dD', $end)));
$randomDate = Date::getRandomDate();
self::assertTrue($randomDate >= $intervalMinDate && $randomDate <= $intervalMaxDate);
}
/**
* @param DateTime $startDate The start date. Start of the random date.
* @param int $start Start of random partition
* @param int $end End of random partition
*
* @dataProvider provideDataOfRandomDateIncorrectEnd
*/
public function testGetRandomDateIncorrectEnd(DateTime $startDate, $start, $end)
{
$randomDate = Date::getRandomDate($startDate, $start, $end);
$intervalDate = (clone $startDate)->add(new DateInterval(sprintf('P%dD', $start)));
self::assertTrue($randomDate >= $intervalDate && $randomDate <= $intervalDate);
}
/**
* @param DateTime $startDate The start date. Start of the random date.
* @param int $start Start of random partition
* @param int $end End of random partition
*
* @dataProvider provideDataOfRandomDate
*/
public function testGetRandomDate(DateTime $startDate, $start, $end)
{
$randomDate = Date::getRandomDate($startDate, $start, $end);
$intervalMinDate = (clone $startDate)->add(new DateInterval(sprintf('P%dD', $start)));
$intervalMaxDate = (clone $startDate)->add(new DateInterval(sprintf('P%dD', $end)));
self::assertTrue($randomDate >= $intervalMinDate && $randomDate <= $intervalMaxDate);
}
/**
* Provides incorrect invalidCount of DateTime
*
* @return Generator
*/
public function provideIncorrectDateTimeValue()
{
/*
* Incorrect one-character values
*/
yield['a'];
yield['m'];
/*
* Incorrect strings
*/
yield['ss'];
yield['sss'];
yield['mm'];
yield['yy'];
yield['yyyy'];
/*
* Incorrect integer values
*/
yield[1];
yield[10];
yield[15];
yield[100];
yield[1000];
/*
* Incorrect string / numeric values
*/
yield['1'];
yield['10'];
yield['15'];
yield['100'];
yield['1000'];
/*
* Incorrect dates
*/
yield['0-0-0'];
yield['20-01-01'];
yield['2015-0-0'];
yield['2015-00-00'];
yield['2015-16-01'];
}
/**
* Provides invalid format of date
*
* @return Generator
*/
public function provideInvalidDateFormats()
{
yield[0];
yield[9];
yield['[]'];
yield['invalid'];
yield['Q'];
yield[','];
yield['.'];
yield['aa###'];
yield['Y/m/d H:i:invalid'];
}
/**
* Provide empty dates for date difference
*
* @return Generator
*/
public function provideEmptyDatesForDateDifference()
{
yield[
null,
null,
];
yield[
'',
'',
];
yield[
null,
new DateTime(),
];
yield[
new DateTime(),
null,
];
}
/**
* Provides incorrect values of year, month and day
*
* @return Generator
*/
public function provideIncorrectYearMonthDay()
{
yield[
null,
null,
null,
];
yield[
'',
'',
'',
];
yield[
0,
0,
0,
];
yield[
-1,
-1,
-1,
];
yield[
5000,
50,
50,
];
yield[
2000,
13,
01,
];
yield[
2000,
01,
40,
];
}
/**
* Provides values of year, month and day
*
* @return Generator
*/
public function provideYearMonthDay()
{
yield[
2000,
01,
01,
];
yield[
2000,
1,
1,
];
yield[
2000,
2,
2,
];
yield[
2000,
6,
1,
];
yield[
2000,
12,
01,
];
yield[
2000,
12,
1,
];
yield[
2000,
12,
31,
];
}
/**
* Provides data for the random date with incorrect end of random partition
*
* @return Generator
*/
public function provideDataOfRandomDateIncorrectEnd()
{
yield[
new DateTime('2000-01-01'),
100,
1,
];
}
/**
* Provides data for the random date
*
* @return Generator
*/
public function provideDataOfRandomDate()
{
yield[
new DateTime('2000-01-01'),
1,
100,
];
yield[
new DateTime('2000-12-01'),
1,
100,
];
yield[
new DateTime('2000-01-01'),
'1',
'100',
];
yield[
new DateTime('2000-12-01'),
'1',
'100',
];
yield[
new DateTime('2000-01-01'),
10,
50,
];
yield[
new DateTime('2000-12-01'),
10,
50,
];
}
}

View File

@@ -0,0 +1,56 @@
<?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\Tests\Utilities;
use Meritoo\Common\Utilities\GeneratorUtility;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of the useful methods for the Generator class
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class GeneratorUtilityTest extends TestCase
{
public function testGetGeneratorElements()
{
/*
* Generator that provides boolean value
*/
$elements = [
[false],
[true],
];
$generator = $this->provideBooleanValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
$elements = [
[''],
[' '],
[null],
[0],
[false],
[[]],
];
/*
* Generator that provides an empty value
*/
$generator = $this->provideEmptyValue();
self::assertEquals($elements, GeneratorUtility::getGeneratorElements($generator));
/*
* Generator that provides instance of DateTime class
*/
$generator = $this->provideDateTimeInstance();
self::assertCount(4, GeneratorUtility::getGeneratorElements($generator));
}
}

View File

@@ -0,0 +1,129 @@
<?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\Tests\Utilities;
use Generator;
use Meritoo\Common\Utilities\Locale;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of the useful locale methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class LocaleTest extends TestCase
{
/**
* @param mixed $languageCode Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetLongFormEmptyLanguageCode($languageCode)
{
self::assertEquals('', Locale::getLongForm($languageCode));
}
/**
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @param string $encoding Encoding of the final locale
* @param string $expected Expected long form of the locale
*
* @dataProvider provideLanguageAndCountryCode
*/
public function testGetLongForm($languageCode, $countryCode, $encoding, $expected)
{
self::assertEquals($expected, Locale::getLongForm($languageCode, $countryCode, $encoding));
}
/**
* @param mixed $emptyValue Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testSetLocaleEmptyCategoryAndLanguageCode($emptyValue)
{
self::assertFalse(Locale::setLocale($emptyValue, $emptyValue));
}
/**
* @param int $category Named constant specifying the category of the functions affected by the locale
* setting. It's the same constant as required by setlocale() function.
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
*
* @dataProvider provideCategoryAndLanguageCode
*/
public function testSetLocale($category, $languageCode)
{
self::assertTrue(Locale::setLocale($category, $languageCode));
}
/**
* Provides language and country code
*
* @return Generator
*/
public function provideLanguageAndCountryCode()
{
yield[
'fr',
'',
'',
'fr_FR',
];
yield[
'fr',
'',
'UTF-8',
'fr_FR.UTF-8',
];
yield[
'fr',
'FR',
'',
'fr_FR',
];
yield[
'fr',
'FR',
'UTF-8',
'fr_FR.UTF-8',
];
}
/**
* Provides category and language
*
* @return Generator
*/
public function provideCategoryAndLanguageCode()
{
yield[
LC_ALL,
'fr',
];
yield[
LC_COLLATE,
'fr',
];
yield[
LC_CTYPE,
'en',
];
yield[
LC_NUMERIC,
'en',
];
}
}

View File

@@ -0,0 +1,472 @@
<?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\Tests\Utilities;
use Generator;
use Meritoo\Common\Utilities\MimeTypes;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of the useful methods for mime types of files
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MimeTypesTest extends TestCase
{
/**
* @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetExtensionEmptyMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param bool $mimeType The mime type, e.g. "video/mpeg"
* @dataProvider provideBooleanValue
*/
public function testGetExtensionBooleanMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType Not existing mime type, e.g. "lorem/ipsum"
* @dataProvider provideNotExistingMimeType
*/
public function testGetExtensionNotExistingMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param string $extension Expected extension
*
* @dataProvider provideMimeTypeToGetSingleExtension
*/
public function testGetExtensionSingle($mimeType, $extension)
{
self::assertEquals($extension, MimeTypes::getExtension($mimeType));
}
/**
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @param array $extensions Expected extensions
*
* @dataProvider provideMimeTypeToGetMultipleExtension
*/
public function testGetExtensionMultiple($mimeType, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtension($mimeType));
}
/**
* @param array $mimesTypes Not existing mimes types, e.g. ['lorem/ipsum']
* @dataProvider provideNotExistingMimeTypes
*/
public function testGetExtensionsNotExistingMimeTypes($mimesTypes)
{
self::assertEquals([], MimeTypes::getExtensions($mimesTypes));
}
/**
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param array $extensions Expected extensions
*
* @dataProvider provideMimesTypesToGetExtensions
*/
public function testGetExtensions($mimesTypes, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtensions($mimesTypes));
}
/**
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param array $extensions Expected extensions
*
* @dataProvider provideMimesTypesToGetExtensionsUpperCase
*/
public function testGetExtensionsUpperCase($mimesTypes, $extensions)
{
self::assertEquals($extensions, MimeTypes::getExtensions($mimesTypes, true));
}
/**
* @param mixed $filePath Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetMimeTypeEmptyPath($filePath)
{
self::assertEquals('', MimeTypes::getMimeType($filePath));
}
/**
* @param string $filePath Path of the file to check
* @param string $mimeType Expected mime type
*
* @dataProvider provideFilePathToGetMimeTypeOfRealFile
*/
public function testGetMimeTypeOfRealFile($filePath, $mimeType)
{
self::assertEquals($mimeType, MimeTypes::getMimeType($filePath));
}
/**
* @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsImageEmptyMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param string $mimeType Not existing mime type, e.g. "lorem/ipsum"
* @dataProvider provideNotExistingMimeType
*/
public function testIsImageNotExistingMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param string $mimeType Mime type of non-image, e.g. "text/plain"
* @dataProvider provideNonImageMimeType
*/
public function testIsImageNonImageMimeType($mimeType)
{
self::assertFalse(MimeTypes::isImage($mimeType));
}
/**
* @param mixed $path Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testIsImagePathEmptyPath($path)
{
self::assertFalse(MimeTypes::isImagePath($path));
}
/**
* @param mixed $path Path of not existing file, e.g. "lorem/ipsum.jpg"
* @dataProvider provideNotExistingFilePath
*/
public function testIsImagePathNotExistingPath($path)
{
self::assertFalse(MimeTypes::isImagePath($path));
}
/**
* @param string $path Path of the file to check
* @param bool $isImage Expected information if the file is an image
*
* @dataProvider provideExistingFilePathToCheckIsImagePath
*/
public function testIsImagePathExistingPath($path, $isImage)
{
self::assertEquals($isImage, MimeTypes::isImagePath($path));
}
/**
* @param string $mimeType Mime type of image, e.g. "image/jpeg"
* @dataProvider provideImageMimeType
*/
public function testIsImageImageMimeType($mimeType)
{
self::assertTrue(MimeTypes::isImage($mimeType));
}
/**
* Provides not existing mime type
*
* @return Generator
*/
public function provideNotExistingMimeType()
{
yield['lorem/ipsum'];
yield['dolor'];
yield['x/y/z'];
}
/**
* Provides mime type of non-image
*
* @return Generator
*/
public function provideNonImageMimeType()
{
yield['application/rtf'];
yield['audio/mp4'];
yield['text/plain'];
yield['text/html'];
}
/**
* Provides mime type of image
*
* @return Generator
*/
public function provideImageMimeType()
{
yield['image/bmp'];
yield['image/jpeg'];
yield['image/png'];
yield['image/tiff'];
yield['image/vnd.microsoft.icon'];
yield['image/x-rgb'];
}
/**
* Provides existing mime type used to get single, one extension
*
* @return Generator
*/
public function provideMimeTypeToGetSingleExtension()
{
yield[
'application/x-7z-compressed',
'7z',
];
yield[
'application/json',
'json',
];
yield[
'application/zip',
'zip',
];
}
/**
* Provides existing mime type used to get multiple, more than one extension
*
* @return Generator
*/
public function provideMimeTypeToGetMultipleExtension()
{
yield[
'application/postscript',
[
'ai',
'eps',
'ps',
],
];
yield[
'audio/midi',
[
'mid',
'midi',
'kar',
'rmi',
],
];
yield[
'image/jpeg',
[
'jpeg',
'jpe',
'jpg',
],
];
yield[
'text/html',
[
'html',
'htm',
],
];
yield[
'text/plain',
[
'txt',
'text',
'conf',
'def',
'list',
'log',
'in',
],
];
yield[
'video/mp4',
[
'mp4',
'mp4v',
'mpg4',
'm4v',
],
];
}
/**
* Provides not existing mime types
*
* @return Generator
*/
public function provideNotExistingMimeTypes()
{
yield[
[],
];
yield[
[
'',
null,
false,
0,
],
];
yield[
[
'lorem/ipsum',
'dolor/sit',
],
];
}
/**
* Provides mime types used to get extensions
*
* @return Generator
*/
public function provideMimesTypesToGetExtensions()
{
yield[
[
'application/x-7z-compressed',
'application/json',
],
[
'application/x-7z-compressed' => '7z',
'application/json' => 'json',
],
];
yield[
[
'application/mathematica',
'application/xml',
'audio/mp4',
'video/mp4',
],
[
'application/mathematica' => [
'ma',
'nb',
'mb',
],
'application/xml' => [
'xml',
'xsl',
],
'audio/mp4' => 'mp4a',
'video/mp4' => [
'mp4',
'mp4v',
'mpg4',
'm4v',
],
],
];
}
/**
* Provides mime types used to get extensions as upper case
*
* @return Generator
*/
public function provideMimesTypesToGetExtensionsUpperCase()
{
yield[
[
'application/x-7z-compressed',
'application/json',
],
[
'application/x-7z-compressed' => '7Z',
'application/json' => 'JSON',
],
];
yield[
[
'application/xml',
'audio/mp4',
'text/html',
'video/mp4',
],
[
'application/xml' => [
'XML',
'XSL',
],
'audio/mp4' => 'MP4A',
'text/html' => [
'HTML',
'HTM',
],
'video/mp4' => [
'MP4',
'MP4V',
'MPG4',
'M4V',
],
],
];
}
/**
* Provides real file path to get mime type
*
* @return Generator
*/
public function provideFilePathToGetMimeTypeOfRealFile()
{
yield[
$this->getFilePathToTests('minion.jpg'),
'image/jpeg',
];
yield[
$this->getFilePathToTests('lorem-ipsum.txt'),
'text/plain',
];
}
/**
* Provides real file path to get information if the file is an image
*
* @return Generator
*/
public function provideExistingFilePathToCheckIsImagePath()
{
yield[
$this->getFilePathToTests('minion.jpg'),
true,
];
yield[
$this->getFilePathToTests('lorem-ipsum.txt'),
false,
];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,20 @@
<?php
namespace Meritoo\Common\Tests\Utilities\Reflection;
/**
* The A class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class A
{
use E;
protected function lorem()
{
return 'ipsum';
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Meritoo\Common\Tests\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
{
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Meritoo\Common\Tests\Utilities\Reflection;
/**
* The C class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class C extends B
{
public function getPositive()
{
return true;
}
public function getNegative()
{
return false;
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Meritoo\Common\Tests\Utilities\Reflection;
/**
* The D class.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class D
{
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Meritoo\Common\Tests\Utilities\Reflection;
/**
* The E trait.
* Used for testing the Reflection class.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
trait E
{
}

View File

@@ -0,0 +1,246 @@
<?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\Tests\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\Tests\Utilities\Reflection\A;
use Meritoo\Common\Tests\Utilities\Reflection\B;
use Meritoo\Common\Tests\Utilities\Reflection\C;
use Meritoo\Common\Tests\Utilities\Reflection\D;
use Meritoo\Common\Tests\Utilities\Reflection\E;
use Meritoo\Common\Utilities\Reflection;
use Meritoo\Common\Utilities\TestCase;
/**
* Tests of the useful reflection methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class ReflectionTest extends TestCase
{
/**
* @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\Tests\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,291 @@
<?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\Utilities;
/**
* Tests of the useful regular expressions methods
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class RegexTest extends \PHPUnit_Framework_TestCase
{
private $simpleText;
private $camelCaseText;
public function testGetCamelCaseParts()
{
$parts = [];
self::assertEquals($parts, Regex::getCamelCaseParts(''));
$parts = [
'lorem',
];
self::assertEquals($parts, Regex::getCamelCaseParts('lorem'));
$parts = [
'lorem',
'Ipsum',
'Dolor',
'Sit',
];
self::assertEquals($parts, Regex::getCamelCaseParts($this->camelCaseText));
$parts = [
'Lorem',
'Ipsum',
'Dolor',
'Sit',
];
$string = ucfirst($this->camelCaseText); // 'LoremIpsumDolorSit'
self::assertEquals($parts, Regex::getCamelCaseParts($string));
}
public function testCamelCase2humanReadable()
{
self::assertEquals('', Regex::camelCase2humanReadable(''));
self::assertEquals('lorem', Regex::camelCase2humanReadable('lorem'));
self::assertEquals($this->simpleText, Regex::camelCase2humanReadable($this->camelCaseText));
self::assertEquals(ucfirst($this->simpleText), Regex::camelCase2humanReadable($this->camelCaseText, true));
}
public function testCamelCase2simpleLowercase()
{
self::assertEquals('', Regex::camelCase2simpleLowercase(''));
self::assertEquals('lorem', Regex::camelCase2simpleLowercase('lorem'));
self::assertEquals('Lorem', Regex::camelCase2simpleLowercase('Lorem', '', false));
self::assertEquals('lorem-ipsum-dolor-sit', Regex::camelCase2simpleLowercase($this->camelCaseText, '-'));
self::assertEquals('lorem-Ipsum-Dolor-Sit', Regex::camelCase2simpleLowercase($this->camelCaseText, '-', false));
}
public function testIsValidUrl()
{
$validUrls = [
'http://php.net',
'http://php.net/',
'http://php.net/docs.php',
'http://php.net/get-involved.php',
'http://php.net/manual/en/function.preg-match.php',
'http://domain.com/BigLetters',
'http://domain.com/Another-Big-Letters',
'http://domain.com/?a=1&b=c2d',
'http://domAin.COM/?a=1&B=c2D',
'http://domain.com/index.php?a=1&b=c2d',
'http://domain.com/another-page-2.php?a=1&b=c2d',
'https://domain.com',
'https://domain.com/',
];
$invalidUrls = [
'',
null,
false,
true,
0,
1,
123,
'123',
'http:',
'http://',
'http://abc',
'ftp://def',
];
foreach ($validUrls as $url) {
self::assertTrue(Regex::isValidUrl($url));
}
foreach ($invalidUrls as $url) {
self::assertFalse(Regex::isValidUrl($url));
}
}
public function testIsSubPathOf()
{
self::assertFalse(Regex::isSubPathOf(null, null));
self::assertFalse(Regex::isSubPathOf('', ''));
self::assertFalse(Regex::isSubPathOf('', '/my/directory'));
self::assertFalse(Regex::isSubPathOf('/my/file', ''));
self::assertFalse(Regex::isSubPathOf('/my/file', '/my/directory'));
self::assertTrue(Regex::isSubPathOf('/my/directory', '/my/directory'));
self::assertTrue(Regex::isSubPathOf('/my/directory/', '/my/directory'));
self::assertTrue(Regex::isSubPathOf('/my/directory', '/my/directory/'));
self::assertTrue(Regex::isSubPathOf('/my/directory/', '/my/directory/'));
self::assertTrue(Regex::isSubPathOf('/my/another/directory/another/file', '/my/another/directory'));
}
public function testIsLetterOrDigit()
{
self::assertTrue(Regex::isLetterOrDigit('a'));
self::assertTrue(Regex::isLetterOrDigit(10));
self::assertFalse(Regex::isLetterOrDigit(';'));
}
public function testStartsWith()
{
$string = 'Lorem ipsum dolor sit amet';
$beginning = 'Lor';
self::assertTrue(Regex::startsWith($string, $beginning));
$beginning = 'L';
self::assertTrue(Regex::startsWith($string, $beginning));
$beginning = 'X';
self::assertFalse(Regex::startsWith($string, $beginning));
$string = '1234567890';
$beginning = '1';
self::assertTrue(Regex::startsWith($string, $beginning));
$beginning = ';';
self::assertFalse(Regex::startsWith($string, $beginning));
}
public function testStartsWithDirectorySeparator()
{
/*
* Slash as separator
*/
$separatorSlash = '/';
self::assertTrue(Regex::startsWithDirectorySeparator('/my/extra/directory', $separatorSlash));
self::assertFalse(Regex::startsWithDirectorySeparator('my/extra/directory', $separatorSlash));
/*
* Backslash as separator
*/
$separatorBackslash = '\\';
self::assertTrue(Regex::startsWithDirectorySeparator('\my\extra\directory', $separatorBackslash));
self::assertFalse(Regex::startsWithDirectorySeparator('my\extra\directory', $separatorBackslash));
}
public function testEndsWithDirectorySeparator()
{
/*
* Slash as separator
*/
$separatorSlash = '/';
self::assertTrue(Regex::endsWithDirectorySeparator('my simple text/', $separatorSlash));
self::assertFalse(Regex::endsWithDirectorySeparator('my simple text', $separatorSlash));
/*
* Backslash as separator
*/
$separatorBackslash = '\\';
self::assertTrue(Regex::endsWithDirectorySeparator('my simple text\\', $separatorBackslash));
self::assertFalse(Regex::endsWithDirectorySeparator('my simple text', $separatorBackslash));
}
public function testEndsWith()
{
self::assertFalse(Regex::endsWith($this->simpleText, '\.\.\.'));
self::assertFalse(Regex::endsWith($this->simpleText, '\.'));
self::assertTrue(Regex::endsWith($this->simpleText, 't'));
}
public function testIsSetUriParameter()
{
$uri = 'www.domain.com/?name=phil&type=4';
$parameterName = 'type';
self::assertTrue(Regex::isSetUriParameter($uri, $parameterName));
$parameterName = 'color';
self::assertFalse(Regex::isSetUriParameter($uri, $parameterName));
}
public function testContainsEntities()
{
self::assertFalse(Regex::containsEntities('Lorem ipsum'));
self::assertTrue(Regex::containsEntities('Lorem ipsum &raquo;'));
}
public function testContains()
{
self::assertTrue(Regex::contains($this->simpleText, 'ipsum'));
self::assertFalse(Regex::contains($this->simpleText, 'neque'));
}
public function testIsFileName()
{
$filePath = __FILE__;
$directoryPath = dirname($filePath);
self::assertTrue(Regex::isFileName($filePath));
self::assertFalse(Regex::isFileName($directoryPath));
}
public function testIsQuoted()
{
self::assertTrue(Regex::isQuoted('\'lorem ipsum\''));
self::assertTrue(Regex::isQuoted('"lorem ipsum"'));
self::assertFalse(Regex::isQuoted('lorem ipsum'));
self::assertFalse(Regex::isQuoted(new \stdClass()));
}
public function testIsWindowsBasedPath()
{
self::assertTrue(Regex::isWindowsBasedPath('C:\path\to\directory'));
self::assertTrue(Regex::isWindowsBasedPath('C:\path\to\file.jpg'));
self::assertFalse(Regex::isWindowsBasedPath('/path/to/directory'));
self::assertFalse(Regex::isWindowsBasedPath('/path/to/file.jpg'));
}
public function testIsValidNip()
{
self::assertFalse(Regex::isValidNip(null));
self::assertFalse(Regex::isValidNip(''));
self::assertFalse(Regex::isValidNip(1234));
self::assertFalse(Regex::isValidNip(1234567890));
self::assertFalse(Regex::isValidNip(0000000000));
self::assertFalse(Regex::isValidNip('1234567890'));
self::assertFalse(Regex::isValidNip('0000000000'));
self::assertFalse(Regex::isValidNip('abc'));
self::assertFalse(Regex::isValidNip($this->simpleText));
self::assertTrue(Regex::isValidNip('7340009469')); // Onet S.A.
self::assertTrue(Regex::isValidNip('5252530705')); // Facebook Poland sp. z o.o.
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->simpleText = 'lorem ipsum dolor sit';
$this->camelCaseText = str_replace(' ', '', lcfirst(ucwords($this->simpleText))); // 'loremIpsumDolorSit'
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
parent::tearDown();
unset($this->simpleText);
unset($this->camelCaseText);
}
}

View File

@@ -0,0 +1,78 @@
<?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\Tests\Utilities;
use Meritoo\Common\Utilities\TestCase;
use Meritoo\Common\Utilities\Uri;
/**
* Tests of the useful uri methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UriTest extends TestCase
{
public function testAddProtocolToUrl()
{
$http = 'http';
$https = 'https';
$url = 'my.domain/some/url';
$httpUrl = sprintf('%s://%s', $http, $url);
$httpsUrl = sprintf('%s://%s', $https, $url);
self::assertEquals($httpUrl, Uri::addProtocolToUrl($httpUrl));
self::assertEquals($httpUrl, Uri::addProtocolToUrl($url));
self::assertEquals($httpsUrl, Uri::addProtocolToUrl($url, $https));
self::assertEquals($httpsUrl, Uri::addProtocolToUrl($httpsUrl, $http));
}
/**
* @param mixed $url Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testReplenishProtocolEmptyUrl($url)
{
self::assertEquals('', Uri::replenishProtocol($url));
}
/**
* @param string $expected Expected result
* @param string $url The url to check and replenish
* @param string $protocol (optional) The protocol which is replenished. If is empty, protocol of current request
* is used.
*
* @dataProvider provideUrlsToReplenishProtocol
*/
public function testReplenishProtocol($expected, $url, $protocol = '')
{
self::assertSame($expected, Uri::replenishProtocol($url, $protocol));
}
/**
* Provides urls to replenish protocol
*
* @return \Generator
*/
public function provideUrlsToReplenishProtocol()
{
yield[
'://test',
'test',
'',
];
yield[
'ftp://lorem.ipsum',
'lorem.ipsum',
'ftp',
];
}
}

View File

@@ -0,0 +1,90 @@
<?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\Tests\Utilities;
use Meritoo\Common\Utilities\Xml;
use SimpleXMLElement;
/**
* Tests of the useful XML-related methods (only static functions)
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class XmlTest extends \PHPUnit_Framework_TestCase
{
private $simpleXml;
private $advancedXml;
public function testMergeNodes()
{
/*
* An empty XMLs
*/
$element1 = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><cars />');
$element2 = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><employees />');
$merged = Xml::mergeNodes($element1, $element2);
self::assertEquals('', (string)$merged);
/*
* XMLs with data
*/
$element1 = new SimpleXMLElement($this->simpleXml);
$element2 = new SimpleXMLElement($this->advancedXml);
$merged = Xml::mergeNodes($element1, $element2);
self::assertEquals('John', (string)$merged->author[0]->first_name);
}
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->simpleXml = '<?xml version="1.0" encoding="UTF-8"?>
<notes>
<note>Lorem ipsum</note>
<note>Dolor sit amet</note>
<note>Consectetur adipiscing elit</note>
<note>Donec ut</note>
<note>Mi a magna</note>
<note>Dapibus bibendum</note>
</notes>
';
$this->advancedXml = '<?xml version="1.0" encoding="UTF-8"?>
<authors>
<author>
<first_name>John</first_name>
<last_name>Scott</last_name>
<email>john.scott@fake.email</email>
</author>
<author>
<first_name>Julia</first_name>
<last_name>Brown</last_name>
<email>julia.brown@fake.email</email>
</author>
</authors>
';
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
parent::tearDown();
unset($this->simpleXml);
unset($this->advancedXml);
}
}