130 Commits

Author SHA1 Message Date
Meritoo
55dde2e898 Merge branch 'develop' 2018-07-02 09:34:53 +02:00
Meritoo
a32e0c4cca Documentation > Exceptions 2018-07-02 09:31:07 +02:00
Meritoo
834b24f348 Exceptions > create instance of exception using static "create()" method (instead of constructor) 2018-07-02 08:54:24 +02:00
Meritoo
9342f0e87e Docker > rename "php-cli" service to "php" 2018-07-02 08:47:56 +02:00
Meritoo
72fd87e165 Composer > support/require PHP 5.6+ (instead of 5.5.9+) 2018-07-02 08:12:26 +02:00
Meritoo
64499b49d3 Update @author and @copyright in classes' descriptions 2018-07-01 21:07:47 +02:00
Meritoo
848adef015 Arrays > minor refactoring 2018-07-01 17:45:03 +02:00
Meritoo
1431fd9935 Composer > require ext-pcre 2018-07-01 17:37:51 +02:00
Meritoo
3bb7a182c2 Merge branch 'develop' 2018-06-22 08:26:10 +02:00
Meritoo
5c9436e4e2 Collection > add() method > treat empty string as not provided index (same as null) 2018-06-22 08:10:06 +02:00
Meritoo
1a649d35e1 Merge branch 'develop' 2018-06-18 09:37:27 +02:00
Meritoo
107480d01b StyleCI > disable & remove 2018-06-16 14:43:16 +02:00
Meritoo
f4c12661b4 StyleCI configuration > fix bug "The provided fixer 'concat_with_spaces' cannot be enabled at the same time as 'concat_without_spaces'" 2018-06-16 14:36:33 +02:00
Meritoo
fc7df571e2 StyleCI configuration > fix bug "The provided fixer 'binary_operator_spaces' cannot be enabled again because it was already enabled" 2018-06-16 14:34:00 +02:00
Meritoo
0f37edfc9b Coding standard > fix automatically 2018-06-16 14:31:04 +02:00
Meritoo
ae3e82e233 Documentation > Docker > add paragraph for PHP Coding Standards Fixer 2018-06-16 14:21:01 +02:00
Meritoo
c99a099c31 StyleCI & PHP Coding Standards Fixer > update configuration 2018-06-16 14:15:35 +02:00
Meritoo
c443ef22d7 .gitignore > PHP Coding Standards Fixer > ignore custom settings 2018-06-16 14:12:07 +02:00
Meritoo
be8b4a3498 Arrays > remove unnecessary code 2018-06-16 14:10:57 +02:00
Meritoo
b1ddc6d561 .env.dist > enter default values (for easier .env creation) 2018-06-16 10:04:14 +02:00
Meritoo
ffe34eb9cf StyleCI > update configuration 2018-06-15 23:06:47 +02:00
Meritoo
155c091a3e StyleCI > update configuration 2018-06-15 23:04:06 +02:00
Meritoo
0a3955026b Revert "StyleCI > update configuration"
This reverts commit f9fa5f5
2018-06-15 23:00:53 +02:00
Meritoo
f9fa5f5915 StyleCI > update configuration 2018-06-15 23:00:29 +02:00
Meritoo
43945a8721 Composer > do not require symfony/http-foundation package
Miscellaneous > remove getCurlResponseWithHeaders() method
2018-06-15 22:54:00 +02:00
Meritoo
e9da0cf351 Reorganize documentation & update Readme 2018-06-14 22:28:53 +02:00
Meritoo
4c534394d9 Docker > Dockerfile > add "WORKDIR" (instead of "working_dir" in docker-compose.yml) 2018-06-14 21:35:50 +02:00
Meritoo
3726a26e47 Reorganize documentation & update Readme 2018-06-14 21:35:14 +02:00
Meritoo
fb24bc2ff1 Docker > use project-related binaries globally 2018-06-14 11:50:45 +02:00
Meritoo
57a78d1299 Reorganize documentation & update Readme 2018-06-14 11:32:54 +02:00
Meritoo
696cff023c Add changelog 2018-06-14 11:32:25 +02:00
Meritoo
9197682cd2 Readme > update paragraphs with Composer, Docker & use 1st level headers 2018-06-14 09:55:44 +02:00
Meritoo
49638ff1c3 .gitignore > update sections' separators 2018-06-13 22:21:28 +02:00
Meritoo
abf0ebf7ec Tests > increase code coverage 2018-06-09 14:25:20 +02:00
Meritoo
2e60176d95 Docker > Dockerfile > make bash terminal wider (increase columns count) 2018-06-07 20:56:48 +02:00
Meritoo
c351ce887a Tests > implement PHPUnit (instead of Codeception) 2018-06-07 20:51:55 +02:00
Meritoo
8a6262a8c3 Phing > tests > update name of property with path (tests_framework.path > tests.framework.path) & ignore /build directory 2018-05-28 21:22:00 +02:00
Meritoo
3c83a8800e Start names of special directories without dot 2018-05-28 21:10:20 +02:00
Meritoo
233473d915 Tests > implement Codeception (instead of PHPUnit) 2018-05-28 17:53:25 +02:00
Meritoo
7382bce842 Phing > tests > do not verify if the "tests" directory exists 2018-05-28 17:05:12 +02:00
Meritoo
c5b42017d2 Phing > tests > do not create database (for code coverage) 2018-05-28 17:03:19 +02:00
Meritoo
bc54f734e2 Phing > update properties.dist > remove unnecessary properties and disabled code 2018-05-28 16:56:59 +02:00
Meritoo
0eb5343df0 Docker > name of containers > use custom suffix
Docker > the "composer" service
2018-05-28 15:03:52 +02:00
Meritoo
52e74c8b48 Tests > increase code coverage 2018-05-28 15:03:11 +02:00
Meritoo
96bdb6eb60 Improve coding standard 2018-05-06 17:21:55 +02:00
Meritoo
5be449a83d Docker > Dockerfile > fix bug when error messages are displayed in french instead of english language (example: "chmod(): Aucun fichier ou dossier de ce type") 2018-05-06 14:40:17 +02:00
Meritoo
132a0a00e7 Docker > Dockerfile > fix bug "pecl/xdebug requires PHP (version >= 7.0.0), installed version is 5.5.38" 2018-05-04 12:53:45 +02:00
Meritoo
6fd18111b4 TravisCI - fix "No output has been received in the last 10m0s" bug (build times out because no output was received) 2018-04-04 21:54:45 +02:00
Meritoo
26c63ecb5c TravisCI > composer > install hirak/prestissimo package globally 2018-04-04 21:40:44 +02:00
Meritoo
bedb6333b9 TravisCI > "composer install" command > increase verbosity to maximum 2018-04-04 21:21:51 +02:00
Meritoo
ec2b5742ec Revert "TravisCI - fix "No output has been received in the last 10m0s" bug (build times out because no output was received)"
This reverts commit ec2f3c6
2018-04-04 21:16:36 +02:00
Meritoo
ec2f3c6ead TravisCI - fix "No output has been received in the last 10m0s" bug (build times out because no output was received) 2018-04-04 08:57:08 +02:00
Meritoo
834c12f280 TravisCI - install locales before running tests - remove unnecessary command 2018-04-03 22:57:41 +02:00
Meritoo
122ff41dad TravisCI - install locales before running tests 2018-04-03 19:13:38 +02:00
Meritoo
180a8b8b5d TravisCI - install locales before running tests 2018-04-03 17:10:40 +02:00
Meritoo
499c603d54 TravisCI - install locales before running tests 2018-04-03 17:04:43 +02:00
Meritoo
1cbc87222f TravisCI - install locales before running tests 2018-04-03 16:58:54 +02:00
Meritoo
129b75ea93 Revert "TravisCI - install locales before running tests"
This reverts commit aae7609
2018-04-03 16:58:32 +02:00
Meritoo
aae7609c8c TravisCI - install locales before running tests 2018-04-03 16:55:12 +02:00
Meritoo
5578b051a7 Update PHPDoc and comments 2018-04-03 08:26:51 +02:00
Meritoo
f111174ed2 Tests - increase code coverage 2018-04-03 08:22:10 +02:00
Meritoo
ddbff1b557 Update PHPDoc and comments 2018-04-02 22:46:52 +02:00
Meritoo
8d1df9ced8 Tests - increase code coverage 2018-04-02 22:44:30 +02:00
Meritoo
b7d0b61094 tests > PHPUnit configuration > update 2018-03-30 21:15:42 +02:00
Meritoo
ad64d2e02a Docker - Dockerfile - minor update 2018-01-27 13:10:14 +01:00
Meritoo
470b8244ec Utilities - Locale - getLocale() method - returns locale for given category 2018-01-27 13:05:20 +01:00
Meritoo
af38c35a1b Utilities - Locale - setLocale() method - return result of setting new locale (instead of "true")
Tests - Locale - fix incorrectly prepared tests
2018-01-27 13:04:04 +01:00
Meritoo
1e3e1d454e Docker - Dockerfile - install "locales" package & generate popular locales
Required to run tests related to setlocale() function (and Meritoo\Common\Utilities\Locale class) properly
2018-01-27 12:59:55 +01:00
Meritoo
57b411b59f Tests - increase code coverage 2018-01-17 21:37:07 +01:00
Meritoo
8a4860088f Phing - Composer-related task - validate Composer 2018-01-14 21:19:06 +01:00
Meritoo
e9b8fb8852 Regex - isBinaryValue() method - returns information if given value is a binary value 2018-01-10 17:35:42 +01:00
Meritoo
780d4df17e Tests - increase code coverage 2017-12-26 14:37:17 +01:00
Meritoo
d801e675fc Exception - InvalidHtmlAttributesException - an exception used while html attributes are invalid 2017-12-24 00:03:23 +01:00
Meritoo
6753076937 Regex - isValidHtmlAttribute() & areValidHtmlAttributes() methods - returns information if given html attribute is valid & if given html attributes are valid 2017-12-23 23:08:49 +01:00
Meritoo
7f713e0c6e Docker - name of containers - use custom prefix 2017-12-22 10:44:07 +01:00
Meritoo
ebbed4825c Bundle - getBundleViewPath() method - return path using namespaced syntax 2017-12-21 23:45:01 +01:00
Meritoo
7d23ff59d1 Bundle - getBundleViewPath() method - verify name of bundle 2017-12-21 22:45:23 +01:00
Meritoo
0e4c33241e Tests - BundleTest - minor refactoring 2017-12-21 22:05:07 +01:00
Meritoo
66aefa2446 Regex - isValidBundleName() method - returns information if given name of bundle is valid 2017-12-21 21:47:45 +01:00
Meritoo
5aaf7cde72 Minor refactoring 2017-12-21 20:41:12 +01:00
Meritoo
8bb529b88d Docker - Dockerfile - minor refactoring 2017-12-02 13:23:26 +01:00
Meritoo
3588c00009 Docker - do not install "zip" package 2017-12-02 13:12:34 +01:00
Meritoo
78480ac853 .gitignore - ignore .env 2017-12-02 12:53:32 +01:00
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
Meritoo
6c70fdd673 Revert "Composer - update packages"
This reverts commit 204e879
2017-09-20 22:00:09 +02:00
Meritoo
204e8793ac Composer - update packages 2017-09-20 21:55:05 +02:00
Meritoo
3dd37ae202 BaseTestCase - fix getting path of file used by tests (by implementing the Miscellaneous::getProjectRootPath() method) 2017-09-20 21:54:07 +02:00
Meritoo
ef017c9d6a Miscellaneous - getProjectRootPath() method - returns project's root path 2017-09-20 21:52:34 +02:00
Meritoo
5030dc2062 Refactor & fix coding standard 2017-09-20 21:47:39 +02:00
Meritoo
2c76158093 Readme - fix displaying 1st block of code 2017-09-20 16:19:36 +02:00
Meritoo
0b560fdf18 Exception - 3 exceptions related to file path & content 2017-09-20 13:50:18 +02:00
Meritoo
284d403061 Fix coding standard (minor fix) 2017-09-20 12:55:25 +02:00
Meritoo
7dbb3f9b2e Tests - update namespace of PHPUnit's TestCase
Related to update versions of the "dev" packages
2017-09-20 11:58:21 +02:00
Meritoo
fba821b798 Readme - StyleCI badge - update configuration file (required to fix failed StyleCI analysis) 2017-09-20 10:56:49 +02:00
Meritoo
3985c70076 Readme - minor update 2017-09-20 09:30:06 +02:00
Meritoo
921d4e6106 composer.json - update versions of the "dev" packages 2017-09-20 09:29:19 +02:00
Meritoo
7aa2239dbd Fix coding standard (no_blank_lines_after_phpdoc, single_blank_line_before_namespace, yoda_style) 2017-09-20 09:27:56 +02:00
Meritoo
e1fefcdeae Readme - move badges below description & update description 2017-09-19 20:10:27 +02:00
115 changed files with 9412 additions and 7181 deletions

15
.env.dist Normal file
View File

@@ -0,0 +1,15 @@
# -----------------------------------------------------------------------------
### Docker
# -----------------------------------------------------------------------------
#
# All containers
#
DOCKER_CONTAINER_OWNER=meritoo
DOCKER_CONTAINER_PROJECT=common-library
#
# PHP configuration:
# - timezone
#
TIMEZONE=Europe/Warsaw

69
.gitignore vendored
View File

@@ -1,44 +1,58 @@
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
# Environment-related parameters
# ------------------------------------------------------------------------------
.env
# ------------------------------------------------------------------------------
### Vendors ### Vendors
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/vendor/ /vendor/
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### Composer ### Composer
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/composer.lock
/composer.phar /composer.phar
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### Phing ### Phing
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/phing/properties /phing/properties
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### PHPUnit ### PHPUnit
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/phpunit.xml /phpunit.xml
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### PHP Coding Standards Fixer generated files ### PHP Coding Standards Fixer
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/.php_cs
/.php_cs.cache /.php_cs.cache
# ---------------------------------------------------------------------------------------------------------------------- # -----------------------------------------------------------------------------
### Build files
# -----------------------------------------------------------------------------
/build/
# ------------------------------------------------------------------------------
### Generated databases ### Generated databases
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/data/tmp /data/tmp
*.sql *.sql
*.sqlite *.sqlite
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### Compiled source ### Compiled source
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
*.com *.com
*.class *.class
*.dll *.dll
@@ -47,23 +61,22 @@
*.so *.so
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### Shell scripts ### Shell scripts
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/*.sh /*.sh
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### JetBrains ### JetBrains
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
/.idea /.idea
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### NetBeans template ### NetBeans template
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
nbproject/private/ nbproject/private/
build/
nbbuild/ nbbuild/
dist/ dist/
nbdist/ nbdist/
@@ -71,9 +84,9 @@ nbactions.xml
.nb-gradle/ .nb-gradle/
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### OSX template ### OSX template
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
.DS_Store .DS_Store
.AppleDouble .AppleDouble
.LSOverride .LSOverride
@@ -100,9 +113,9 @@ Temporary Items
.apdisk .apdisk
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### Linux template ### Linux template
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
*~ *~
# temporary files which can be created if a process still has a handle open of a deleted file # temporary files which can be created if a process still has a handle open of a deleted file
@@ -115,9 +128,9 @@ Temporary Items
.Trash-* .Trash-*
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
### Windows template ### Windows template
# ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------
# Windows image file caches # Windows image file caches
Thumbs.db Thumbs.db
ehthumbs.db ehthumbs.db

View File

@@ -1,13 +1,6 @@
<?php <?php
$finder = PhpCsFixer\Finder::create() $finder = PhpCsFixer\Finder::create()
/*
* Do not verify:
* - all DependencyInjection/Configuration classes: the Configuration.php files
* - autoloader from /app directory: autoload.php
*/
->notPath('/DependencyInjection\/Configuration\.php/')
->notPath('/autoload\.php/')
->in([ ->in([
__DIR__ . '/src', __DIR__ . '/src',
__DIR__ . '/tests', __DIR__ . '/tests',
@@ -15,16 +8,20 @@ $finder = PhpCsFixer\Finder::create()
return PhpCsFixer\Config::create() return PhpCsFixer\Config::create()
->setRules([ ->setRules([
'@Symfony' => true, '@Symfony' => true,
'phpdoc_summary' => false, 'binary_operator_spaces' => [
'phpdoc_separation' => false,
'phpdoc_align' => false,
'cast_spaces' => false,
'binary_operator_spaces' => [
'align_double_arrow' => true, 'align_double_arrow' => true,
], ],
'concat_space' => [ 'blank_line_before_return' => false,
'cast_spaces' => false,
'concat_space' => [
'spacing' => 'one', 'spacing' => 'one',
], ],
'phpdoc_add_missing_param_annotation' => true,
'phpdoc_align' => false,
'phpdoc_order' => true,
'phpdoc_separation' => false,
'phpdoc_summary' => false,
'trim_array_spaces' => false,
]) ])
->setFinder($finder); ->setFinder($finder);

View File

@@ -1 +0,0 @@
preset: symfony

View File

@@ -5,8 +5,12 @@ php:
- 7.0 - 7.0
- 7.1 - 7.1
before_install:
- sudo locale-gen de_DE.UTF-8 es_ES.UTF-8 en_GB.UTF-8 en_US.UTF-8 fr_FR.UTF-8 it_IT.UTF-8 pl_PL.UTF-8 ru_RU.UTF-8
- composer global require hirak/prestissimo
install: install:
- composer install - travis_wait 30 composer install -vvv
script: script:
- php ./vendor/bin/phpunit - php ./vendor/bin/phpunit

31
CHANGELOG.md Normal file
View File

@@ -0,0 +1,31 @@
# Meritoo Common Library
Common and useful classes, methods, exceptions etc.
# 0.1.0
1. Composer > support/require PHP 5.6+ (instead of 5.5.9+)
2. Docker > rename `php-cli` service to `php`
3. Exceptions > create instance of exception using static `create()` method (instead of constructor)
4. Documentation > Exceptions
# 0.0.21
1. Composer > require ext-pcre
2. Arrays > minor refactoring
3. Update @author and @copyright in classes' descriptions
# 0.0.20
1. Collection > add() method > treat empty string as not provided index (same as null)
# 0.0.19
1. Add this changelog
2. Reorganize documentation & update [Readme](README.md)
3. Docker: use project-related binaries globally
4. StyleCI & PHP Coding Standards Fixer: update configuration
5. Documentation > Docker > add paragraph for PHP Coding Standards Fixer
6. Coding standard > fix automatically
7. StyleCI configuration > fix bug "The provided fixer 'binary_operator_spaces' cannot be enabled again because it was already enabled"
8. StyleCI > disable & remove

105
README.md
View File

@@ -1,103 +1,28 @@
# Meritoo Common Library [![Travis](https://img.shields.io/travis/rust-lang/rust.svg?style=flat-square)](https://travis-ci.org/meritoo/common-library) [![Packagist](https://img.shields.io/packagist/v/meritoo/common-library.svg?style=flat-square)](https://packagist.org/packages/meritoo/common-library) [![StyleCI](https://styleci.io/repos/101790028/shield?branch=master)](https://styleci.io/repos/101790028) [![license](https://img.shields.io/github/license/meritoo/common-library.svg?style=flat-square)](https://github.com/meritoo/common-library) [![GitHub commits](https://img.shields.io/github/commits-since/meritoo/common-library/0.0.1.svg?style=flat-square)](https://github.com/meritoo/common-library) [![Coverage Status](https://coveralls.io/repos/github/meritoo/common-library/badge.svg?branch=master)](https://coveralls.io/github/meritoo/common-library?branch=master) # Meritoo Common Library
Useful classes, methods, extensions etc.
## Installation Common and useful classes, methods, exceptions etc.
Run [Composer](https://getcomposer.org) to install new package: [![Travis](https://img.shields.io/travis/rust-lang/rust.svg?style=flat-square)](https://travis-ci.org/meritoo/common-library) [![Packagist](https://img.shields.io/packagist/v/meritoo/common-library.svg?style=flat-square)](https://packagist.org/packages/meritoo/common-library) [![license](https://img.shields.io/github/license/meritoo/common-library.svg?style=flat-square)](https://github.com/meritoo/common-library) [![GitHub commits](https://img.shields.io/github/commits-since/meritoo/common-library/0.0.1.svg?style=flat-square)](https://github.com/meritoo/common-library) [![Coverage Status](https://coveralls.io/repos/github/meritoo/common-library/badge.svg?branch=master)](https://coveralls.io/github/meritoo/common-library?branch=master)
```bash # Installation
$ composer require meritoo/common-library
```
> How to install Composer: https://getcomposer.org/download Run [Composer](https://getcomposer.org) to install this package in your project:
## Static methods ```bash
composer require meritoo/common-library
This package contains a lot of class with static methods, so usage is not so complicated. Just run the static method who would you like to use. Example:
```php
use Meritoo\Common\Utilities\Arrays;
$firstElement = Arrays::getFirstElement(['lorem', 'ipsum']);
var_dump($firstElement); // string(5) "lorem"
``` ```
## Base test case with common methods and data providers > [How to install Composer?](https://getcomposer.org/download)
Located here: `Meritoo\Common\Test\Base\BaseTestCase`. Just extend the `BaseTestCase` class and use it like in `Meritoo\Common\Test\Utilities\DateTest` class: # Usage
```php 1. [Base test case (with common methods and data providers)](docs/Base-test-case.md)
class DateTest extends BaseTestCase 2. [Collection of elements](docs/Collection-of-elements.md)
{ 3. [Exceptions](docs/Static-methods.md)
/** 4. [Static methods](docs/Static-methods.md)
* @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetDateTimeEmptyValue($value)
{
self::assertFalse(Date::getDateTime($value));
}
(...) # Development
}
```
or in `Meritoo\Common\Test\Utilities\MimeTypesTest` class: More information [you can find here](docs/Development.md)
```php
class MimeTypesTest extends BaseTestCase
{
(...)
/**
* @param bool $mimeType The mime type, e.g. "video/mpeg"
* @dataProvider provideBooleanValue
*/
public function testGetExtensionBooleanMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
(...)
}
```
## Collection of elements
Located here: `Meritoo\Common\Collection\Collection`. It's a set of some elements, e.g. objects. It's iterable and countable. Provides very useful methods. Some of them:
- `getFirst()` - returns the first element in the collection
- `getLast()` - returns the last element in the collection
- `isEmpty()` - returns information if collection is empty
- `add($element, $index = null)` - adds given element (at the end of collection)
- `addMultiple($elements, $useIndexes = false)` - adds given elements (at the end of collection)
- `prepend($element)` - prepends given element (adds given element at the beginning of collection)
- `remove($element)` - removes given element
Examples of usage below.
#### An empty collection
```php
use Meritoo\Common\Collection\Collection;
$emptyCollection = new Collection();
var_dump($emptyCollection->isEmpty()); // bool(true)
```
#### Simple collection
```php
use Meritoo\Common\Collection\Collection;
$elements = [
'lorem',
'ipsum',
123 => 'dolor',
345 => 'sit',
];
$simpleCollection = new Collection($elements);
var_dump($simpleCollection->has('dolor')); // bool(true)
```
Enjoy! Enjoy!

View File

@@ -4,10 +4,10 @@
<if> <if>
<available file="phing/properties" property="custom.properties.available"/> <available file="phing/properties" property="custom.properties.available"/>
<then> <then>
<property file="phing/properties" /> <property file="phing/properties"/>
</then> </then>
<else> <else>
<property file="phing/properties.dist" /> <property file="phing/properties.dist"/>
</else> </else>
</if> </if>
@@ -18,18 +18,18 @@
<!-- Build app --> <!-- Build app -->
<target name="build:app" description="Prepares app to build and tests"> <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> </target>
<!-- Build tests --> <!-- Build tests -->
<target name="build:tests" description="Runs all tests, checks and creates docs"> <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. Conditional running of tests.
Disabled, because not required. Disabled, because not required.
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
<if> <if>

View File

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

3518
composer.lock generated

File diff suppressed because it is too large Load Diff

20
docker-compose.yml Normal file
View File

@@ -0,0 +1,20 @@
version: '3'
services:
php:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-php
entrypoint: php
command: -S 0.0.0.0:9999
build:
context: ./docker/config
args:
- TIMEZONE=$TIMEZONE
volumes:
- .:/project
composer:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-composer
entrypoint: composer
volumes:
- .:/project

131
docker/config/Dockerfile Normal file
View File

@@ -0,0 +1,131 @@
FROM php:5.6-cli
MAINTAINER Meritoo <github@meritoo.pl>
#
# Tools & libraries
#
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
vim \
git \
unzip \
libicu-dev \
locales \
&& apt-get clean \
&& rm -rf \
/var/lib/apt/lists/* \
/tmp/* \
/var/tmp/*
#
# Generating locales:
# - de_DE
# - es_ES
# - en_GB
# - en_US
# - fr_FR
# - it_IT
# - pl_PL
# - ru_RU
#
RUN sed -i 's/^# de_DE/de_DE/g; \
s/^# es_ES/es_ES/g; \
s/^# en_GB/en_GB/g; \
s/^# en_US/en_US/g; \
s/^# fr_FR/fr_FR/g; \
s/^# it_IT/it_IT/g; \
s/^# pl_PL/pl_PL/g; \
s/^# ru_RU/ru_RU/g;' /etc/locale.gen \
&& locale-gen
#
# Set default language
#
# Required to avoid problem with using strange language by error messages.
# Example: "chmod(): Aucun fichier ou dossier de ce type"
#
ENV LANGUAGE=en_US.UTF-8
#
# PHP extensions
#
RUN docker-php-ext-install \
intl \
mbstring
#
# PHP extensions (PECL):
# - Xdebug
#
RUN pecl install \
xdebug-2.5.5 \
&& docker-php-ext-enable \
xdebug
COPY xdebug.ini /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
#
# PHP configuration:
# - default configuration
# - timezone
#
COPY php.ini /usr/local/etc/php/php.ini
ARG TIMEZONE
RUN ln -snf /usr/share/zoneinfo/${TIMEZONE} /etc/localtime \
&& echo ${TIMEZONE} > /etc/timezone \
&& printf '[PHP]\ndate.timezone = "%s"\n' ${TIMEZONE} > /usr/local/etc/php/conf.d/tzone.ini \
&& "date"
#RUN echo "\n""date.timezone = $TIMEZONE""\n" >> /usr/local/etc/php/php.ini
#
# Phing
#
RUN pear channel-discover pear.phing.info \
&& pear install [--alldeps] phing/phing
#
# Composer - environment variables:
# - disable warning about running commands as root/super user
# - disable automatic clearing of sudo sessions
#
# More:
# https://getcomposer.org/doc/03-cli.md#composer-allow-superuser
#
ENV COMPOSER_ALLOW_SUPERUSER 1
#
# 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 \
--no-progress \
--no-suggest \
--no-interaction \
--prefer-dist \
--optimize-autoloader \
--classmap-authoritative \
hirak/prestissimo \
&& rm -rf ~/.composer/cache/* \
&& composer clear-cache \
&& composer --version
#
# Bash
#
RUN sed -i 's/^# export/export/g; \
s/^# alias/alias/g;' ~/.bashrc \
&& echo 'COLUMNS=200'"\n" >> ~/.bashrc
#
# Use project-related binaries globally
#
ENV PATH="/project/vendor/bin:${PATH}"
WORKDIR /project

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

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

6
docker/config/xdebug.ini Normal file
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

52
docs/Base-test-case.md Normal file
View File

@@ -0,0 +1,52 @@
# Meritoo Common Library
Common and useful classes, methods, exceptions etc.
# Base test case (with common methods and data providers)
Located here: `Meritoo\Common\Test\Base\BaseTestCase`. Just extend the `BaseTestCase` class and use it like in `Meritoo\Common\Test\Utilities\DateTest` class:
```php
class DateTest extends BaseTestCase
{
/**
* @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue
*/
public function testGetDateTimeEmptyValue($value)
{
self::assertFalse(Date::getDateTime($value));
}
(...)
}
```
or in `Meritoo\Common\Test\Utilities\MimeTypesTest` class:
```php
class MimeTypesTest extends BaseTestCase
{
(...)
/**
* @param bool $mimeType The mime type, e.g. "video/mpeg"
* @dataProvider provideBooleanValue
*/
public function testGetExtensionBooleanMimeType($mimeType)
{
self::assertEquals('', MimeTypes::getExtension($mimeType));
}
(...)
}
```
# More
1. [**Base test case (with common methods and data providers)**](Base-test-case.md)
2. [Collection of elements](Collection-of-elements.md)
3. [Exceptions](Exceptions.md)
4. [Static methods](Static-methods.md)
[&lsaquo; Back to `Readme`](../README.md)

View File

@@ -0,0 +1,50 @@
# Meritoo Common Library
Common and useful classes, methods, exceptions etc.
# Collection of elements
Located here: `Meritoo\Common\Collection\Collection`. It's a set of some elements, e.g. objects. It's iterable and countable. Provides very useful methods. Some of them:
- `getFirst()` - returns the first element in the collection
- `getLast()` - returns the last element in the collection
- `isEmpty()` - returns information if collection is empty
- `add($element, $index = null)` - adds given element (at the end of collection)
- `addMultiple($elements, $useIndexes = false)` - adds given elements (at the end of collection)
- `prepend($element)` - prepends given element (adds given element at the beginning of collection)
- `remove($element)` - removes given element
Examples of usage below.
### An empty collection
```php
use Meritoo\Common\Collection\Collection;
$emptyCollection = new Collection();
var_dump($emptyCollection->isEmpty()); // bool(true)
```
### Simple collection
```php
use Meritoo\Common\Collection\Collection;
$elements = [
'lorem',
'ipsum',
123 => 'dolor',
345 => 'sit',
];
$simpleCollection = new Collection($elements);
var_dump($simpleCollection->has('dolor')); // bool(true)
```
# More
1. [Base test case (with common methods and data providers)](Base-test-case.md)
2. [**Collection of elements**](Collection-of-elements.md)
3. [Exceptions](Exceptions.md)
4. [Static methods](Static-methods.md)
[&lsaquo; Back to `Readme`](../README.md)

119
docs/Development.md Normal file
View File

@@ -0,0 +1,119 @@
# Meritoo Common Library
Development-related information
# Requirements
* [Docker](https://www.docker.com)
* Your favourite IDE :)
# Getting started
1. Build, create and start Docker's containers by running command:
```bash
docker-compose up -d
```
2. Install packages by running command:
```bash
docker-compose run composer install
```
> [What is Docker?](https://www.docker.com/what-docker)
# Composer
Available as `composer` service. You can run any Composer's command using the `composer` service:
```bash
docker-compose run composer <command>
```
Examples below.
##### Install packages
```bash
docker-compose run composer install
```
##### Update packages
```bash
docker-compose run composer update
```
##### Add package
```bash
docker-compose run composer require <vendor>/<package>
```
##### Remove package
```bash
docker-compose run composer remove <vendor>/<package>
```
# Coding Standards Fixer
Fix coding standard by running command:
```bash
docker-compose exec php php-cs-fixer fix
```
Omit cache and run the Fixer from scratch by running command:
```bash
docker-compose exec php rm .php_cs.cache && docker-compose exec php php-cs-fixer fix
```
> [Want more?](https://cs.sensiolabs.org)
# Tests
### Prerequisites
Install required packages by running command: `docker-compose run composer install`.
### Running tests
#### Simply & quick, without code coverage
Tests are running using Docker and `php` service defined in `docker-compose.yml`. Example:
```bash
docker-compose exec php phpunit --no-coverage
```
You can also run them in container. In this case you have to run 2 commands:
1. Enter container:
```bash
docker-compose exec php bash
```
2. Run tests:
```bash
phpunit --no-coverage
```
#### With code coverage
```bash
docker-compose exec php phpunit
```
# Other
Rebuild project and run tests by running command:
```bash
docker-compose exec php phing
```
[&lsaquo; Back to `Readme`](../README.md)

61
docs/Exceptions.md Normal file
View File

@@ -0,0 +1,61 @@
# Meritoo Common Library
Common and useful classes, methods, exceptions etc.
# Exceptions
### Create instance of exception
This package contains a lot of exceptions. Each of them contains static method `create()` with proper arguments that is used to create instance of the exception. Example:
```php
use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException;
throw IncorrectBundleNameException::create('RisusIpsum');
```
### Base exception for unknown type of something
##### Short description
It's a `Meritoo\Common\Exception\Base\UnknownTypeException` class. Related to `Meritoo\Common\Type\Base\BaseType` class that represents type of something, e.g. type of button, order.
##### Usage
You can extend `Meritoo\Common\Exception\Base\UnknownTypeException` class and create your own static method, e.g. `createException()`, which will be used create instance of the exception. Inside the `createException()` method you can call `parent::create()` method.
##### Example
```php
<?php
namespace Your\Package\Exception\Type;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Your\Package\Type\SimpleType;
class UnknownSimpleTypeException extends UnknownTypeException
{
/**
* Creates exception
*
* @param string $unknownType Unknown and simple type
* @return UnknownSimpleTypeException
*/
public static function createException($unknownType)
{
/* @var UnknownSimpleTypeException $exception */
$exception = parent::create($unknownType, new SimpleType(), 'my simple type of something');
return $exception;
}
}
```
# More
1. [Base test case (with common methods and data providers)](Base-test-case.md)
2. [Collection of elements](Collection-of-elements.md)
3. [**Exceptions**](Exceptions.md)
4. [Static methods](Static-methods.md)
[&lsaquo; Back to `Readme`](../README.md)

23
docs/Static-methods.md Normal file
View File

@@ -0,0 +1,23 @@
# Meritoo Common Library
Common and useful classes, methods, exceptions etc.
# Static methods
This package contains a lot of class with static methods, so usage is not so complicated. Just run the static method who would you like to use. Example:
```php
use Meritoo\Common\Utilities\Arrays;
$firstElement = Arrays::getFirstElement(['lorem', 'ipsum']);
var_dump($firstElement); // string(5) "lorem"
```
# More
1. [Base test case (with common methods and data providers)](Base-test-case.md)
2. [Collection of elements](Collection-of-elements.md)
3. [Exceptions](Exceptions.md)
4. [**Static methods**](Static-methods.md)
[&lsaquo; Back to `Readme`](../README.md)

View File

@@ -4,10 +4,10 @@
<if> <if>
<available file="phing/properties" property="custom.properties.available"/> <available file="phing/properties" property="custom.properties.available"/>
<then> <then>
<property file="phing/properties" /> <property file="phing/properties"/>
</then> </then>
<else> <else>
<property file="phing/properties.dist" /> <property file="phing/properties.dist"/>
</else> </else>
</if> </if>
@@ -21,9 +21,9 @@
depends="app:composer, app:vendors, app:checkout" depends="app:composer, app:vendors, app:checkout"
description="Prepares app to build." /> description="Prepares app to build." />
<!-- Check / update composer --> <!-- Updates Composer and validates composer.* files -->
<target name="app:composer" description="Checks / updates composer"> <target name="app:composer" description="Updates Composer and validates composer.* files">
<echo msg="Checking / updating composer..." /> <echo msg="Updating Composer and validating composer.* files..." />
<if> <if>
<available file="composer.phar" /> <available file="composer.phar" />
@@ -42,7 +42,14 @@
</if> </if>
</else> </else>
</if> </if>
<!-- Update Composer -->
<composer command="selfupdate" /> <composer command="selfupdate" />
<!-- Validate Composer -->
<composer command="validate">
<arg line="--no-check-all --strict" />
</composer>
</target> </target>
<!-- Project Install/update vendors --> <!-- Project Install/update vendors -->
@@ -68,6 +75,8 @@
<then> <then>
<composer php="${composer.php}" composer="${composer.path}" command="install"> <composer php="${composer.php}" composer="${composer.path}" command="install">
<arg value="--optimize-autoloader" /> <arg value="--optimize-autoloader" />
<arg value="--prefer-dist" />
<arg value="--classmap-authoritative" />
</composer> </composer>
</then> </then>
<else> <else>

View File

@@ -28,7 +28,13 @@ assets.installWithSymlink = true
# Clear cache with the "warmup" option # 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
#
# Meritoo <github@meritoo.pl>
# 2017-06-06
#
cache.clearWithWarmup = false
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Composer # Composer
@@ -75,7 +81,7 @@ dir.reports.coverage = ${dir.reports}/phpunit_coverage
# Disabled, because unnecessary right now # Disabled, because unnecessary right now
# phpdocumentor/phpdocumentor cannot be installed via Composer # phpdocumentor/phpdocumentor cannot be installed via Composer
# #
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl> # Meritoo <github@meritoo.pl>
# 2017-02-22 # 2017-02-22
# #
#dir.docs = ${dir.build}/docs #dir.docs = ${dir.build}/docs
@@ -85,40 +91,15 @@ dir.reports.coverage = ${dir.reports}/phpunit_coverage
# Data directories # Data directories
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
dir.data.tests = ${dir.data}/tests
dir.data.temporary = ${dir.data}/tmp dir.data.temporary = ${dir.data}/tmp
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Testing # Testing
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Test database path # Path of the framework used to run unit tests
# #
tests.database = ${dir.data.temporary}/database.sqlite tests.framework.path = ./vendor/bin/phpunit --verbose --no-coverage --testdox
#
# Disabled, because unnecessary right now
# PHPUnit is installed and loaded by Composer
#
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
# 2017-02-22
#
# Run PHPUnit using exec task instead of phpunitTask
#phpunit.useExec = false
#
# Disabled, because unnecessary right now
# We want generate code coverage always
#
# Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
# 2017-02-22
#
# Collect coverage data during tests
#phpunit.withCoverage = true
# Path of the PHPUnit (https://phpunit.de)
#
phpUnit.path = ./vendor/bin/phpunit
# Path of the PHP Coding Standards Fixer (http://cs.sensiolabs.org) # Path of the PHP Coding Standards Fixer (http://cs.sensiolabs.org)
# #

View File

@@ -4,7 +4,7 @@
The AutoloaderTask is required to load binaries installed by Composer. The AutoloaderTask is required to load binaries installed by Composer.
The "autoloaderpath" attribute of this task is not required, because it's default value is: vendor/autoload.php. The "autoloaderpath" attribute of this task is not required, because it's default value is: vendor/autoload.php.
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-23 2017-02-23
--> -->
<autoloader /> <autoloader />
@@ -13,10 +13,10 @@
<if> <if>
<available file="phing/properties" property="custom.properties.available"/> <available file="phing/properties" property="custom.properties.available"/>
<then> <then>
<property file="phing/properties" /> <property file="phing/properties"/>
</then> </then>
<else> <else>
<property file="phing/properties.dist" /> <property file="phing/properties.dist"/>
</else> </else>
</if> </if>
@@ -48,7 +48,7 @@
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2 a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.* b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
--> -->
@@ -73,7 +73,7 @@
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2 a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.* b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
--> -->
<!--<target name="build:doc"--> <!--<target name="build:doc"-->
@@ -87,7 +87,7 @@
<!-- Test target --> <!-- Test target -->
<target name="build:test" <target name="build:test"
depends="test:phpunit" depends="test:unit"
description="Executes all tests" /> description="Executes all tests" />
<!-- Project build clean --> <!-- Project build clean -->
@@ -103,8 +103,8 @@
<!--<mkdir dir="${dir.docs}" />--> <!--<mkdir dir="${dir.docs}" />-->
<!--<mkdir dir="${dir.docs.phpdoc2}" />--> <!--<mkdir dir="${dir.docs.phpdoc2}" />-->
<mkdir dir="${dir.reports}" /> <mkdir dir="${dir.reports}" />
<mkdir dir="${dir.reports.coverage}" />
<mkdir dir="${dir.reports.pdepend}" /> <mkdir dir="${dir.reports.pdepend}" />
<mkdir dir="${dir.reports.coverage}"/>
</target> </target>
<!-- PHPDocumentor2 API documentation target --> <!-- PHPDocumentor2 API documentation target -->
@@ -113,7 +113,7 @@
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2 a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.* b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
<target name="doc:phpdoc2" description="Generates API documentations"> <target name="doc:phpdoc2" description="Generates API documentations">
@@ -142,7 +142,7 @@
via Composer the Symfony2 standard is not included / available in this package. In this case the PHP Coding via Composer the Symfony2 standard is not included / available in this package. In this case the PHP Coding
Standards Fixer (http://cs.sensiolabs.org) is used. Standards Fixer (http://cs.sensiolabs.org) is used.
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
--> -->
<target name="check:cs" description="Checks coding standard"> <target name="check:cs" description="Checks coding standard">
@@ -166,7 +166,7 @@
<!-- <!--
Previous / old version Previous / old version
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
<exec command="phpcpd \-\-log-pmd=${dir.reports}/pmd-cpd.xml ${dir.src}" /> <exec command="phpcpd \-\-log-pmd=${dir.reports}/pmd-cpd.xml ${dir.src}" />
@@ -204,7 +204,7 @@
<!-- <!--
Previous / old version Previous / old version
Krzysztof Niziol <krzysztof.niziol@meritoo.pl> Meritoo <github@meritoo.pl>
2017-02-22 2017-02-22
<exec command="phploc \-\-log-csv=${dir.reports}/phploc.csv ${dir.src}" /> <exec command="phploc \-\-log-csv=${dir.reports}/phploc.csv ${dir.src}" />
@@ -212,94 +212,9 @@
</target> </target>
<!-- Unit tests --> <!-- Unit tests -->
<target name="test:phpunit" description="Executes PHPUnit tests"> <target name="test:unit" description="Executes unit tests">
<!-- Check test database -->
<if>
<not>
<available file="${dir.data.tests}" type="dir" property="dir.data.tests.available" />
</not>
<then>
<mkdir dir="${dir.data.tests}" />
</then>
</if>
<if>
<not>
<available file="${tests.database}" property="tests.database.available" />
</not>
<then>
<touch file="${tests.database}" />
</then>
</if>
<echo msg="Running unit tests..." /> <echo msg="Running unit tests..." />
<coverage-setup database="${dir.reports.coverage}/coverage.db"> <exec command="${tests.framework.path}" passthru="true"/>
<fileset refid="sourcecode" />
</coverage-setup>
<exec command="${phpUnit.path} --verbose --configuration ${project.basedir}/phpunit.xml.dist" passthru="true" />
<!--
I have to use ExecTask to run PHPUnit instead of PHPUnitTask, because tests are not running if PHPUnitTask is
used (don't know why):
Total tests run: 0, Failures: 0, Errors: 0, Incomplete: 0, Skipped: 0
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-23
<phpunit configuration="${project.basedir}/phpunit.xml.dist" printsummary="true">
<formatter type="xml" todir="${dir.reports}" outfile="phpunit.xml" />
<formatter type="plain" todir="${dir.reports}" outfile="phpunit.txt" />
<formatter type="clover" todir="${dir.reports.coverage}" />
<formatter type="summary" todir="${dir.reports}" outfile="phpunit_summary.txt" />
</phpunit>
-->
<!--
Previous / old version
Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
2017-02-22
<if>
<istrue value="${phpunit.useExec}" />
<then>
<if>
<istrue value="${phpunit.withCoverage}" />
<then>
<echo message="Running tests with code coverage..." />
<exec command="phpunit \-\-log-junit ${dir.reports}/phpunit.xml \-\-coverage-clover ${dir.reports.coverage}/clover-coverage.xml \-\-coverage-crap4j ${dir.reports.coverage}/crap4j-coverage.xml \-\-coverage-html ${dir.reports.coverage}/ -c ${project.basedir} \-\-colors" passthru="true" checkreturn="true" />
</then>
<else>
<echo message="Running tests without code coverage..." />
<exec command="phpunit \-\-log-junit ${dir.reports}/phpunit.xml -c ${project.basedir} \-\-colors" passthru="true" checkreturn="true" />
</else>
</if>
</then>
<else>
<if>
<istrue value="${phpunit.withCoverage}" />
<then>
<echo message="Running tests with code coverage..." />
<coverage-setup database="${dir.reports.coverage}/coverage.db">
<fileset refid="sourcecode" />
</coverage-setup>
<phpunit printsummary="true" codecoverage="true">
<formatter type="xml" todir="${dir.reports}" outfile="phpunit.xml" />
<formatter type="plain" todir="${dir.reports}" outfile="phpunit.txt" />
<formatter type="clover" todir="${dir.reports.coverage}" />
<formatter type="summary" todir="${dir.reports}" outfile="phpunit_summary.txt" />
</phpunit>
</then>
<else>
<echo message="Running tests without code coverage..." />
<phpunit printsummary="true">
<formatter todir="${dir.reports}" type="xml" outfile="phpunit.xml" />
<batchtest>
<fileset refid="tests" />
</batchtest>
</phpunit>
</else>
</if>
</else>
</if>
-->
</target> </target>
<!-- Checkout and finalization --> <!-- Checkout and finalization -->

View File

@@ -1,16 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false" <phpunit
backupStaticAttributes="false" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
colors="true" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/4.8/phpunit.xsd"
convertErrorsToExceptions="true" backupGlobals="true"
convertNoticesToExceptions="true" backupStaticAttributes="false"
convertWarningsToExceptions="true" bootstrap="./vendor/autoload.php"
processIsolation="false" cacheTokens="false"
stopOnFailure="false" colors="true"
syntaxCheck="true" convertErrorsToExceptions="true"
bootstrap="./vendor/autoload.php" convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
stopOnRisky="false"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
timeoutForSmallTests="1"
timeoutForMediumTests="10"
timeoutForLargeTests="60"
verbose="true"
> >
<php>
<ini name="error_reporting" value="-1"/>
</php>
<testsuites> <testsuites>
<testsuite name="Meritoo Package - Main Test Suite"> <testsuite name="Meritoo Package - Main Test Suite">
<directory>./tests/</directory> <directory>./tests/</directory>
@@ -30,6 +48,6 @@
</groups> </groups>
<logging> <logging>
<log type="coverage-html" target="./build/logs/phpunit_coverage/html" /> <log type="coverage-html" target="./build/logs/phpunit_coverage/html"/>
</logging> </logging>
</phpunit> </phpunit>

View File

@@ -18,20 +18,20 @@ use Meritoo\Common\Utilities\Arrays;
* Collection of elements. * Collection of elements.
* It's a set of some elements, e.g. objects. * It's a set of some elements, e.g. objects.
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Collection implements Countable, ArrayAccess, IteratorAggregate class Collection implements Countable, ArrayAccess, IteratorAggregate
{ {
/** /**
* The elements of collection. * The elements of collection
* *
* @var array * @var array
*/ */
private $elements; private $elements;
/** /**
* Class constructor. * Class constructor
* *
* @param array $elements (optional) The elements of collection * @param array $elements (optional) The elements of collection
*/ */
@@ -42,7 +42,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
/** /**
* {@inheritdoc} * {@inheritdoc}
* Required by interface Countable. * Required by interface Countable
*/ */
public function count() public function count()
{ {
@@ -51,7 +51,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
/** /**
* {@inheritdoc} * {@inheritdoc}
* Required by interface ArrayAccess. * Required by interface ArrayAccess
*/ */
public function offsetExists($offset) public function offsetExists($offset)
{ {
@@ -60,7 +60,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
/** /**
* {@inheritdoc} * {@inheritdoc}
* Required by interface ArrayAccess. * Required by interface ArrayAccess
*/ */
public function offsetGet($offset) public function offsetGet($offset)
{ {
@@ -73,7 +73,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
/** /**
* {@inheritdoc} * {@inheritdoc}
* Required by interface ArrayAccess. * Required by interface ArrayAccess
*/ */
public function offsetSet($offset, $value) public function offsetSet($offset, $value)
{ {
@@ -82,7 +82,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
/** /**
* {@inheritdoc} * {@inheritdoc}
* Required by interface ArrayAccess. * Required by interface ArrayAccess
*/ */
public function offsetUnset($offset) public function offsetUnset($offset)
{ {
@@ -93,7 +93,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
/** /**
* {@inheritdoc} * {@inheritdoc}
* Required by interface IteratorAggregate. * Required by interface IteratorAggregate
*/ */
public function getIterator() public function getIterator()
{ {
@@ -101,16 +101,15 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Adds given element (at the end of collection). * Adds given element (at the end of collection)
* *
* @param mixed $element The element to add * @param mixed $element The element to add
* @param mixed $index (optional) Index / key of the element * @param mixed $index (optional) Index / key of the element
*
* @return $this * @return $this
*/ */
public function add($element, $index = null) public function add($element, $index = null)
{ {
if ($index === null) { if (null === $index || '' === $index) {
$this->elements[] = $element; $this->elements[] = $element;
} else { } else {
$this->elements[$index] = $element; $this->elements[$index] = $element;
@@ -120,12 +119,11 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Adds given elements (at the end of collection). * Adds given elements (at the end of collection)
* *
* @param array|Collection $elements The elements to add * @param array|Collection $elements The elements to add
* @param bool|false $useIndexes (optional) If is set to true, indexes of given elements will be used in * @param bool|false $useIndexes (optional) If is set to true, indexes of given elements will be used in
* this collection. Otherwise - not. * this collection. Otherwise - not.
*
* @return $this * @return $this
*/ */
public function addMultiple($elements, $useIndexes = false) public function addMultiple($elements, $useIndexes = false)
@@ -144,10 +142,9 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Prepends given element (adds given element at the beginning of collection). * Prepends given element (adds given element at the beginning of collection)
* *
* @param mixed $element The element to prepend * @param mixed $element The element to prepend
*
* @return $this * @return $this
*/ */
public function prepend($element) public function prepend($element)
@@ -158,10 +155,9 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Removes given element. * Removes given element
* *
* @param mixed $element The element to remove * @param mixed $element The element to remove
*
* @return $this * @return $this
*/ */
public function remove($element) public function remove($element)
@@ -170,7 +166,6 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
foreach ($this->elements as $index => $existing) { foreach ($this->elements as $index => $existing) {
if ($element === $existing) { if ($element === $existing) {
unset($this->elements[$index]); unset($this->elements[$index]);
break; break;
} }
} }
@@ -180,7 +175,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns information if collection is empty. * Returns information if collection is empty
* *
* @return bool * @return bool
*/ */
@@ -190,10 +185,9 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns information if given element is first in the collection. * Returns information if given element is first in the collection
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
*
* @return bool * @return bool
*/ */
public function isFirst($element) public function isFirst($element)
@@ -202,10 +196,9 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns information if given element is last in the collection. * Returns information if given element is last in the collection
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
*
* @return bool * @return bool
*/ */
public function isLast($element) public function isLast($element)
@@ -214,24 +207,22 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns information if the collection has given element, iow. if given element exists in the collection. * Returns information if the collection has given element, iow. if given element exists in the collection
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
*
* @return bool * @return bool
*/ */
public function has($element) public function has($element)
{ {
$index = Arrays::getIndexOf($this->elements, $element); $index = Arrays::getIndexOf($this->elements, $element);
return $index !== null && $index !== false; return null !== $index && false !== $index;
} }
/** /**
* Returns previous element for given element. * Returns previous element for given element
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
*
* @return mixed|null * @return mixed|null
*/ */
public function getPrevious($element) public function getPrevious($element)
@@ -240,10 +231,9 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns next element for given element. * Returns next element for given element
* *
* @param mixed $element The element to verify * @param mixed $element The element to verify
*
* @return mixed|null * @return mixed|null
*/ */
public function getNext($element) public function getNext($element)
@@ -252,7 +242,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns the first element in the collection. * Returns the first element in the collection
* *
* @return mixed * @return mixed
*/ */
@@ -262,7 +252,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns the last element in the collection. * Returns the last element in the collection
* *
* @return mixed * @return mixed
*/ */
@@ -272,7 +262,7 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns an array representation of the collection. * Returns an array representation of the collection
* *
* @return array * @return array
*/ */
@@ -282,10 +272,9 @@ class Collection implements Countable, ArrayAccess, IteratorAggregate
} }
/** /**
* Returns information if element with given index/key exists. * Returns information if element with given index/key exists
* *
* @param string|int $index The index/key of element * @param string|int $index The index/key of element
*
* @return bool * @return bool
*/ */
private function exists($index) private function exists($index)

View File

@@ -13,29 +13,30 @@ use Meritoo\Common\Type\Base\BaseType;
use Meritoo\Common\Utilities\Arrays; use Meritoo\Common\Utilities\Arrays;
/** /**
* An exception used while type of something is unknown. * An exception used while type of something is unknown
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
abstract class UnknownTypeException extends Exception abstract class UnknownTypeException extends Exception
{ {
/** /**
* Class constructor. * Creates exception
* *
* @param string|int $unknownType The unknown type of something (value of constant) * @param string|int $unknownType The unknown type of something (value of constant)
* @param BaseType $typeInstance An instance of class that contains type of the something * @param BaseType $typeInstance An instance of class that contains type of the something
* @param string $typeName Name of the something * @param string $typeName Name of the something
* @return UnknownTypeException
*/ */
public function __construct($unknownType, BaseType $typeInstance, $typeName) public static function create($unknownType, BaseType $typeInstance, $typeName)
{ {
$template = 'The \'%s\' type of %s is unknown. Probably doesn\'t exist or there is a typo. You should use one'
. ' of these types: %s.';
$allTypes = $typeInstance->getAll(); $allTypes = $typeInstance->getAll();
$types = Arrays::values2string($allTypes, '', ', '); $types = Arrays::values2string($allTypes, '', ', ');
$template = 'The \'%s\' type of %s is unknown. Probably doesn\'t exist or there is a typo. You should use one'
.' of these types: %s.';
$message = sprintf(sprintf($template, $unknownType, $typeName, $types)); $message = sprintf(sprintf($template, $unknownType, $typeName, $types));
parent::__construct($message);
return new static($message);
} }
} }

View File

@@ -0,0 +1,36 @@
<?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\Bundle;
use Exception;
/**
* An exception used while name of bundle is incorrect
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class IncorrectBundleNameException extends Exception
{
/**
* Creates exception
*
* @param string $bundleName Incorrect name of bundle
* @return IncorrectBundleNameException
*/
public static function create($bundleName)
{
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
. ' there everything ok?';
$message = sprintf($template, $bundleName);
return new static($message);
}
}

View File

@@ -0,0 +1,32 @@
<?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\File;
/**
* An exception used while file with given path is empty (has no content)
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class EmptyFileException extends \Exception
{
/**
* Creates exception
*
* @param string $emptyFilePath Path of the empty file
* @return EmptyFileException
*/
public static function create($emptyFilePath)
{
$template = 'File with path \'%s\' is empty (has no content). Did you provide path of proper file?';
$message = sprintf($template, $emptyFilePath);
return new static($message);
}
}

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\Exception\File;
/**
* An exception used while path of given file is empty
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class EmptyFilePathException extends \Exception
{
/**
* Creates exception
*/
public static function create()
{
return new static('Path of the file is empty. Did you provide path of proper file?');
}
}

View File

@@ -0,0 +1,32 @@
<?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\File;
/**
* An exception used while file with given path does not exist
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class NotExistingFileException extends \Exception
{
/**
* Creates exception
*
* @param string $notExistingFilePath Path of not existing (or not readable) file
* @return NotExistingFileException
*/
public static function create($notExistingFilePath)
{
$template = 'File with path \'%s\' does not exist (or is not readable). Did you provide path of proper file?';
$message = sprintf($template, $notExistingFilePath);
return new static($message);
}
}

View File

@@ -0,0 +1,40 @@
<?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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class DisabledMethodException extends Exception
{
/**
* Creates exception
*
* @param string $disabledMethod Name of the disabled method
* @param string $alternativeMethod (optional) Name of the alternative method
* @return DisabledMethodException
*/
public static function create($disabledMethod, $alternativeMethod = '')
{
$template = 'Method %s() cannot be called, because is disabled.';
if (!empty($alternativeMethod)) {
$template .= ' Use %s() instead.';
}
$message = sprintf($template, $disabledMethod, $alternativeMethod);
return new static($message);
}
}

View File

@@ -11,22 +11,23 @@ namespace Meritoo\Common\Exception\Reflection;
use Exception; use Exception;
/** /**
* An exception used while name of class or trait cannot be resolved. * An exception used while name of class or trait cannot be resolved
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class CannotResolveClassNameException extends Exception class CannotResolveClassNameException extends Exception
{ {
/** /**
* Class constructor. * Creates exception
* *
* @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. * namespaces, object or namespace.
* @param bool $forClass (optional) If is set to true, message of this exception for class is * @param bool $forClass (optional) If is set to true, message of this exception for class is
* prepared. Otherwise - for trait. * prepared. Otherwise - for trait.
* @return CannotResolveClassNameException
*/ */
public function __construct($source, $forClass = true) public static function create($source, $forClass = true)
{ {
$forWho = 'trait'; $forWho = 'trait';
$value = ''; $value = '';
@@ -36,12 +37,12 @@ class CannotResolveClassNameException extends Exception
} }
if (is_scalar($source)) { if (is_scalar($source)) {
$value = sprintf(' %s', (string) $source); $value = sprintf(' %s', (string)$source);
} }
$template = 'Name of %s from given \'%s\'%s cannot be resolved. Is there everything ok?'; $template = 'Name of %s from given \'%s\'%s cannot be resolved. Is there everything ok?';
$message = sprintf($template, $forWho, gettype($source), $value); $message = sprintf($template, $forWho, gettype($source), $value);
parent::__construct($message); return new static($message);
} }
} }

View File

@@ -12,27 +12,28 @@ use Exception;
use Meritoo\Common\Utilities\Reflection; use Meritoo\Common\Utilities\Reflection;
/** /**
* An exception used while given class has no child classes. * An exception used while given class has no child classes
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class MissingChildClassesException extends Exception class MissingChildClassesException extends Exception
{ {
/** /**
* Class constructor. * Creates exception
* *
* @param array|object|string $parentClass Class that hasn't child classes, but it should. An array of objects, * @param array|object|string $parentClass Class that hasn't child classes, but it should. An array of objects,
* strings, object or string. * strings, object or string.
* @return MissingChildClassesException
*/ */
public function __construct($parentClass) public static function create($parentClass)
{ {
$template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract' $template = 'The \'%s\' class requires one child class at least who will extend her (maybe is an abstract'
.' class), but the child classes are missing. Did you forget to extend this class?'; . ' class), but the child classes are missing. Did you forget to extend this class?';
$parentClassName = Reflection::getClassName($parentClass); $parentClassName = Reflection::getClassName($parentClass);
$message = sprintf($template, $parentClassName); $message = sprintf($template, $parentClassName);
parent::__construct($message); return new static($message);
} }
} }

View File

@@ -12,28 +12,29 @@ use Exception;
use Meritoo\Common\Utilities\Reflection; use Meritoo\Common\Utilities\Reflection;
/** /**
* An exception used while given class has more than one child class. * An exception used while given class has more than one child class
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class TooManyChildClassesException extends Exception class TooManyChildClassesException extends Exception
{ {
/** /**
* Class constructor. * Creates exception
* *
* @param array|object|string $parentClass Class that has more than one child class, but it shouldn't. An array * @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. * of objects, strings, object or string.
* @param array $childClasses Child classes * @param array $childClasses Child classes
* @return TooManyChildClassesException
*/ */
public function __construct($parentClass, array $childClasses) public static function create($parentClass, array $childClasses)
{ {
$template = "The '%s' class requires one child class at most who will extend her, but more than one child" $template = "The '%s' class requires one child class at most who will extend her, but more than one child"
." class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?"; . " class was found:\n- %s\n\nWhy did you create more than one classes that extend '%s' class?";
$parentClassName = Reflection::getClassName($parentClass); $parentClassName = Reflection::getClassName($parentClass);
$message = sprintf($template, $parentClassName, implode("\n- ", $childClasses), $parentClassName); $message = sprintf($template, $parentClassName, implode("\n- ", $childClasses), $parentClassName);
parent::__construct($message); return new static($message);
} }
} }

View File

@@ -9,24 +9,26 @@
namespace Meritoo\Common\Exception\Regex; namespace Meritoo\Common\Exception\Regex;
/** /**
* An exception used while length of given hexadecimal value of color is incorrect. * An exception used while length of given hexadecimal value of color is incorrect
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class IncorrectColorHexLengthException extends \Exception class IncorrectColorHexLengthException extends \Exception
{ {
/** /**
* Class constructor. * Creates exception
* *
* @param string $color Incorrect hexadecimal value of color * @param string $color Incorrect hexadecimal value of color
* @return IncorrectColorHexLengthException
*/ */
public function __construct($color) public static function create($color)
{ {
$template = 'Length of hexadecimal value of color \'%s\' is incorrect. It\'s %d, but it should be 3 or 6.' $template = 'Length of hexadecimal value of color \'%s\' is incorrect. It\'s %d, but it should be 3 or 6.'
.' Is there everything ok?'; . ' Is there everything ok?';
$message = sprintf($template, $color, strlen($color)); $message = sprintf($template, $color, strlen($color));
parent::__construct($message);
return new static($message);
} }
} }

View File

@@ -9,21 +9,23 @@
namespace Meritoo\Common\Exception\Regex; namespace Meritoo\Common\Exception\Regex;
/** /**
* An exception used while given hexadecimal value of color is invalid. * An exception used while given hexadecimal value of color is invalid
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class InvalidColorHexValueException extends \Exception class InvalidColorHexValueException extends \Exception
{ {
/** /**
* Class constructor. * Creates exception
* *
* @param string $color Invalid hexadecimal value of color * @param string $color Invalid hexadecimal value of color
* @return InvalidColorHexValueException
*/ */
public function __construct($color) public static function create($color)
{ {
$message = sprintf('Hexadecimal value of color \'%s\' is invalid. Is there everything ok?', $color); $message = sprintf('Hexadecimal value of color \'%s\' is invalid. Is there everything ok?', $color);
parent::__construct($message);
return new static($message);
} }
} }

View File

@@ -0,0 +1,31 @@
<?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\Regex;
/**
* An exception used while html attributes are invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidHtmlAttributesException extends \Exception
{
/**
* Creates exception
*
* @param string $htmlAttributes Invalid html attributes
* @return InvalidHtmlAttributesException
*/
public static function create($htmlAttributes)
{
$message = sprintf('HTML attributes \'%s\' are invalid. Is there everything ok?', $htmlAttributes);
return new static($message);
}
}

View File

@@ -0,0 +1,31 @@
<?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\Regex;
/**
* An exception used while url is invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidUrlException extends \Exception
{
/**
* Creates exception
*
* @param string $url Invalid url
* @return InvalidUrlException
*/
public static function create($url)
{
$message = sprintf('Url \'%s\' is invalid. Is there everything ok?', $url);
return new static($message);
}
}

View File

@@ -0,0 +1,36 @@
<?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\Type;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Type\DatePartType;
/**
* An exception used while type of date part, e.g. "year", is unknown
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class UnknownDatePartTypeException extends UnknownTypeException
{
/**
* Creates exception
*
* @param string $unknownDatePart Unknown type of date part
* @param string $value Incorrect value
* @return UnknownDatePartTypeException
*/
public static function createException($unknownDatePart, $value)
{
/* @var UnknownDatePartTypeException $exception */
$exception = parent::create($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value));
return $exception;
}
}

View File

@@ -0,0 +1,35 @@
<?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\Type;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Type\OopVisibilityType;
/**
* An exception used while the visibility of a property, a method or (as of PHP 7.1.0) a constant is unknown
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class UnknownOopVisibilityTypeException extends UnknownTypeException
{
/**
* Creates exception
*
* @param string $unknownType Unknown visibility of a property, a method or (as of PHP 7.1.0) a constant
* @return UnknownOopVisibilityTypeException
*/
public static function createException($unknownType)
{
/* @var UnknownOopVisibilityTypeException $exception */
$exception = parent::create($unknownType, new OopVisibilityType(), 'OOP-related visibility');
return $exception;
}
}

View File

@@ -1,32 +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\Exception\Date;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Type\DatePartType;
/**
* An exception used while type of date part, e.g. "year", is unknown.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class UnknownDatePartTypeException extends UnknownTypeException
{
/**
* Class constructor.
*
* @param string $unknownDatePart Type of date part, e.g. "year". One of DatePartType class constants.
* @param string $value Incorrect value
*/
public function __construct($unknownDatePart, $value)
{
parent::__construct($unknownDatePart, new DatePartType(), sprintf('date part (with value %s)', $value));
}
}

View File

@@ -1,23 +0,0 @@
<?php
namespace Meritoo\Common\Exception\Regex;
/**
* An exception used while url is invalid.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class InvalidUrlException extends \Exception
{
/**
* Class constructor.
*
* @param string $url Invalid url
*/
public function __construct($url)
{
$message = sprintf('Url \'%s\' is invalid. Is there everything ok?', $url);
parent::__construct($message);
}
}

View File

@@ -1,23 +0,0 @@
<?php
namespace Meritoo\Common\Exception\Type;
use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Type\OopVisibilityType;
/**
* 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 UnknownOopVisibilityTypeException extends UnknownTypeException
{
/**
* {@inheritdoc}
*/
public function __construct($unknownType)
{
parent::__construct($unknownType, new OopVisibilityType(), 'OOP-related visibility');
}
}

View File

@@ -1,47 +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\Utilities;
/**
* Useful methods for bundle.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Bundle
{
/**
* Returns path to view / template of given bundle.
*
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template
*
* @return string|null
*/
public static function getBundleViewPath($viewPath, $bundleName, $extension = 'html.twig')
{
/*
* Unknown path, extension of the view / template or name of the bundle?
* Nothing to do
*/
if (empty($viewPath) || empty($bundleName) || empty($extension)) {
return null;
}
/*
* Path of the view / template doesn't end with given extension?
*/
if (!Regex::endsWith($viewPath, $extension)) {
$viewPath = sprintf('%s.%s', $viewPath, $extension);
}
return sprintf('%s:%s', $bundleName, $viewPath);
}
}

View File

@@ -1,822 +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\Utilities;
/**
* Useful methods for mime types of files.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class MimeTypes
{
/**
* Mime types data.
*
* @var array
*/
private static $mimeTypes = [
'7z' => 'application/x-7z-compressed',
'ez' => 'application/andrew-inset',
'atom' => 'application/atom+xml',
'atomcat' => 'application/atomcat+xml',
'atomsvc' => 'application/atomsvc+xml',
'ccxml' => 'application/ccxml+xml',
'davmount' => 'application/davmount+xml',
'ecma' => 'application/ecmascript',
'pfr' => 'application/font-tdpfr',
'stk' => 'application/hyperstudio',
'js' => 'application/javascript',
'json' => 'application/json',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'mrc' => 'application/marc',
'ma' => 'application/mathematica',
'nb' => 'application/mathematica',
'mb' => 'application/mathematica',
'mathml' => 'application/mathml+xml',
'mbox' => 'application/mbox',
'mscml' => 'application/mediaservercontrol+xml',
'mp4s' => 'application/mp4',
'dot' => 'application/msword',
'doc' => 'application/msword',
/*
* MS Office system file format MIME types
* http://technet.microsoft.com/en-us/library/ee309278%28office.12%29.aspx
*/
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'mxf' => 'application/mxf',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'class' => 'application/octet-stream',
'so' => 'application/octet-stream',
'iso' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'dist' => 'application/octet-stream',
'distz' => 'application/octet-stream',
'pkg' => 'application/octet-stream',
'bpk' => 'application/octet-stream',
'dump' => 'application/octet-stream',
'elc' => 'application/octet-stream',
'scpt' => 'application/octet-stream',
'oda' => 'application/oda',
'ogg' => 'application/ogg',
'pdf' => 'application/pdf',
'pgp' => 'application/pgp-encrypted',
'asc' => 'application/pgp-signature',
'sig' => 'application/pgp-signature',
'prf' => 'application/pics-rules',
'p10' => 'application/pkcs10',
'p7m' => 'application/pkcs7-mime',
'p7c' => 'application/pkcs7-mime',
'p7s' => 'application/pkcs7-signature',
'cer' => 'application/pkix-cert',
'crl' => 'application/pkix-crl',
'pkipath' => 'application/pkix-pkipath',
'pki' => 'application/pkixcmp',
'pls' => 'application/pls+xml',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'cww' => 'application/prs.cww',
'rdf' => 'application/rdf+xml',
'rif' => 'application/reginfo+xml',
'rnc' => 'application/relax-ng-compact-syntax',
'rl' => 'application/resource-lists+xml',
'rs' => 'application/rls-services+xml',
'rsd' => 'application/rsd+xml',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'sbml' => 'application/sbml+xml',
'sdp' => 'application/sdp',
'setpay' => 'application/set-payment-initiation',
'setreg' => 'application/set-registration-initiation',
'shf' => 'application/shf+xml',
'smi' => 'application/smil+xml',
'smil' => 'application/smil+xml',
'gram' => 'application/srgs',
'grxml' => 'application/srgs+xml',
'ssml' => 'application/ssml+xml',
'plb' => 'application/vnd.3gpp.pic-bw-large',
'psb' => 'application/vnd.3gpp.pic-bw-small',
'pvb' => 'application/vnd.3gpp.pic-bw-var',
'pwn' => 'application/vnd.3m.post-it-notes',
'aso' => 'application/vnd.accpac.simply.aso',
'imp' => 'application/vnd.accpac.simply.imp',
'acu' => 'application/vnd.acucobol',
'atc' => 'application/vnd.acucorp',
'acutc' => 'application/vnd.acucorp',
'xdp' => 'application/vnd.adobe.xdp+xml',
'xfdf' => 'application/vnd.adobe.xfdf',
'ami' => 'application/vnd.amiga.ami',
'cii' => 'application/vnd.anser-web-certificate-issue-initiation',
'fti' => 'application/vnd.anser-web-funds-transfer-initiation',
'atx' => 'application/vnd.antix.game-component',
'mpkg' => 'application/vnd.apple.installer+xml',
'aep' => 'application/vnd.audiograph',
'mpm' => 'application/vnd.blueice.multipass',
'bmi' => 'application/vnd.bmi',
'rep' => 'application/vnd.businessobjects',
'cdxml' => 'application/vnd.chemdraw+xml',
'mmd' => 'application/vnd.chipnuts.karaoke-mmd',
'cdy' => 'application/vnd.cinderella',
'cla' => 'application/vnd.claymore',
'c4g' => 'application/vnd.clonk.c4group',
'c4d' => 'application/vnd.clonk.c4group',
'c4f' => 'application/vnd.clonk.c4group',
'c4p' => 'application/vnd.clonk.c4group',
'c4u' => 'application/vnd.clonk.c4group',
'csp' => 'application/vnd.commonspace',
'cst' => 'application/vnd.commonspace',
'cdbcmsg' => 'application/vnd.contact.cmsg',
'cmc' => 'application/vnd.cosmocaller',
'clkx' => 'application/vnd.crick.clicker',
'clkk' => 'application/vnd.crick.clicker.keyboard',
'clkp' => 'application/vnd.crick.clicker.palette',
'clkt' => 'application/vnd.crick.clicker.template',
'clkw' => 'application/vnd.crick.clicker.wordbank',
'wbs' => 'application/vnd.criticaltools.wbs+xml',
'pml' => 'application/vnd.ctc-posml',
'ppd' => 'application/vnd.cups-ppd',
'curl' => 'application/vnd.curl',
'rdz' => 'application/vnd.data-vision.rdz',
'dna' => 'application/vnd.dna',
'mlp' => 'application/vnd.dolby.mlp',
'dpg' => 'application/vnd.dpgraph',
'dfac' => 'application/vnd.dreamfactory',
'mag' => 'application/vnd.ecowin.chart',
'nml' => 'application/vnd.enliven',
'esf' => 'application/vnd.epson.esf',
'msf' => 'application/vnd.epson.msf',
'qam' => 'application/vnd.epson.quickanime',
'slt' => 'application/vnd.epson.salt',
'ssf' => 'application/vnd.epson.ssf',
'es3' => 'application/vnd.eszigno3+xml',
'et3' => 'application/vnd.eszigno3+xml',
'ez2' => 'application/vnd.ezpix-album',
'ez3' => 'application/vnd.ezpix-package',
'fdf' => 'application/vnd.fdf',
'gph' => 'application/vnd.flographit',
'ftc' => 'application/vnd.fluxtime.clip',
'fm' => 'application/vnd.framemaker',
'frame' => 'application/vnd.framemaker',
'maker' => 'application/vnd.framemaker',
'fnc' => 'application/vnd.frogans.fnc',
'ltf' => 'application/vnd.frogans.ltf',
'fsc' => 'application/vnd.fsc.weblaunch',
'oas' => 'application/vnd.fujitsu.oasys',
'oa2' => 'application/vnd.fujitsu.oasys2',
'oa3' => 'application/vnd.fujitsu.oasys3',
'fg5' => 'application/vnd.fujitsu.oasysgp',
'bh2' => 'application/vnd.fujitsu.oasysprs',
'ddd' => 'application/vnd.fujixerox.ddd',
'xdw' => 'application/vnd.fujixerox.docuworks',
'xbd' => 'application/vnd.fujixerox.docuworks.binder',
'fzs' => 'application/vnd.fuzzysheet',
'txd' => 'application/vnd.genomatix.tuxedo',
'kml' => 'application/vnd.google-earth.kml+xml',
'kmz' => 'application/vnd.google-earth.kmz',
'gqf' => 'application/vnd.grafeq',
'gqs' => 'application/vnd.grafeq',
'gac' => 'application/vnd.groove-account',
'ghf' => 'application/vnd.groove-help',
'gim' => 'application/vnd.groove-identity-message',
'grv' => 'application/vnd.groove-injector',
'gtm' => 'application/vnd.groove-tool-message',
'tpl' => 'application/vnd.groove-tool-template',
'vcg' => 'application/vnd.groove-vcard',
'zmm' => 'application/vnd.handheld-entertainment+xml',
'hbci' => 'application/vnd.hbci',
'les' => 'application/vnd.hhe.lesson-player',
'hpgl' => 'application/vnd.hp-hpgl',
'hpid' => 'application/vnd.hp-hpid',
'hps' => 'application/vnd.hp-hps',
'jlt' => 'application/vnd.hp-jlyt',
'pcl' => 'application/vnd.hp-pcl',
'pclxl' => 'application/vnd.hp-pclxl',
'x3d' => 'application/vnd.hzn-3d-crossword',
'mpy' => 'application/vnd.ibm.minipay',
'afp' => 'application/vnd.ibm.modcap',
'listafp' => 'application/vnd.ibm.modcap',
'list3820' => 'application/vnd.ibm.modcap',
'irm' => 'application/vnd.ibm.rights-management',
'sc' => 'application/vnd.ibm.secure-container',
'igl' => 'application/vnd.igloader',
'ivp' => 'application/vnd.immervision-ivp',
'ivu' => 'application/vnd.immervision-ivu',
'xpw' => 'application/vnd.intercon.formnet',
'xpx' => 'application/vnd.intercon.formnet',
'qbo' => 'application/vnd.intu.qbo',
'qfx' => 'application/vnd.intu.qfx',
'rcprofile' => 'application/vnd.ipunplugged.rcprofile',
'irp' => 'application/vnd.irepository.package+xml',
'xpr' => 'application/vnd.is-xpr',
'jam' => 'application/vnd.jam',
'rms' => 'application/vnd.jcp.javame.midlet-rms',
'jisp' => 'application/vnd.jisp',
'ktz' => 'application/vnd.kahootz',
'ktr' => 'application/vnd.kahootz',
'karbon' => 'application/vnd.kde.karbon',
'chrt' => 'application/vnd.kde.kchart',
'kfo' => 'application/vnd.kde.kformula',
'flw' => 'application/vnd.kde.kivio',
'kon' => 'application/vnd.kde.kontour',
'kpr' => 'application/vnd.kde.kpresenter',
'kpt' => 'application/vnd.kde.kpresenter',
'ksp' => 'application/vnd.kde.kspread',
'kwd' => 'application/vnd.kde.kword',
'kwt' => 'application/vnd.kde.kword',
'htke' => 'application/vnd.kenameaapp',
'kia' => 'application/vnd.kidspiration',
'kne' => 'application/vnd.kinar',
'knp' => 'application/vnd.kinar',
'skp' => 'application/vnd.koan',
'skd' => 'application/vnd.koan',
'skt' => 'application/vnd.koan',
'skm' => 'application/vnd.koan',
'lbd' => 'application/vnd.llamagraphics.life-balance.desktop',
'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml',
'123' => 'application/vnd.lotus-1-2-3',
'apr' => 'application/vnd.lotus-approach',
'pre' => 'application/vnd.lotus-freelance',
'nsf' => 'application/vnd.lotus-notes',
'org' => 'application/vnd.lotus-organizer',
'scm' => 'application/vnd.lotus-screencam',
'lwp' => 'application/vnd.lotus-wordpro',
'portpkg' => 'application/vnd.macports.portpkg',
'mcd' => 'application/vnd.mcd',
'mc1' => 'application/vnd.medcalcdata',
'cdkey' => 'application/vnd.mediastation.cdkey',
'mwf' => 'application/vnd.mfer',
'mfm' => 'application/vnd.mfmp',
'flo' => 'application/vnd.micrografx.flo',
'igx' => 'application/vnd.micrografx.igx',
'mif' => 'application/vnd.mif',
'daf' => 'application/vnd.mobius.daf',
'dis' => 'application/vnd.mobius.dis',
'mbk' => 'application/vnd.mobius.mbk',
'mqy' => 'application/vnd.mobius.mqy',
'msl' => 'application/vnd.mobius.msl',
'plc' => 'application/vnd.mobius.plc',
'txf' => 'application/vnd.mobius.txf',
'mpn' => 'application/vnd.mophun.application',
'mpc' => 'application/vnd.mophun.certificate',
'xul' => 'application/vnd.mozilla.xul+xml',
'cil' => 'application/vnd.ms-artgalry',
'asf' => 'application/vnd.ms-asf',
'cab' => 'application/vnd.ms-cab-compressed',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlm' => 'application/vnd.ms-excel',
'xla' => 'application/vnd.ms-excel',
'xlc' => 'application/vnd.ms-excel',
'xlt' => 'application/vnd.ms-excel',
'xlw' => 'application/vnd.ms-excel',
'eot' => 'application/vnd.ms-fontobject',
'chm' => 'application/vnd.ms-htmlhelp',
'ims' => 'application/vnd.ms-ims',
'lrm' => 'application/vnd.ms-lrm',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pps' => 'application/vnd.ms-powerpoint',
'pot' => 'application/vnd.ms-powerpoint',
'mpp' => 'application/vnd.ms-project',
'mpt' => 'application/vnd.ms-project',
'wps' => 'application/vnd.ms-works',
'wks' => 'application/vnd.ms-works',
'wcm' => 'application/vnd.ms-works',
'wdb' => 'application/vnd.ms-works',
'wpl' => 'application/vnd.ms-wpl',
'xps' => 'application/vnd.ms-xpsdocument',
'mseq' => 'application/vnd.mseq',
'mus' => 'application/vnd.musician',
'nlu' => 'application/vnd.neurolanguage.nlu',
'nnd' => 'application/vnd.noblenet-directory',
'nns' => 'application/vnd.noblenet-sealer',
'nnw' => 'application/vnd.noblenet-web',
'ngdat' => 'application/vnd.nokia.n-gage.data',
'n-gage' => 'application/vnd.nokia.n-gage.symbian.install',
'rpst' => 'application/vnd.nokia.radio-preset',
'rpss' => 'application/vnd.nokia.radio-presets',
'edm' => 'application/vnd.novadigm.edm',
'edx' => 'application/vnd.novadigm.edx',
'ext' => 'application/vnd.novadigm.ext',
'odc' => 'application/vnd.oasis.opendocument.chart',
'otc' => 'application/vnd.oasis.opendocument.chart-template',
'odf' => 'application/vnd.oasis.opendocument.formula',
'otf' => 'application/vnd.oasis.opendocument.formula-template',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'oti' => 'application/vnd.oasis.opendocument.image-template',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'otm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'xo' => 'application/vnd.olpc-sugar',
'dd2' => 'application/vnd.oma.dd2+xml',
'oxt' => 'application/vnd.openofficeorg.extension',
'dp' => 'application/vnd.osgi.dp',
'prc' => 'application/vnd.palm',
'pdb' => 'application/vnd.palm',
'pqa' => 'application/vnd.palm',
'oprc' => 'application/vnd.palm',
'str' => 'application/vnd.pg.format',
'ei6' => 'application/vnd.pg.osasli',
'efif' => 'application/vnd.picsel',
'plf' => 'application/vnd.pocketlearn',
'pbd' => 'application/vnd.powerbuilder6',
'box' => 'application/vnd.previewsystems.box',
'mgz' => 'application/vnd.proteus.magazine',
'qps' => 'application/vnd.publishare-delta-tree',
'ptid' => 'application/vnd.pvi.ptid1',
'qxd' => 'application/vnd.quark.quarkxpress',
'qxt' => 'application/vnd.quark.quarkxpress',
'qwd' => 'application/vnd.quark.quarkxpress',
'qwt' => 'application/vnd.quark.quarkxpress',
'qxl' => 'application/vnd.quark.quarkxpress',
'qxb' => 'application/vnd.quark.quarkxpress',
'mxl' => 'application/vnd.recordare.musicxml',
'rm' => 'application/vnd.rn-realmedia',
'see' => 'application/vnd.seemail',
'sema' => 'application/vnd.sema',
'semd' => 'application/vnd.semd',
'semf' => 'application/vnd.semf',
'ifm' => 'application/vnd.shana.informed.formdata',
'itp' => 'application/vnd.shana.informed.formtemplate',
'iif' => 'application/vnd.shana.informed.interchange',
'ipk' => 'application/vnd.shana.informed.package',
'twd' => 'application/vnd.simtech-mindmapper',
'twds' => 'application/vnd.simtech-mindmapper',
'mmf' => 'application/vnd.smaf',
'sdkm' => 'application/vnd.solent.sdkm+xml',
'sdkd' => 'application/vnd.solent.sdkm+xml',
'dxp' => 'application/vnd.spotfire.dxp',
'sfs' => 'application/vnd.spotfire.sfs',
'sus' => 'application/vnd.sus-calendar',
'susp' => 'application/vnd.sus-calendar',
'svd' => 'application/vnd.svd',
'xsm' => 'application/vnd.syncml+xml',
'bdm' => 'application/vnd.syncml.dm+wbxml',
'xdm' => 'application/vnd.syncml.dm+xml',
'tao' => 'application/vnd.tao.intent-module-archive',
'tmo' => 'application/vnd.tmobile-livetv',
'tpt' => 'application/vnd.trid.tpt',
'mxs' => 'application/vnd.triscape.mxs',
'tra' => 'application/vnd.trueapp',
'ufd' => 'application/vnd.ufdl',
'ufdl' => 'application/vnd.ufdl',
'utz' => 'application/vnd.uiq.theme',
'umj' => 'application/vnd.umajin',
'unityweb' => 'application/vnd.unity',
'uoml' => 'application/vnd.uoml+xml',
'vcx' => 'application/vnd.vcx',
'vsd' => 'application/vnd.visio',
'vst' => 'application/vnd.visio',
'vss' => 'application/vnd.visio',
'vsw' => 'application/vnd.visio',
'vis' => 'application/vnd.visionary',
'vsf' => 'application/vnd.vsf',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'wtb' => 'application/vnd.webturbo',
'wpd' => 'application/vnd.wordperfect',
'wqd' => 'application/vnd.wqd',
'stf' => 'application/vnd.wt.stf',
'xar' => 'application/vnd.xara',
'xfdl' => 'application/vnd.xfdl',
'hvd' => 'application/vnd.yamaha.hv-dic',
'hvs' => 'application/vnd.yamaha.hv-script',
'hvp' => 'application/vnd.yamaha.hv-voice',
'saf' => 'application/vnd.yamaha.smaf-audio',
'spf' => 'application/vnd.yamaha.smaf-phrase',
'cmp' => 'application/vnd.yellowriver-custom-menu',
'zaz' => 'application/vnd.zzazz.deck+xml',
'vxml' => 'application/voicexml+xml',
'hlp' => 'application/winhlp',
'wsdl' => 'application/wsdl+xml',
'wspolicy' => 'application/wspolicy+xml',
'ace' => 'application/x-ace-compressed',
'bcpio' => 'application/x-bcpio',
'torrent' => 'application/x-bittorrent',
'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2',
'boz' => 'application/x-bzip2',
'vcd' => 'application/x-cdlink',
'chat' => 'application/x-chat',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'fgd' => 'application/x-director',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'jnlp' => 'application/x-java-jnlp-file',
'latex' => 'application/x-latex',
'wmd' => 'application/x-ms-wmd',
'wmz' => 'application/x-ms-wmz',
'mdb' => 'application/x-msaccess',
'obd' => 'application/x-msbinder',
'crd' => 'application/x-mscardfile',
'clp' => 'application/x-msclip',
'exe' => 'application/x-msdownload',
'dll' => 'application/x-msdownload',
'com' => 'application/x-msdownload',
'bat' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'mvb' => 'application/x-msmediaview',
'm13' => 'application/x-msmediaview',
'm14' => 'application/x-msmediaview',
'wmf' => 'application/x-msmetafile',
'mny' => 'application/x-msmoney',
'pub' => 'application/x-mspublisher',
'scd' => 'application/x-msschedule',
'trm' => 'application/x-msterminal',
'wri' => 'application/x-mswrite',
'nc' => 'application/x-netcdf',
'cdf' => 'application/x-netcdf',
'p12' => 'application/x-pkcs12',
'pfx' => 'application/x-pkcs12',
'p7b' => 'application/x-pkcs7-certificates',
'spc' => 'application/x-pkcs7-certificates',
'p7r' => 'application/x-pkcs7-certreqresp',
'rar' => 'application/x-rar-compressed',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sitx' => 'application/x-stuffitx',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texinfo' => 'application/x-texinfo',
'texi' => 'application/x-texinfo',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'der' => 'application/x-x509-ca-cert',
'crt' => 'application/x-x509-ca-cert',
'xenc' => 'application/xenc+xml',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'dtd' => 'application/xml-dtd',
'xop' => 'application/xop+xml',
'xslt' => 'application/xslt+xml',
'xspf' => 'application/xspf+xml',
'mxml' => 'application/xv+xml',
'xhvml' => 'application/xv+xml',
'xvml' => 'application/xv+xml',
'xvm' => 'application/xv+xml',
'zip' => 'application/zip',
'au' => 'audio/basic',
'snd' => 'audio/basic',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'kar' => 'audio/midi',
'rmi' => 'audio/midi',
'mp4a' => 'audio/mp4',
'm4a' => 'audio/mp4a-latm',
'm4p' => 'audio/mp4a-latm',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp2a' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'm2a' => 'audio/mpeg',
'm3a' => 'audio/mpeg',
'eol' => 'audio/vnd.digital-winds',
'lvp' => 'audio/vnd.lucent.voice',
'ecelp4800' => 'audio/vnd.nuera.ecelp4800',
'ecelp7470' => 'audio/vnd.nuera.ecelp7470',
'ecelp9600' => 'audio/vnd.nuera.ecelp9600',
'wav' => 'audio/wav',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'm3u' => 'audio/x-mpegurl',
'wax' => 'audio/x-ms-wax',
'wma' => 'audio/x-ms-wma',
'ram' => 'audio/x-pn-realaudio',
'ra' => 'audio/x-pn-realaudio',
'rmp' => 'audio/x-pn-realaudio-plugin',
'cdx' => 'chemical/x-cdx',
'cif' => 'chemical/x-cif',
'cmdf' => 'chemical/x-cmdf',
'cml' => 'chemical/x-cml',
'csml' => 'chemical/x-csml',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'cgm' => 'image/cgm',
'g3' => 'image/g3fax',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jp2' => 'image/jp2',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'pict' => 'image/pict',
'pic' => 'image/pict',
'pct' => 'image/pict',
'png' => 'image/png',
'btif' => 'image/prs.btif',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'psd' => 'image/vnd.adobe.photoshop',
'djvu' => 'image/vnd.djvu',
'djv' => 'image/vnd.djvu',
'dwg' => 'image/vnd.dwg',
'dxf' => 'image/vnd.dxf',
'fbs' => 'image/vnd.fastbidsheet',
'fpx' => 'image/vnd.fpx',
'fst' => 'image/vnd.fst',
'mmr' => 'image/vnd.fujixerox.edmics-mmr',
'rlc' => 'image/vnd.fujixerox.edmics-rlc',
'ico' => 'image/vnd.microsoft.icon',
'mdi' => 'image/vnd.ms-modi',
'npx' => 'image/vnd.net-fpx',
'wbmp' => 'image/vnd.wap.wbmp',
'xif' => 'image/vnd.xiff',
'ras' => 'image/x-cmu-raster',
'cmx' => 'image/x-cmx',
'pntg' => 'image/x-macpaint',
'pnt' => 'image/x-macpaint',
'mac' => 'image/x-macpaint',
'pcx' => 'image/x-pcx',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'qtif' => 'image/x-quicktime',
'qti' => 'image/x-quicktime',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'eml' => 'message/rfc822',
'mime' => 'message/rfc822',
'igs' => 'model/iges',
'iges' => 'model/iges',
'msh' => 'model/mesh',
'mesh' => 'model/mesh',
'silo' => 'model/mesh',
'dwf' => 'model/vnd.dwf',
'gdl' => 'model/vnd.gdl',
'gtw' => 'model/vnd.gtw',
'mts' => 'model/vnd.mts',
'vtu' => 'model/vnd.vtu',
'wrl' => 'model/vrml',
'vrml' => 'model/vrml',
'ics' => 'text/calendar',
'ifb' => 'text/calendar',
'css' => 'text/css',
'csv' => 'text/csv',
'html' => 'text/html',
'htm' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'conf' => 'text/plain',
'def' => 'text/plain',
'list' => 'text/plain',
'log' => 'text/plain',
'in' => 'text/plain',
'dsc' => 'text/prs.lines.tag',
'rtx' => 'text/richtext',
'sgml' => 'text/sgml',
'sgm' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
't' => 'text/troff',
'tr' => 'text/troff',
'roff' => 'text/troff',
'man' => 'text/troff',
'me' => 'text/troff',
'ms' => 'text/troff',
'uri' => 'text/uri-list',
'uris' => 'text/uri-list',
'urls' => 'text/uri-list',
'fly' => 'text/vnd.fly',
'flx' => 'text/vnd.fmi.flexstor',
'3dml' => 'text/vnd.in3d.3dml',
'spot' => 'text/vnd.in3d.spot',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
's' => 'text/x-asm',
'asm' => 'text/x-asm',
'c' => 'text/x-c',
'cc' => 'text/x-c',
'cxx' => 'text/x-c',
'cpp' => 'text/x-c',
'h' => 'text/x-c',
'hh' => 'text/x-c',
'dic' => 'text/x-c',
'f' => 'text/x-fortran',
'for' => 'text/x-fortran',
'f77' => 'text/x-fortran',
'f90' => 'text/x-fortran',
'p' => 'text/x-pascal',
'pas' => 'text/x-pascal',
'java' => 'text/x-java-source',
'etx' => 'text/x-setext',
'uu' => 'text/x-uuencode',
'vcs' => 'text/x-vcalendar',
'vcf' => 'text/x-vcard',
'3gp' => 'video/3gpp',
'3g2' => 'video/3gpp2',
'h261' => 'video/h261',
'h263' => 'video/h263',
'h264' => 'video/h264',
'jpgv' => 'video/jpeg',
'jpm' => 'video/jpm',
'jpgm' => 'video/jpm',
'mj2' => 'video/mj2',
'mjp2' => 'video/mj2',
'mp4' => 'video/mp4',
'mp4v' => 'video/mp4',
'mpg4' => 'video/mp4',
'm4v' => 'video/mp4',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'm1v' => 'video/mpeg',
'm2v' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'fvt' => 'video/vnd.fvt',
'mxu' => 'video/vnd.mpegurl',
'm4u' => 'video/vnd.mpegurl',
'viv' => 'video/vnd.vivo',
'dv' => 'video/x-dv',
'dif' => 'video/x-dv',
'fli' => 'video/x-fli',
'asx' => 'video/x-ms-asf',
'wm' => 'video/x-ms-wm',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wvx' => 'video/x-ms-wvx',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
];
/**
* Returns extensions for given mimes types.
*
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param bool $asUpperCase (optional) If is set to true, extensions are returned as upper case. Otherwise - lower
* case.
*
* @return array
*/
public static function getExtensions(array $mimesTypes, $asUpperCase = false)
{
if (empty($mimesTypes)) {
return [];
}
$extensions = [];
foreach ($mimesTypes as $mimeType) {
$extension = self::getExtension($mimeType);
/*
* No extension for given mime type?
* Nothing to do
*/
if (empty($extension)) {
continue;
}
/*
* Extensions should be returned as upper case?
*/
if ($asUpperCase) {
if (is_array($extension)) {
array_walk($extension, function (&$value) {
$value = strtoupper($value);
});
} else {
$extension = strtoupper($extension);
}
}
$extensions[$mimeType] = $extension;
}
return $extensions;
}
/**
* Returns extension for given mime type.
*
* @param string $mimeType The mime type, e.g. "video/mpeg"
*
* @return string|array
*/
public static function getExtension($mimeType)
{
if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes)) {
$data = Arrays::setKeysAsValues(self::$mimeTypes, false);
return $data[$mimeType];
}
return '';
}
/**
* Returns information whether file with the given path is an image.
*
* @param string $path Path of the file to check
*
* @return bool
*/
public static function isImagePath($path)
{
$mimeType = self::getMimeType($path);
return self::isImage($mimeType);
}
/**
* Returns mime type of given file.
*
* @param string $filePath Path of the file to check
*
* @return string
*
* @throws \RuntimeException
*/
public static function getMimeType($filePath)
{
/*
* The file does not exist?
* Nothing to do
*/
if (!is_string($filePath) || !is_readable($filePath)) {
return '';
}
/*
* 1st possibility: the finfo class
*/
if (class_exists('finfo')) {
$finfo = new \finfo();
return $finfo->file($filePath, FILEINFO_MIME_TYPE);
}
/*
* 2nd possibility: the mime_content_type function
*/
if (function_exists('mime_content_type')) {
return mime_content_type($filePath);
}
/*
* Oops, there is no possibility to read the mime type
*/
$template = 'Neither \'finfo\' class nor \'mime_content_type\' function exists. There is no way to read the'
.' mime type of file \'%s\'.';
$message = sprintf($template, $filePath);
throw new \RuntimeException($message);
}
/**
* Returns information whether the given file type is an image.
*
* @param string $mimeType The mime type of file
*
* @return bool
*/
public static function isImage($mimeType)
{
if (in_array($mimeType, self::$mimeTypes)) {
return (bool) preg_match('|^image/.+$|', $mimeType);
}
return false;
}
}

View File

@@ -1,111 +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\Utilities;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
/**
* Useful methods for repository.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class Repository
{
/**
* Replenishes positions of given items.
*
* @param array $items The items
* @param bool $asLast (optional) If is set to true, items are placed at the end. Otherwise - at the top.
* @param bool $force (optional) If is set to true, positions are set even there is no extreme position.
* Otherwise - if extreme position is not found (is null) replenishment is stopped / skipped.
*/
public static function replenishPositions($items, $asLast = true, $force = false)
{
$position = self::getExtremePosition($items, $asLast);
if ($position === null && $force) {
$position = 0;
}
if ($position !== null && !empty($items)) {
foreach ($items as $item) {
if (method_exists($item, 'getPosition')) {
if ($item->getPosition() === null) {
if ($asLast) {
++$position;
} else {
--$position;
}
if (method_exists($item, 'setPosition')) {
$item->setPosition($position);
}
}
}
}
}
}
/**
* Returns extreme position (max or min) of given items.
*
* @param array $items The items
* @param bool $max (optional) If is set to true, maximum value is returned. Otherwise - minimum.
*
* @return int
*/
public static function getExtremePosition($items, $max = true)
{
$extreme = null;
if (!empty($items)) {
foreach ($items as $item) {
if (Reflection::hasMethod($item, 'getPosition')) {
$position = $item->getPosition();
if ($max) {
if ($position > $extreme) {
$extreme = $position;
}
} else {
if ($position < $extreme) {
$extreme = $position;
}
}
}
}
}
return $extreme;
}
/**
* Returns query builder for given entity's repository.
* The entity should contain given property, e.g. "name".
*
* @param EntityRepository $repository Repository of the entity
* @param string $property (optional) Name of property used by the ORDER BY clause
* @param string $direction (optional) Direction used by the ORDER BY clause ("ASC" or "DESC")
*
* @return QueryBuilder
*/
public static function getEntityOrderedQueryBuilder(
EntityRepository $repository,
$property = 'name',
$direction = 'ASC'
) {
$alias = 'qb';
return $repository
->createQueryBuilder($alias)
->orderBy(sprintf('%s.%s', $alias, $property), $direction);
}
}

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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
abstract class BaseTypeTestCase extends BaseTestCase
{
use BaseTypeTestCaseTrait;
}

View File

@@ -6,26 +6,36 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Meritoo\Common\Test\Base; namespace Meritoo\Common\Traits\Test\Base;
use DateTime; use DateTime;
use Generator; use Generator;
use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException; use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use PHPUnit_Framework_TestCase; use Meritoo\Common\Utilities\Miscellaneous;
use ReflectionClass; use ReflectionClass;
use ReflectionException;
use ReflectionMethod; use ReflectionMethod;
use stdClass;
/** /**
* Base test case with common methods and data providers. * BaseTestCaseTrait
* Created on 2017-11-02
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
abstract class BaseTestCase extends PHPUnit_Framework_TestCase trait BaseTestCaseTrait
{ {
/** /**
* Provides an empty value. * Path of directory with data used by test cases
*
* @var string
*/
private static $testsDataDirPath = 'data/tests';
/**
* Provides an empty value
* *
* @return Generator * @return Generator
*/ */
@@ -40,7 +50,7 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
} }
/** /**
* Provides boolean value. * Provides boolean value
* *
* @return Generator * @return Generator
*/ */
@@ -51,7 +61,7 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
} }
/** /**
* Provides instance of DateTime class. * Provides instance of DateTime class
* *
* @return Generator * @return Generator
*/ */
@@ -64,7 +74,7 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
} }
/** /**
* Provides relative / compound format of DateTime. * Provides relative / compound format of DateTime
* *
* @return Generator * @return Generator
*/ */
@@ -84,7 +94,7 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
} }
/** /**
* Provides path of not existing file, e.g. "lorem/ipsum.jpg". * Provides path of not existing file, e.g. "lorem/ipsum.jpg"
* *
* @return Generator * @return Generator
*/ */
@@ -95,26 +105,50 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
yield['surprise/me/one/more/time.txt']; yield['surprise/me/one/more/time.txt'];
} }
/**
* Provides non scalar value, e.g. [] or null
*
* @return Generator
*/
public function provideNonScalarValue()
{
yield[
[],
];
yield[
null,
];
yield[
new stdClass(),
];
}
/** /**
* Returns path of file used by tests. * 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 $fileName Name of file
* @param string $directoryPath (optional) Path of directory containing the file * @param string $directoryPath (optional) Path of directory containing the file
*
* @return string * @return string
*/ */
public function getFilePathToTests($fileName, $directoryPath = '') public function getFilePathForTesting($fileName, $directoryPath = '')
{ {
if (!empty($directoryPath)) { $rootPath = Miscellaneous::getProjectRootPath();
$directoryPath = '/'.$directoryPath;
}
return sprintf('%s/../../../../../data/tests/%s%s', __DIR__, $fileName, $directoryPath); $paths = [
$rootPath,
self::$testsDataDirPath,
$directoryPath,
$fileName,
];
return Miscellaneous::concatenatePaths($paths);
} }
/** /**
* Verifies visibility and arguments of method. * Verifies visibility and arguments of method
* *
* @param string $classNamespace Namespace of class that contains method to verify * @param string $classNamespace Namespace of class that contains method to verify
* @param string|ReflectionMethod $method Name of method or just the method to verify * @param string|ReflectionMethod $method Name of method or just the method to verify
@@ -124,14 +158,14 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
* verified method * verified method
* @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments
* of the verified method * of the verified method
*
* @throws UnknownOopVisibilityTypeException * @throws UnknownOopVisibilityTypeException
* @throws ReflectionException
* *
* Attention. 2nd argument, the $method, may be: * Attention. 2nd argument, the $method, may be:
* - string - name of the method * - string - name of the method
* - instance of ReflectionMethod - just the method (provided by ReflectionClass::getMethod() method) * - instance of ReflectionMethod - just the method (provided by ReflectionClass::getMethod() method)
*/ */
protected function verifyMethodVisibilityAndArguments( protected static function assertMethodVisibilityAndArguments(
$classNamespace, $classNamespace,
$method, $method,
$visibilityType, $visibilityType,
@@ -158,17 +192,14 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
switch ($visibilityType) { switch ($visibilityType) {
case OopVisibilityType::IS_PUBLIC: case OopVisibilityType::IS_PUBLIC:
static::assertTrue($method->isPublic()); static::assertTrue($method->isPublic());
break; break;
case OopVisibilityType::IS_PROTECTED: case OopVisibilityType::IS_PROTECTED:
static::assertTrue($method->isProtected()); static::assertTrue($method->isProtected());
break; break;
case OopVisibilityType::IS_PRIVATE: case OopVisibilityType::IS_PRIVATE:
static::assertTrue($method->isPrivate()); static::assertTrue($method->isPrivate());
break; break;
} }
@@ -177,18 +208,18 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
} }
/** /**
* Verifies visibility and arguments of class constructor. * 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 * @param string $visibilityType Expected visibility of verified method. One of OopVisibilityType class
* constants. * constants.
* @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method * @param int $argumentsCount (optional) Expected count/amount of arguments of the verified method
* @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments of the verified * @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments of the verified
* method * method
* * @throws ReflectionException
* @throws UnknownOopVisibilityTypeException * @throws UnknownOopVisibilityTypeException
*/ */
protected function verifyConstructorVisibilityAndArguments( protected static function assertConstructorVisibilityAndArguments(
$classNamespace, $classNamespace,
$visibilityType, $visibilityType,
$argumentsCount = 0, $argumentsCount = 0,
@@ -200,6 +231,33 @@ abstract class BaseTestCase extends PHPUnit_Framework_TestCase
$reflection = new ReflectionClass($classNamespace); $reflection = new ReflectionClass($classNamespace);
$method = $reflection->getConstructor(); $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
* @throws ReflectionException
*/
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,20 +1,26 @@
<?php <?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 Generator;
use Meritoo\Common\Type\Base\BaseType; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
abstract class BaseTypeTestCase extends BaseTestCase trait BaseTypeTestCaseTrait
{ {
/** /**
* Verifies availability of all types. * Verifies availability of all types
*/ */
public function testAvailabilityOfAllTypes() public function testAvailabilityOfAllTypes()
{ {
@@ -25,7 +31,7 @@ abstract class BaseTypeTestCase extends BaseTestCase
} }
/** /**
* Verifies whether given type is correct or not. * Verifies whether given type is correct or not
* *
* @param string $type Type to verify * @param string $type Type to verify
* @param bool $expected Information if given type is correct or not * @param bool $expected Information if given type is correct or not
@@ -38,21 +44,21 @@ abstract class BaseTypeTestCase extends BaseTestCase
} }
/** /**
* Provides type to verify and information if it's correct. * Provides type to verify and information if it's correct
* *
* @return Generator * @return Generator
*/ */
abstract public function provideTypeToVerify(); abstract public function provideTypeToVerify();
/** /**
* Returns instance of the tested type. * Returns instance of the tested type
* *
* @return BaseType * @return BaseType
*/ */
abstract protected function getTestedTypeInstance(); abstract protected function getTestedTypeInstance();
/** /**
* Returns all expected types of the tested type. * Returns all expected types of the tested type
* *
* @return array * @return array
*/ */

View File

@@ -14,26 +14,26 @@ use Meritoo\Common\Utilities\Reflection;
* Base / abstract type of something, e.g. type of button, order, date etc. * Base / abstract type of something, e.g. type of button, order, date etc.
* Child class should contain constants - each of them represent one type. * Child class should contain constants - each of them represent one type.
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
abstract class BaseType abstract class BaseType
{ {
/** /**
* All types. * All types
* *
* @var array * @var array
*/ */
private $all; private $all;
/** /**
* Returns all types. * Returns all types
* *
* @return array * @return array
*/ */
public function getAll() public function getAll()
{ {
if ($this->all === null) { if (null === $this->all) {
$this->all = Reflection::getConstants($this); $this->all = Reflection::getConstants($this);
} }
@@ -41,10 +41,9 @@ abstract class BaseType
} }
/** /**
* Returns information if given type is correct. * Returns information if given type is correct
* *
* @param string $type The type to check * @param string $type The type to check
*
* @return bool * @return bool
*/ */
public function isCorrectType($type) public function isCorrectType($type)

View File

@@ -11,50 +11,50 @@ namespace Meritoo\Common\Type;
use Meritoo\Common\Type\Base\BaseType; use Meritoo\Common\Type\Base\BaseType;
/** /**
* Type of date part, e.g. "year". * Type of date part, e.g. "year"
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class DatePartType extends BaseType class DatePartType extends BaseType
{ {
/** /**
* The "day" date part. * The "day" date part
* *
* @var string * @var string
*/ */
const DAY = 'day'; const DAY = 'day';
/** /**
* The "hour" date part. * The "hour" date part
* *
* @var string * @var string
*/ */
const HOUR = 'hour'; const HOUR = 'hour';
/** /**
* The "minute" date part. * The "minute" date part
* *
* @var string * @var string
*/ */
const MINUTE = 'minute'; const MINUTE = 'minute';
/** /**
* The "month" date part. * The "month" date part
* *
* @var string * @var string
*/ */
const MONTH = 'month'; const MONTH = 'month';
/** /**
* The "second" date part. * The "second" date part
* *
* @var string * @var string
*/ */
const SECOND = 'second'; const SECOND = 'second';
/** /**
* The "year" date part. * The "year" date part
* *
* @var string * @var string
*/ */

View File

@@ -6,98 +6,100 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Type;
use DateTime; use DateTime;
use Meritoo\Common\Type\Base\BaseType;
use Meritoo\Common\Utilities\Date;
/** /**
* A date's period. * A date's period.
* Contains start and end date of the period. * Contains start and end date of the period.
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class DatePeriod class DatePeriod extends BaseType
{ {
/** /**
* The period constant: last month. * The period constant: last month
* *
* @var int * @var int
*/ */
const LAST_MONTH = 4; const LAST_MONTH = 4;
/** /**
* The period constant: last week. * The period constant: last week
* *
* @var int * @var int
*/ */
const LAST_WEEK = 1; const LAST_WEEK = 1;
/** /**
* The period constant: last year. * The period constant: last year
* *
* @var int * @var int
*/ */
const LAST_YEAR = 7; const LAST_YEAR = 7;
/** /**
* The period constant: next month. * The period constant: next month
* *
* @var int * @var int
*/ */
const NEXT_MONTH = 6; const NEXT_MONTH = 6;
/** /**
* The period constant: next week. * The period constant: next week
* *
* @var int * @var int
*/ */
const NEXT_WEEK = 3; const NEXT_WEEK = 3;
/** /**
* The period constant: next year. * The period constant: next year
* *
* @var int * @var int
*/ */
const NEXT_YEAR = 9; const NEXT_YEAR = 9;
/** /**
* The period constant: this month. * The period constant: this month
* *
* @var int * @var int
*/ */
const THIS_MONTH = 5; const THIS_MONTH = 5;
/** /**
* The period constant: this week. * The period constant: this week
* *
* @var int * @var int
*/ */
const THIS_WEEK = 2; const THIS_WEEK = 2;
/** /**
* The period constant: this year. * The period constant: this year
* *
* @var int * @var int
*/ */
const THIS_YEAR = 8; const THIS_YEAR = 8;
/** /**
* The start date of period. * The start date of period
* *
* @var DateTime * @var DateTime
*/ */
private $startDate; private $startDate;
/** /**
* The end date of period. * The end date of period
* *
* @var DateTime * @var DateTime
*/ */
private $endDate; private $endDate;
/** /**
* Class constructor. * Class constructor
* *
* @param DateTime $startDate (optional) The start date of period * @param DateTime $startDate (optional) The start date of period
* @param DateTime $endDate (optional) The end date of period * @param DateTime $endDate (optional) The end date of period
@@ -109,23 +111,10 @@ class DatePeriod
} }
/** /**
* Returns information if given period is correct. * Returns formatted one of the period's date: start date or end date
*
* @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.
* *
* @param string $format Format used to format the date * @param string $format Format used to format the date
* @param bool $startDate (optional) If is set to true, start date is formatted. Otherwise - end date. * @param bool $startDate (optional) If is set to true, start date is formatted. Otherwise - end date.
*
* @return string * @return string
*/ */
public function getFormattedDate($format, $startDate = true) public function getFormattedDate($format, $startDate = true)
@@ -142,7 +131,7 @@ class DatePeriod
/* /*
* Unknown date or format is invalid? * Unknown date or format is invalid?
*/ */
if ($date === null || !Date::isValidDateFormat($format)) { if (null === $date || !Date::isValidDateFormat($format)) {
return ''; return '';
} }
@@ -150,7 +139,7 @@ class DatePeriod
} }
/** /**
* Returns the end date of period. * Returns the end date of period
* *
* @return DateTime * @return DateTime
*/ */
@@ -160,10 +149,9 @@ class DatePeriod
} }
/** /**
* Sets the end date of period. * Sets the end date of period
* *
* @param DateTime $endDate (optional) The end date of period * @param DateTime $endDate (optional) The end date of period
*
* @return $this * @return $this
*/ */
public function setEndDate(DateTime $endDate = null) public function setEndDate(DateTime $endDate = null)
@@ -174,7 +162,7 @@ class DatePeriod
} }
/** /**
* Returns the start date of period. * Returns the start date of period
* *
* @return DateTime * @return DateTime
*/ */
@@ -184,10 +172,9 @@ class DatePeriod
} }
/** /**
* Sets the start date of period. * Sets the start date of period
* *
* @param DateTime $startDate (optional) The start date of period * @param DateTime $startDate (optional) The start date of period
*
* @return $this * @return $this
*/ */
public function setStartDate(DateTime $startDate = null) public function setStartDate(DateTime $startDate = null)

View File

@@ -5,31 +5,31 @@ namespace Meritoo\Common\Type;
use Meritoo\Common\Type\Base\BaseType; use Meritoo\Common\Type\Base\BaseType;
/** /**
* The visibility of a property, a method or (as of PHP 7.1.0) a constant. * The visibility of a property, a method or (as of PHP 7.1.0) a constant
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
* *
* @see http://php.net/manual/en/language.oop5.visibility.php * @see http://php.net/manual/en/language.oop5.visibility.php
*/ */
class OopVisibilityType extends BaseType class OopVisibilityType extends BaseType
{ {
/** /**
* The "private" visibility of OOP. * The "private" visibility of OOP
* *
* @var int * @var int
*/ */
const IS_PRIVATE = 3; const IS_PRIVATE = 3;
/** /**
* The "protected" visibility of OOP. * The "protected" visibility of OOP
* *
* @var int * @var int
*/ */
const IS_PROTECTED = 2; const IS_PROTECTED = 2;
/** /**
* The "public" visibility of OOP. * The "public" visibility of OOP
* *
* @var int * @var int
*/ */

View File

@@ -9,15 +9,15 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
/** /**
* Useful arrays methods. * Useful arrays methods
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Arrays class Arrays
{ {
/** /**
* Name of the array's key used to store position of element of the array. * Name of the array's key used to store position of element of the array
* *
* @var string * @var string
*/ */
@@ -30,7 +30,6 @@ class Arrays
* @param array $array Array data to be converted * @param array $array Array data to be converted
* @param string|int $arrayColumnKey (optional) Column name * @param string|int $arrayColumnKey (optional) Column name
* @param string $separator (optional) Separator used in resultant string * @param string $separator (optional) Separator used in resultant string
*
* @return string * @return string
*/ */
public static function values2string(array $array, $arrayColumnKey = '', $separator = ',') public static function values2string(array $array, $arrayColumnKey = '', $separator = ',')
@@ -49,23 +48,6 @@ class Arrays
if (is_array($value)) { if (is_array($value)) {
$effect .= self::values2string($value, $arrayColumnKey, $separator); $effect .= self::values2string($value, $arrayColumnKey, $separator);
/*
* Previous version. Doesn't work with array containing arrays, e.g.:
* array(
* 1 => array(
* 'item1',
* 'item2'
* ),
* 2 => array(
* 'item3',
* 'item4'
* )
* )
*
if(isset($value[$arrayColumnKey])){
$effect .= $value[$arrayColumnKey];
}
*/
} else { } else {
if (empty($arrayColumnKey)) { if (empty($arrayColumnKey)) {
$effect .= $value; $effect .= $value;
@@ -80,13 +62,12 @@ class Arrays
} }
/** /**
* Converts given array to string with keys, e.g. abc=1&def=2 or abc="1" def="2". * Converts given array to string with keys, e.g. abc=1&def=2 or abc="1" def="2"
* *
* @param array $array Array data to be converted * @param array $array Array data to be converted
* @param string $separator (optional) Separator used between name-value pairs in resultant string * @param string $separator (optional) Separator used between name-value pairs in resultant string
* @param string $valuesKeysSeparator (optional) Separator used between name and value in resultant string * @param string $valuesKeysSeparator (optional) Separator used between name and value in resultant string
* @param string $valuesWrapper (optional) Wrapper used to wrap values, e.g. double-quote: key="value" * @param string $valuesWrapper (optional) Wrapper used to wrap values, e.g. double-quote: key="value"
*
* @return string * @return string
*/ */
public static function valuesKeys2string($array, $separator = ',', $valuesKeysSeparator = '=', $valuesWrapper = '') public static function valuesKeys2string($array, $separator = ',', $valuesKeysSeparator = '=', $valuesWrapper = '')
@@ -103,7 +84,7 @@ class Arrays
$value = sprintf('%s%s%s', $valuesWrapper, $value, $valuesWrapper); $value = sprintf('%s%s%s', $valuesWrapper, $value, $valuesWrapper);
} }
$effect .= $key.$valuesKeysSeparator.$value; $effect .= $key . $valuesKeysSeparator . $value;
} }
} }
@@ -111,11 +92,10 @@ class Arrays
} }
/** /**
* Converts given array's rows to csv string. * Converts given array's rows to csv string
* *
* @param array $array Array data to be converted. It have to be an array that represents database table. * @param array $array Array data to be converted. It have to be an array that represents database table.
* @param string $separator (optional) Separator used in resultant string * @param string $separator (optional) Separator used in resultant string
*
* @return string * @return string
*/ */
public static function values2csv($array, $separator = ',') public static function values2csv($array, $separator = ',')
@@ -148,13 +128,12 @@ class Arrays
} }
/** /**
* Returns information if given element is the first one. * Returns information if given element is the first one
* *
* @param array $array The array to get the first element of * @param array $array The array to get the first element of
* @param mixed $element The element to check / verify * @param mixed $element The element to check / verify
* @param bool $firstLevelOnly (optional) If is set to true, first element is returned. Otherwise - totally * @param bool $firstLevelOnly (optional) If is set to true, first element is returned. Otherwise - totally
* first element is returned (first of the First array). * first element is returned (first of the First array).
*
* @return bool * @return bool
*/ */
public static function isFirstElement(array $array, $element, $firstLevelOnly = true) public static function isFirstElement(array $array, $element, $firstLevelOnly = true)
@@ -165,7 +144,7 @@ class Arrays
} }
/** /**
* Returns the first element of given array. * Returns the first element of given array
* *
* It may be first element of given array or the totally first element from the all elements (first element of the * It may be first element of given array or the totally first element from the all elements (first element of the
* first array). * first array).
@@ -173,7 +152,6 @@ class Arrays
* @param array $array The array to get the first element of * @param array $array The array to get the first element of
* @param bool $firstLevelOnly (optional) If is set to true, first element is returned. Otherwise - totally * @param bool $firstLevelOnly (optional) If is set to true, first element is returned. Otherwise - totally
* first element is returned (first of the first array). * first element is returned (first of the first array).
*
* @return mixed * @return mixed
*/ */
public static function getFirstElement(array $array, $firstLevelOnly = true) public static function getFirstElement(array $array, $firstLevelOnly = true)
@@ -197,10 +175,9 @@ class Arrays
} }
/** /**
* Returns first key of array. * Returns first key of array
* *
* @param array $array The array to get the first key of * @param array $array The array to get the first key of
*
* @return mixed * @return mixed
*/ */
public static function getFirstKey(array $array) public static function getFirstKey(array $array)
@@ -219,13 +196,12 @@ class Arrays
} }
/** /**
* Returns information if given element is the last one. * Returns information if given element is the last one
* *
* @param array $array The array to get the last element of * @param array $array The array to get the last element of
* @param mixed $element The element to check / verify * @param mixed $element The element to check / verify
* @param bool $firstLevelOnly (optional) If is set to true, last element is returned. Otherwise - totally * @param bool $firstLevelOnly (optional) If is set to true, last element is returned. Otherwise - totally
* last element is returned (last of the latest array). * last element is returned (last of the latest array).
*
* @return bool * @return bool
*/ */
public static function isLastElement(array $array, $element, $firstLevelOnly = true) public static function isLastElement(array $array, $element, $firstLevelOnly = true)
@@ -236,7 +212,7 @@ class Arrays
} }
/** /**
* Returns the last element of given array. * Returns the last element of given array
* *
* It may be last element of given array or the totally last element from the all elements (last element of the * It may be last element of given array or the totally last element from the all elements (last element of the
* latest array). * latest array).
@@ -244,7 +220,6 @@ class Arrays
* @param array $array The array to get the last element of * @param array $array The array to get the last element of
* @param bool $firstLevelOnly (optional) If is set to true, last element is returned. Otherwise - totally * @param bool $firstLevelOnly (optional) If is set to true, last element is returned. Otherwise - totally
* last element is returned (last of the latest array). * last element is returned (last of the latest array).
*
* @return mixed * @return mixed
*/ */
public static function getLastElement(array $array, $firstLevelOnly = true) public static function getLastElement(array $array, $firstLevelOnly = true)
@@ -267,11 +242,10 @@ class Arrays
} }
/** /**
* Returns breadcrumb (a path) to the last element of array. * Returns breadcrumb (a path) to the last element of array
* *
* @param array $array The array to get the breadcrumb * @param array $array The array to get the breadcrumb
* @param string $separator (optional) Separator used to stick the elements * @param string $separator (optional) Separator used to stick the elements
*
* @return string * @return string
*/ */
public static function getLastElementBreadCrumb($array, $separator = '/') public static function getLastElementBreadCrumb($array, $separator = '/')
@@ -290,14 +264,13 @@ class Arrays
$crumb = $last; $crumb = $last;
} }
return $breadCrumb.$separator.$crumb; return $breadCrumb . $separator . $crumb;
} }
/** /**
* Returns the last row of array. * Returns the last row of array
* *
* @param array $array The array to get the last row of * @param array $array The array to get the last row of
*
* @return mixed * @return mixed
*/ */
public static function getLastRow(array $array) public static function getLastRow(array $array)
@@ -332,12 +305,11 @@ class Arrays
} }
/** /**
* Replaces array keys that match given pattern with new key name. * Replaces array keys that match given pattern with new key name
* *
* @param array $dataArray The array * @param array $dataArray The array
* @param string $oldKeyPattern Old key pattern * @param string $oldKeyPattern Old key pattern
* @param string $newKey New key name * @param string $newKey New key name
*
* @return array * @return array
*/ */
public static function replaceArrayKeys($dataArray, $oldKeyPattern, $newKey) public static function replaceArrayKeys($dataArray, $oldKeyPattern, $newKey)
@@ -362,13 +334,12 @@ class Arrays
} }
/** /**
* Generates JavaScript code for given PHP array. * Generates JavaScript code for given PHP array
* *
* @param array $array The array that should be generated to JavaScript * @param array $array The array that should be generated to JavaScript
* @param string $jsVariableName (optional) Name of the variable that will be in generated JavaScript code * @param string $jsVariableName (optional) Name of the variable that will be in generated JavaScript code
* @param bool $preserveIndexes (optional) If is set to true and $jsVariableName isn't empty, indexes also * @param bool $preserveIndexes (optional) If is set to true and $jsVariableName isn't empty, indexes also
* will be added to the JavaScript code. Otherwise not. * will be added to the JavaScript code. Otherwise not.
*
* @return string|null * @return string|null
*/ */
public static function array2JavaScript(array $array, $jsVariableName = '', $preserveIndexes = false) public static function array2JavaScript(array $array, $jsVariableName = '', $preserveIndexes = false)
@@ -413,8 +384,8 @@ class Arrays
if (is_array($value)) { if (is_array($value)) {
$variable = $index; $variable = $index;
if (is_int($index)) { if (is_integer($index)) {
$variable = 'value_'.$variable; $variable = 'value_' . $variable;
} }
$value = self::array2JavaScript($value, $variable, $preserveIndexes); $value = self::array2JavaScript($value, $variable, $preserveIndexes);
@@ -427,11 +398,11 @@ class Arrays
* var autoGeneratedVariable = new Array(...);autoGeneratedVariable[0] = new Array(...); * var autoGeneratedVariable = new Array(...);autoGeneratedVariable[0] = new Array(...);
* autoGeneratedVariable[1] = new Array(...); * autoGeneratedVariable[1] = new Array(...);
*/ */
if ($counter === 1) { if (1 === $counter) {
$effect .= "\n"; $effect .= "\n";
} }
$effect .= $value."\n"; $effect .= $value . "\n";
$effect .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable); $effect .= sprintf('%s[%s] = %s;', $jsVariableName, Miscellaneous::quoteValue($index), $variable);
if ($counter !== $arrayCount) { if ($counter !== $arrayCount) {
@@ -464,10 +435,9 @@ class Arrays
} }
/** /**
* Quotes (adds quotes) to elements of an array that are strings. * Quotes (adds quotes) to elements of an array that are strings
* *
* @param array $array The array to check for string values * @param array $array The array to check for string values
*
* @return array * @return array
*/ */
public static function quoteStrings($array) public static function quoteStrings($array)
@@ -482,7 +452,7 @@ class Arrays
$value = self::quoteStrings($value); $value = self::quoteStrings($value);
} elseif (is_string($value)) { } elseif (is_string($value)) {
if (!Regex::isQuoted($value)) { if (!Regex::isQuoted($value)) {
$value = '\''.$value.'\''; $value = '\'' . $value . '\'';
} }
} }
@@ -494,11 +464,10 @@ class Arrays
} }
/** /**
* Removes marginal element (first or last). * Removes marginal element (first or last)
* *
* @param string|array $item The item which should be shortened * @param string|array $item The item which should be shortened
* @param bool $last (optional) If is set to true, last element is removed. Otherwise - first. * @param bool $last (optional) If is set to true, last element is removed. Otherwise - first.
*
* @return string|array * @return string|array
*/ */
public static function removeMarginalElement($item, $last = true) public static function removeMarginalElement($item, $last = true)
@@ -523,10 +492,9 @@ class Arrays
} }
/** /**
* Returns last key of array. * Returns last key of array
* *
* @param array $array The array to get the last key of * @param array $array The array to get the last key of
*
* @return mixed * @return mixed
*/ */
public static function getLastKey(array $array) public static function getLastKey(array $array)
@@ -537,15 +505,18 @@ class Arrays
} }
/** /**
* Removes element / item of given array. * Removes element / item of given array
* *
* @param array $array The array that contains element / item which should be removed * @param array $array The array that contains element / item which should be removed
* @param mixed $item The element / item which should be removed * @param mixed $item The element / item which should be removed
*
* @return bool|array * @return bool|array
*/ */
public static function removeElement(array $array, $item) public static function removeElement(array $array, $item)
{ {
/*
* No elements or the element does not exist?
* Nothing to do
*/
if (empty($array) || !in_array($item, $array)) { if (empty($array) || !in_array($item, $array)) {
return false; return false;
} }
@@ -569,7 +540,7 @@ class Arrays
} }
/** /**
* Removes items from given array starting at given element (before or after the element). * Removes items from given array starting at given element (before or after the element)
* *
* @param array $array The array which contains items to remove * @param array $array The array which contains items to remove
* @param mixed $needle The element which is start point of deletion * @param mixed $needle The element which is start point of deletion
@@ -621,7 +592,6 @@ class Arrays
* value will be used with it's key, because other will be overridden. * value will be used with it's key, because other will be overridden.
* Otherwise - values are preserved and keys assigned to that values are * Otherwise - values are preserved and keys assigned to that values are
* returned as an array. * returned as an array.
*
* @return array * @return array
* *
* Example of $ignoreDuplicatedValues = false: * Example of $ignoreDuplicatedValues = false:
@@ -643,6 +613,10 @@ class Arrays
*/ */
public static function setKeysAsValues(array $array, $ignoreDuplicatedValues = true) public static function setKeysAsValues(array $array, $ignoreDuplicatedValues = true)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) { if (empty($array)) {
return []; return [];
} }
@@ -656,7 +630,6 @@ class Arrays
*/ */
if (is_array($value)) { if (is_array($value)) {
$replaced[$key] = self::setKeysAsValues($value, $ignoreDuplicatedValues); $replaced[$key] = self::setKeysAsValues($value, $ignoreDuplicatedValues);
continue; continue;
} }
@@ -684,11 +657,10 @@ class Arrays
} }
/** /**
* Applies ksort() function recursively in the given array. * Applies ksort() function recursively in the given array
* *
* @param array $array The array to sort * @param array $array The array to sort
* @param int $sortFlags (optional) Options of ksort() function * @param int $sortFlags (optional) Options of ksort() function
*
* @return array|null * @return array|null
*/ */
public static function ksortRecursive(array &$array, $sortFlags = SORT_REGULAR) public static function ksortRecursive(array &$array, $sortFlags = SORT_REGULAR)
@@ -701,7 +673,7 @@ class Arrays
return null; return null;
} }
$effect = $array; $effect = &$array;
ksort($effect, $sortFlags); ksort($effect, $sortFlags);
foreach ($effect as &$value) { foreach ($effect as &$value) {
@@ -714,10 +686,9 @@ class Arrays
} }
/** /**
* Returns count / amount of elements that are not array. * Returns count / amount of elements that are not array
* *
* @param array $array The array to count * @param array $array The array to count
*
* @return int|null * @return int|null
*/ */
public static function getNonArrayElementsCount(array $array) public static function getNonArrayElementsCount(array $array)
@@ -735,7 +706,6 @@ class Arrays
foreach ($array as &$value) { foreach ($array as &$value) {
if (is_array($value)) { if (is_array($value)) {
$count += self::getNonArrayElementsCount($value); $count += self::getNonArrayElementsCount($value);
continue; continue;
} }
@@ -746,7 +716,7 @@ class Arrays
} }
/** /**
* Converts given string with special separators to array. * Converts given string with special separators to array
* *
* Example: * Example:
* ~ string: * ~ string:
@@ -761,7 +731,6 @@ class Arrays
* @param string $string The string to be converted * @param string $string The string to be converted
* @param string $separator (optional) Separator used between name-value pairs in the string * @param string $separator (optional) Separator used between name-value pairs in the string
* @param string $valuesKeysSeparator (optional) Separator used between name and value in the string * @param string $valuesKeysSeparator (optional) Separator used between name and value in the string
*
* @return array * @return array
*/ */
public static function string2array($string, $separator = '|', $valuesKeysSeparator = ':') public static function string2array($string, $separator = '|', $valuesKeysSeparator = ':')
@@ -780,7 +749,7 @@ class Arrays
foreach ($exploded as $item) { foreach ($exploded as $item) {
$exploded2 = explode($valuesKeysSeparator, $item); $exploded2 = explode($valuesKeysSeparator, $item);
if (count($exploded2) == 2) { if (2 == count($exploded2)) {
$key = trim($exploded2[0]); $key = trim($exploded2[0]);
$value = trim($exploded2[1]); $value = trim($exploded2[1]);
@@ -792,12 +761,11 @@ class Arrays
} }
/** /**
* Returns information if given keys exist in given array. * Returns information if given keys exist in given array
* *
* @param array $keys The keys to find * @param array $keys The keys to find
* @param array $array The array which maybe contains keys * @param array $array The array which maybe contains keys
* @param bool $explicit (optional) If is set to true, all keys should exist in given array. Otherwise - not all. * @param bool $explicit (optional) If is set to true, all keys should exist in given array. Otherwise - not all.
*
* @return bool * @return bool
*/ */
public static function areKeysInArray($keys, $array, $explicit = true) public static function areKeysInArray($keys, $array, $explicit = true)
@@ -835,7 +803,7 @@ class Arrays
} }
/** /**
* Returns paths of the last elements. * Returns paths of the last elements
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param string $separator (optional) Separator used in resultant strings. Default: ".". * @param string $separator (optional) Separator used in resultant strings. Default: ".".
@@ -843,7 +811,6 @@ class Arrays
* @param string|array $stopIfMatchedBy (optional) Patterns of keys or paths that matched will stop the process * @param string|array $stopIfMatchedBy (optional) Patterns of keys or paths that matched will stop the process
* of path building and including children of those keys or paths (recursive * of path building and including children of those keys or paths (recursive
* will not be used for keys in lower level of given array) * will not be used for keys in lower level of given array)
*
* @return array * @return array
* *
* Examples - $stopIfMatchedBy argument: * Examples - $stopIfMatchedBy argument:
@@ -855,62 +822,66 @@ class Arrays
*/ */
public static function getLastElementsPaths(array $array, $separator = '.', $parentPath = '', $stopIfMatchedBy = '') public static function getLastElementsPaths(array $array, $separator = '.', $parentPath = '', $stopIfMatchedBy = '')
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return [];
}
if (!empty($stopIfMatchedBy)) {
$stopIfMatchedBy = self::makeArray($stopIfMatchedBy);
}
$paths = []; $paths = [];
if (!empty($array)) { foreach ($array as $key => $value) {
if (!empty($stopIfMatchedBy)) { $path = $key;
$stopIfMatchedBy = self::makeArray($stopIfMatchedBy); $stopRecursion = false;
/*
* If the path of parent element is delivered,
* I have to use it and build longer path
*/
if (!empty($parentPath)) {
$pathTemplate = '%s%s%s';
$path = sprintf($pathTemplate, $parentPath, $separator, $key);
} }
foreach ($array as $key => $value) { /*
$path = $key; * Check if the key or current path matches one of patterns at which the process should be stopped,
$stopRecursion = false; * the recursive not used. It means that I have to pass current value and stop processing of the
* array (don't go to the next step).
*/
if (!empty($stopIfMatchedBy)) {
foreach ($stopIfMatchedBy as $rawPattern) {
$pattern = sprintf('|%s|', $rawPattern);
/* if (preg_match($pattern, $key) || preg_match($pattern, $path)) {
* If the path of parent element is delivered, $stopRecursion = true;
* I have to use it and build longer path break;
*/
if (!empty($parentPath)) {
$pathTemplate = '%s%s%s';
$path = sprintf($pathTemplate, $parentPath, $separator, $key);
}
/*
* Check if the key or current path matches one of patterns at which the process should be stopped,
* the recursive not used. It means that I have to pass current value and stop processing of the
* array (don't go to the next step).
*/
if (!empty($stopIfMatchedBy)) {
foreach ($stopIfMatchedBy as $rawPattern) {
$pattern = sprintf('|%s|', $rawPattern);
if (preg_match($pattern, $key) || preg_match($pattern, $path)) {
$stopRecursion = true;
break;
}
} }
} }
}
/* /*
* The value is passed to the returned array if: * The value is passed to the returned array if:
* - it's not an array * - it's not an array
* or * or
* - the process is stopped, recursive is not used * - the process is stopped, recursive is not used
*/ */
if (!is_array($value) || (is_array($value) && empty($value)) || $stopRecursion) { if (!is_array($value) || (is_array($value) && empty($value)) || $stopRecursion) {
$paths[$path] = $value; $paths[$path] = $value;
continue;
}
continue; /*
} * Let's iterate through the next level, using recursive
*/
/* if (is_array($value)) {
* Let's iterate through the next level, using recursive $recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy);
*/ $paths += $recursivePaths;
if (is_array($value)) {
$recursivePaths = self::getLastElementsPaths($value, $separator, $path, $stopIfMatchedBy);
$paths += $recursivePaths;
}
} }
} }
@@ -918,10 +889,9 @@ class Arrays
} }
/** /**
* Makes and returns an array for given variable. * Makes and returns an array for given variable
* *
* @param mixed $variable Variable that should be an array * @param mixed $variable Variable that should be an array
*
* @return array * @return array
*/ */
public static function makeArray($variable) public static function makeArray($variable)
@@ -934,13 +904,12 @@ class Arrays
} }
/** /**
* Returns information if keys / indexes of given array are matched by given pattern. * Returns information if keys / indexes of given array are matched by given pattern
* *
* @param array $array The array to check * @param array $array The array to check
* @param string $pattern The pattern which keys / indexes should match, e.g. "\d+" * @param string $pattern The pattern which keys / indexes should match, e.g. "\d+"
* @param bool $firstLevelOnly (optional) If is set to true, all keys / indexes are checked. Otherwise - from the * @param bool $firstLevelOnly (optional) If is set to true, all keys / indexes are checked. Otherwise - from the
* first level only. * first level only.
*
* @return bool * @return bool
*/ */
public static function areAllKeysMatchedByPattern($array, $pattern, $firstLevelOnly = false) public static function areAllKeysMatchedByPattern($array, $pattern, $firstLevelOnly = false)
@@ -971,7 +940,6 @@ class Arrays
*/ */
if (!preg_match($pattern, $key)) { if (!preg_match($pattern, $key)) {
$areMatched = false; $areMatched = false;
break; break;
} }
@@ -989,12 +957,11 @@ class Arrays
/** /**
* Returns information if keys / indexes of given array are integers, in other words if the array contains * Returns information if keys / indexes of given array are integers, in other words if the array contains
* zero-based keys / indexes. * zero-based keys / indexes
* *
* @param array $array The array to check * @param array $array The array to check
* @param bool $firstLevelOnly (optional) If is set to true, all keys / indexes are checked. Otherwise - from the * @param bool $firstLevelOnly (optional) If is set to true, all keys / indexes are checked. Otherwise - from the
* first level only. * first level only.
*
* @return bool * @return bool
*/ */
public static function areAllKeysIntegers($array, $firstLevelOnly = false) public static function areAllKeysIntegers($array, $firstLevelOnly = false)
@@ -1010,7 +977,6 @@ class Arrays
* *
* @param array $array The array which should contains a value * @param array $array The array which should contains a value
* @param array $keys Keys, path of keys, to find in given array * @param array $keys Keys, path of keys, to find in given array
*
* @return mixed * @return mixed
* *
* Examples: * Examples:
@@ -1060,7 +1026,6 @@ class Arrays
* *
* @param array $array The array to check * @param array $array The array to check
* @param array $keys Keys, path of keys, to find in given array * @param array $keys Keys, path of keys, to find in given array
*
* @return bool * @return bool
* *
* Examples: * Examples:
@@ -1111,11 +1076,14 @@ class Arrays
* *
* @param array $array The array which should contain values of the key * @param array $array The array which should contain values of the key
* @param string $key The key * @param string $key The key
*
* @return array|null * @return array|null
*/ */
public static function getAllValuesOfKey(array $array, $key) public static function getAllValuesOfKey(array $array, $key)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) { if (empty($array)) {
return null; return null;
} }
@@ -1125,7 +1093,6 @@ class Arrays
foreach ($array as $index => $value) { foreach ($array as $index => $value) {
if ($index === $key) { if ($index === $key) {
$values[] = $value; $values[] = $value;
continue; continue;
} }
@@ -1142,7 +1109,7 @@ class Arrays
} }
/** /**
* Sets positions for each element / child of given array and returns the array. * Sets positions for each element / child of given array and returns the array
* *
* Position for the 1st element / child of a parent is set to 1 and incremented for the next element and * Position for the 1st element / child of a parent is set to 1 and incremented for the next element and
* so on. Each parent is treated as separate array, so its elements are treated as positioned at 1st level. * so on. Each parent is treated as separate array, so its elements are treated as positioned at 1st level.
@@ -1151,7 +1118,6 @@ class Arrays
* @param string $keyName (optional) Name of key which will contain the position value * @param string $keyName (optional) Name of key which will contain the position value
* @param int $startPosition (optional) Default, start value of the position for main / given array, not the * @param int $startPosition (optional) Default, start value of the position for main / given array, not the
* children * children
*
* @return array * @return array
*/ */
public static function setPositions(array $array, $keyName = self::POSITION_KEY_NAME, $startPosition = null) public static function setPositions(array $array, $keyName = self::POSITION_KEY_NAME, $startPosition = null)
@@ -1159,7 +1125,7 @@ class Arrays
if (!empty($array)) { if (!empty($array)) {
$childPosition = 1; $childPosition = 1;
if ($startPosition !== null) { if (null !== $startPosition) {
$array[$keyName] = $startPosition; $array[$keyName] = $startPosition;
} }
@@ -1175,10 +1141,9 @@ class Arrays
} }
/** /**
* Trims string values of given array and returns the new array. * Trims string values of given array and returns the new array
* *
* @param array $array The array which values should be trimmed * @param array $array The array which values should be trimmed
*
* @return array * @return array
*/ */
public static function trimRecursive(array $array) public static function trimRecursive(array $array)
@@ -1191,7 +1156,6 @@ class Arrays
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
$effect[$key] = self::trimRecursive($value); $effect[$key] = self::trimRecursive($value);
continue; continue;
} }
@@ -1247,7 +1211,6 @@ class Arrays
* *
* @param array $array An array to sort * @param array $array An array to sort
* @param array $keysOrder An array with keys of the 1st argument in proper / required order * @param array $keysOrder An array with keys of the 1st argument in proper / required order
*
* @return array|null * @return array|null
*/ */
public static function sortByCustomKeysOrder(array $array, array $keysOrder) public static function sortByCustomKeysOrder(array $array, array $keysOrder)
@@ -1289,7 +1252,7 @@ class Arrays
} }
/** /**
* Returns smartly imploded string. * Returns smartly imploded string
* *
* Separators located at the beginning or end of elements are removed. * Separators located at the beginning or end of elements are removed.
* It's required to avoid problems with duplicated separator, e.g. "first//second/third", where separator is a * It's required to avoid problems with duplicated separator, e.g. "first//second/third", where separator is a
@@ -1297,7 +1260,6 @@ class Arrays
* *
* @param array $array The array with elements to implode * @param array $array The array with elements to implode
* @param string $separator Separator used to stick together elements of given array * @param string $separator Separator used to stick together elements of given array
*
* @return string * @return string
*/ */
public static function implodeSmart(array $array, $separator) public static function implodeSmart(array $array, $separator)
@@ -1328,12 +1290,11 @@ class Arrays
} }
/** /**
* Returns information if given array is empty, iow. information if all elements of given array are empty. * Returns information if given array is empty, iow. information if all elements of given array are empty
* *
* @param array $array The array to verify * @param array $array The array to verify
* @param bool $strictNull (optional) If is set to true elements are verified if they are null. Otherwise - only * @param bool $strictNull (optional) If is set to true elements are verified if they are null. Otherwise - only
* if they are empty (e.g. null, '', 0, array()). * if they are empty (e.g. null, '', 0, array()).
*
* @return bool * @return bool
*/ */
public static function areAllValuesEmpty(array $array, $strictNull = false) public static function areAllValuesEmpty(array $array, $strictNull = false)
@@ -1356,7 +1317,7 @@ class Arrays
* *
* If one of the above is true, not all elements of given array are empty * If one of the above is true, not all elements of given array are empty
*/ */
if ((!is_array($element) && $strictNull && $element !== null) || !empty($element)) { if ((!is_array($element) && $strictNull && null !== $element) || !empty($element)) {
return false; return false;
} }
} }
@@ -1383,7 +1344,6 @@ class Arrays
* @param array $array2 The 2nd array to verify * @param array $array2 The 2nd array to verify
* @param bool $valuesOnly (optional) If is set to true, compares values only. Otherwise - keys and values * @param bool $valuesOnly (optional) If is set to true, compares values only. Otherwise - keys and values
* (default behaviour). * (default behaviour).
*
* @return array * @return array
*/ */
public static function arrayDiffRecursive(array $array1, array $array2, $valuesOnly = false) public static function arrayDiffRecursive(array $array1, array $array2, $valuesOnly = false)
@@ -1394,7 +1354,7 @@ class Arrays
* Values should be compared only and both arrays are one-dimensional? * Values should be compared only and both arrays are one-dimensional?
* Let's find difference by using simple function * Let's find difference by using simple function
*/ */
if ($valuesOnly && self::getDimensionsCount($array1) == 1 && self::getDimensionsCount($array2) == 1) { if ($valuesOnly && 1 == self::getDimensionsCount($array1) && 1 == self::getDimensionsCount($array2)) {
return array_diff($array1, $array2); return array_diff($array1, $array2);
} }
@@ -1422,7 +1382,7 @@ class Arrays
} }
} }
if ($difference !== null) { if (null !== $difference) {
$effect[] = $difference; $effect[] = $difference;
} }
} else { } else {
@@ -1470,11 +1430,10 @@ class Arrays
} }
/** /**
* Returns an index / key of given element in given array. * Returns an index / key of given element in given array
* *
* @param array $array The array to verify * @param array $array The array to verify
* @param mixed $element The element who index / key is needed * @param mixed $element The element who index / key is needed
*
* @return bool|null|mixed * @return bool|null|mixed
*/ */
public static function getIndexOf(array $array, $element) public static function getIndexOf(array $array, $element)
@@ -1497,13 +1456,12 @@ class Arrays
} }
/** /**
* Returns an array with incremented indexes / keys. * Returns an array with incremented indexes / keys
* *
* @param array $array The array which indexes / keys should be incremented * @param array $array The array which indexes / keys should be incremented
* @param int|null $startIndex (optional) Index from which incrementation should be started. If not provided, * @param int|null $startIndex (optional) Index from which incrementation should be started. If not provided,
* the first index / key will be used. * the first index / key will be used.
* @param int $incrementStep (optional) Value used for incrementation. The step of incrementation. * @param int $incrementStep (optional) Value used for incrementation. The step of incrementation.
*
* @return array * @return array
*/ */
public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1) public static function incrementIndexes(array $array, $startIndex = null, $incrementStep = 1)
@@ -1515,7 +1473,7 @@ class Arrays
* Start index not provided? * Start index not provided?
* Let's look for the first index / key of given array * Let's look for the first index / key of given array
*/ */
if ($startIndex === null) { if (null === $startIndex) {
$startIndex = self::getFirstKey($array); $startIndex = self::getFirstKey($array);
} }
@@ -1554,11 +1512,10 @@ class Arrays
} }
/** /**
* Returns next element of given array related to given element. * Returns next element of given array related to given element
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param mixed $element Element for who next element should be returned * @param mixed $element Element for who next element should be returned
*
* @return null|mixed * @return null|mixed
*/ */
public static function getNextElement(array $array, $element) public static function getNextElement(array $array, $element)
@@ -1567,11 +1524,10 @@ class Arrays
} }
/** /**
* Returns previous element of given array related to given element. * Returns previous element of given array related to given element
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param mixed $element Element for who previous element should be returned * @param mixed $element Element for who previous element should be returned
*
* @return null|mixed * @return null|mixed
*/ */
public static function getPreviousElement(array $array, $element) public static function getPreviousElement(array $array, $element)
@@ -1580,10 +1536,9 @@ class Arrays
} }
/** /**
* Returns information if given array is a multi dimensional array. * Returns information if given array is a multi dimensional array
* *
* @param array $array The array to verify * @param array $array The array to verify
*
* @return bool|null * @return bool|null
*/ */
public static function isMultiDimensional(array $array) public static function isMultiDimensional(array $array)
@@ -1600,10 +1555,9 @@ class Arrays
} }
/** /**
* Returns count of dimensions, maximum nesting level actually, in given array. * Returns count of dimensions, maximum nesting level actually, in given array
* *
* @param array $array The array to verify * @param array $array The array to verify
*
* @return int * @return int
*/ */
public static function getDimensionsCount(array $array) public static function getDimensionsCount(array $array)
@@ -1628,12 +1582,11 @@ class Arrays
} }
/** /**
* Returns neighbour (next or previous element) for given element. * Returns neighbour (next or previous element) for given element
* *
* @param array $array The array with elements * @param array $array The array with elements
* @param mixed $element Element for who next element should be returned * @param mixed $element Element for who next element should be returned
* @param bool $next (optional) If is set to true, returns next neighbour. Otherwise - previous. * @param bool $next (optional) If is set to true, returns next neighbour. Otherwise - previous.
*
* @return mixed|null * @return mixed|null
*/ */
private static function getNeighbour(array $array, $element, $next = true) private static function getNeighbour(array $array, $element, $next = true)
@@ -1665,7 +1618,7 @@ class Arrays
* Index of element or of element's key is unknown? * Index of element or of element's key is unknown?
* Probably the element does not exist in given array, so... nothing to do * Probably the element does not exist in given array, so... nothing to do
*/ */
if ($elementKey === null || $indexOfKey === null) { if (null === $elementKey || null === $indexOfKey) {
return null; return null;
} }

89
src/Utilities/Bundle.php Normal file
View File

@@ -0,0 +1,89 @@
<?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;
use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException;
/**
* Useful methods for bundle
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class Bundle
{
/**
* Returns path of given bundle to view / template with given extension
*
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template (default: "html.twig")
* @throws IncorrectBundleNameException
* @return string|null
*/
public static function getBundleViewPath($viewPath, $bundleName, $extension = 'html.twig')
{
/*
* Unknown path, extension of the view / template or name of the bundle?
* Nothing to do
*/
if (empty($viewPath) || empty($bundleName) || empty($extension)) {
return null;
}
/*
* Given name of bundle is invalid?
*/
if (!Regex::isValidBundleName($bundleName)) {
throw IncorrectBundleNameException::create($bundleName);
}
/*
* Path of the view / template doesn't end with given extension?
*/
if (!Regex::endsWith($viewPath, $extension)) {
$viewPath = sprintf('%s.%s', $viewPath, $extension);
}
/*
* Prepare short name of bundle and path of view / template with "/" (instead of ":")
*/
$shortBundleName = static::getShortBundleName($bundleName);
$viewPath = str_replace(':', '/', $viewPath);
return sprintf('@%s/%s', $shortBundleName, $viewPath);
}
/**
* Returns short name of bundle (without "Bundle")
*
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @throws IncorrectBundleNameException
* @return string|null
*/
public static function getShortBundleName($fullBundleName)
{
/*
* Given name of bundle is invalid?
*/
if (!Regex::isValidBundleName($fullBundleName)) {
if (!is_string($fullBundleName)) {
$fullBundleName = gettype($fullBundleName);
}
throw new IncorrectBundleNameException($fullBundleName);
}
$matches = [];
$pattern = Regex::getBundleNamePattern();
preg_match($pattern, $fullBundleName, $matches);
return $matches[1];
}
}

View File

@@ -11,26 +11,25 @@ namespace Meritoo\Common\Utilities;
use stdClass; use stdClass;
/** /**
* Useful Composer-related methods (only static functions). * Useful Composer-related methods (only static functions)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Composer class Composer
{ {
/** /**
* Name of the Composer's main file with configuration in Json format. * Name of the Composer's main file with configuration in Json format
* *
* @var string * @var string
*/ */
const FILE_NAME_MAIN = 'composer.json'; const FILE_NAME_MAIN = 'composer.json';
/** /**
* Returns value from composer.json file. * Returns value from composer.json file
* *
* @param string $composerJsonPath Path of composer.json file * @param string $composerJsonPath Path of composer.json file
* @param string $nodeName Name of node who value should be returned * @param string $nodeName Name of node who value should be returned
*
* @return string|null * @return string|null
*/ */
public static function getValue($composerJsonPath, $nodeName) public static function getValue($composerJsonPath, $nodeName)
@@ -60,7 +59,7 @@ class Composer
* Unknown data from the composer.json file or there is no node with given name? * Unknown data from the composer.json file or there is no node with given name?
* Nothing to do * Nothing to do
*/ */
if ($data === null || !isset($data->{$nodeName})) { if (null === $data || !isset($data->{$nodeName})) {
return null; return null;
} }

View File

@@ -10,14 +10,16 @@ namespace Meritoo\Common\Utilities;
use DateInterval; use DateInterval;
use DateTime; use DateTime;
use Meritoo\Common\Exception\Date\UnknownDatePartTypeException; use Exception;
use Meritoo\Common\Exception\Type\UnknownDatePartTypeException;
use Meritoo\Common\Type\DatePartType; use Meritoo\Common\Type\DatePartType;
use Meritoo\Common\Type\DatePeriod;
/** /**
* Useful date methods. * Useful date methods
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Date class Date
{ {
@@ -66,106 +68,113 @@ class Date
* The dates are returned in an array with indexes 'start' and 'end'. * 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. * @param int $period The period, type of period. One of DatePeriod class constants, e.g. DatePeriod::LAST_WEEK.
* * @throws Exception
* @return DatePeriod * @return null|DatePeriod
*/ */
public static function getDatesForPeriod($period) public static function getDatesForPeriod($period)
{ {
$datePeriod = null; /*
* Type of period is incorrect?
if (DatePeriod::isCorrectPeriod($period)) { * Nothing to do
$dateStart = null; */
$dateEnd = null; if (!(new DatePeriod())->isCorrectType($period)) {
return 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 ($period == DatePeriod::LAST_YEAR || $period == DatePeriod::NEXT_YEAR) {
$yearDifference = 1;
if ($period == DatePeriod::LAST_YEAR) {
$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 ($dateStart !== null && $dateEnd !== null) {
$dateStart->setTime(0, 0, 0);
$dateEnd->setTime(23, 59, 59);
$datePeriod = new DatePeriod($dateStart, $dateEnd);
}
} }
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);
} }
/** /**
* Generates and returns random time (the hour, minute and second values). * Generates and returns random time (the hour, minute and second values)
* *
* @param string $format (optional) Format of returned value. A string acceptable by the DateTime::format() * @param string $format (optional) Format of returned value. A string acceptable by the DateTime::format()
* method. * method.
*
* @return string|null * @return string|null
*/ */
public static function generateRandomTime($format = 'H:i:s') public static function generateRandomTime($format = 'H:i:s')
@@ -209,8 +218,9 @@ class Date
} }
/** /**
* Returns current day of week. * Returns current day of week
* *
* @throws UnknownDatePartTypeException
* @return int * @return int
*/ */
public static function getCurrentDayOfWeek() public static function getCurrentDayOfWeek()
@@ -232,35 +242,34 @@ class Date
* @param int $month The month value * @param int $month The month value
* @param int $day The day value * @param int $day The day value
* *
* @return int
*
* @throws UnknownDatePartTypeException * @throws UnknownDatePartTypeException
* @return int
*/ */
public static function getDayOfWeek($year, $month, $day) public static function getDayOfWeek($year, $month, $day)
{ {
$year = (int) $year; $year = (int)$year;
$month = (int) $month; $month = (int)$month;
$day = (int) $day; $day = (int)$day;
/* /*
* Oops, incorrect year * Oops, incorrect year
*/ */
if ($year <= 0) { if ($year <= 0) {
throw new UnknownDatePartTypeException(DatePartType::YEAR, $year); throw UnknownDatePartTypeException::createException(DatePartType::YEAR, $year);
} }
/* /*
* Oops, incorrect month * Oops, incorrect month
*/ */
if ($month < 1 || $month > 12) { if ($month < 1 || $month > 12) {
throw new UnknownDatePartTypeException(DatePartType::MONTH, $month); throw UnknownDatePartTypeException::createException(DatePartType::MONTH, $month);
} }
/* /*
* Oops, incorrect day * Oops, incorrect day
*/ */
if ($day < 1 || $day > 31) { if ($day < 1 || $day > 31) {
throw new UnknownDatePartTypeException(DatePartType::DAY, $day); throw UnknownDatePartTypeException::createException(DatePartType::DAY, $day);
} }
if ($month < 3) { if ($month < 3) {
@@ -280,7 +289,7 @@ class Date
} }
/** /**
* Returns based on locale name of current weekday. * Returns based on locale name of current weekday
* *
* @return string * @return string
*/ */
@@ -296,12 +305,11 @@ class Date
} }
/** /**
* Returns name of weekday based on locale. * Returns name of weekday based on locale
* *
* @param int $year The year value * @param int $year The year value
* @param int $month The month value * @param int $month The month value
* @param int $day The day value * @param int $day The day value
*
* @return string * @return string
*/ */
public static function getDayOfWeekName($year, $month, $day) public static function getDayOfWeekName($year, $month, $day)
@@ -315,7 +323,7 @@ class Date
$encoding = mb_detect_encoding($name); $encoding = mb_detect_encoding($name);
if ($encoding === false) { if (false === $encoding) {
$name = mb_convert_encoding($name, 'UTF-8', 'ISO-8859-2'); $name = mb_convert_encoding($name, 'UTF-8', 'ISO-8859-2');
} }
@@ -342,7 +350,6 @@ class Date
* @param int $differenceUnit (optional) Unit of date difference. One of this class * @param int $differenceUnit (optional) Unit of date difference. One of this class
* DATE_DIFFERENCE_UNIT_* constants. If is set to null all units are * DATE_DIFFERENCE_UNIT_* constants. If is set to null all units are
* returned in the array. * returned in the array.
*
* @return array|int * @return array|int
*/ */
public static function getDateDifference($dateStart, $dateEnd, $differenceUnit = null) public static function getDateDifference($dateStart, $dateEnd, $differenceUnit = null)
@@ -383,46 +390,46 @@ class Date
self::DATE_DIFFERENCE_UNIT_MINUTES, self::DATE_DIFFERENCE_UNIT_MINUTES,
]; ];
if ($differenceUnit === null || $differenceUnit == self::DATE_DIFFERENCE_UNIT_YEARS) { if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_YEARS == $differenceUnit) {
$diff = $dateEnd->diff($dateStart); $diff = $dateEnd->diff($dateStart);
/* /*
* Difference between dates in years should be returned only? * Difference between dates in years should be returned only?
*/ */
if ($differenceUnit == self::DATE_DIFFERENCE_UNIT_YEARS) { if (self::DATE_DIFFERENCE_UNIT_YEARS == $differenceUnit) {
return $diff->y; return $diff->y;
} }
$difference[self::DATE_DIFFERENCE_UNIT_YEARS] = $diff->y; $difference[self::DATE_DIFFERENCE_UNIT_YEARS] = $diff->y;
} }
if ($differenceUnit === null || $differenceUnit == self::DATE_DIFFERENCE_UNIT_MONTHS) { if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_MONTHS == $differenceUnit) {
$diff = $dateEnd->diff($dateStart); $diff = $dateEnd->diff($dateStart);
/* /*
* Difference between dates in months should be returned only? * Difference between dates in months should be returned only?
*/ */
if ($differenceUnit == self::DATE_DIFFERENCE_UNIT_MONTHS) { if (self::DATE_DIFFERENCE_UNIT_MONTHS == $differenceUnit) {
return $diff->m; return $diff->m;
} }
$difference[self::DATE_DIFFERENCE_UNIT_MONTHS] = $diff->m; $difference[self::DATE_DIFFERENCE_UNIT_MONTHS] = $diff->m;
} }
if ($differenceUnit === null || in_array($differenceUnit, $relatedUnits)) { if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits)) {
$days = (int) floor($dateDiff / $daySeconds); $days = (int)floor($dateDiff / $daySeconds);
/* /*
* Difference between dates in days should be returned only? * Difference between dates in days should be returned only?
*/ */
if ($differenceUnit == self::DATE_DIFFERENCE_UNIT_DAYS) { if (self::DATE_DIFFERENCE_UNIT_DAYS == $differenceUnit) {
return $days; return $days;
} }
/* /*
* All units should be returned? * All units should be returned?
*/ */
if ($differenceUnit === null) { if (null === $differenceUnit) {
$difference[self::DATE_DIFFERENCE_UNIT_DAYS] = $days; $difference[self::DATE_DIFFERENCE_UNIT_DAYS] = $days;
} }
@@ -432,20 +439,20 @@ class Date
$daysInSeconds = $days * $daySeconds; $daysInSeconds = $days * $daySeconds;
} }
if ($differenceUnit === null || in_array($differenceUnit, $relatedUnits)) { if (null === $differenceUnit || in_array($differenceUnit, $relatedUnits)) {
$hours = (int) floor(($dateDiff - $daysInSeconds) / $hourSeconds); $hours = (int)floor(($dateDiff - $daysInSeconds) / $hourSeconds);
/* /*
* Difference between dates in hours should be returned only? * Difference between dates in hours should be returned only?
*/ */
if ($differenceUnit == self::DATE_DIFFERENCE_UNIT_HOURS) { if (self::DATE_DIFFERENCE_UNIT_HOURS == $differenceUnit) {
return $hours; return $hours;
} }
/* /*
* All units should be returned? * All units should be returned?
*/ */
if ($differenceUnit === null) { if (null === $differenceUnit) {
$difference[self::DATE_DIFFERENCE_UNIT_HOURS] = $hours; $difference[self::DATE_DIFFERENCE_UNIT_HOURS] = $hours;
} }
@@ -455,13 +462,13 @@ class Date
$hoursInSeconds = $hours * $hourSeconds; $hoursInSeconds = $hours * $hourSeconds;
} }
if ($differenceUnit === null || $differenceUnit == self::DATE_DIFFERENCE_UNIT_MINUTES) { if (null === $differenceUnit || self::DATE_DIFFERENCE_UNIT_MINUTES == $differenceUnit) {
$minutes = (int) floor(($dateDiff - $daysInSeconds - $hoursInSeconds) / 60); $minutes = (int)floor(($dateDiff - $daysInSeconds - $hoursInSeconds) / 60);
/* /*
* Difference between dates in minutes should be returned only? * Difference between dates in minutes should be returned only?
*/ */
if ($differenceUnit == self::DATE_DIFFERENCE_UNIT_MINUTES) { if (self::DATE_DIFFERENCE_UNIT_MINUTES == $differenceUnit) {
return $minutes; return $minutes;
} }
@@ -480,7 +487,7 @@ class Date
* @param string $intervalTemplate (optional) Template used to build date interval. It should contain "%d" as the * @param string $intervalTemplate (optional) Template used to build date interval. It should contain "%d" as the
* placeholder which is replaced with a number that represents each iteration. * placeholder which is replaced with a number that represents each iteration.
* Default: interval for days. * Default: interval for days.
* * @throws Exception
* @return array * @return array
*/ */
public static function getDatesCollection(DateTime $startDate, $datesCount, $intervalTemplate = 'P%dD') public static function getDatesCollection(DateTime $startDate, $datesCount, $intervalTemplate = 'P%dD')
@@ -506,7 +513,7 @@ class Date
$matchCount = preg_match($intervalPattern, $intervalTemplate, $matches); $matchCount = preg_match($intervalPattern, $intervalTemplate, $matches);
if ($matchCount > 0 && (!empty($matches[1]) || !empty($matches[2]))) { if ($matchCount > 0 && (!empty($matches[1]) || !empty($matches[2]))) {
$datesCount = (int) $datesCount; $datesCount = (int)$datesCount;
for ($index = 1; $index <= $datesCount; ++$index) { for ($index = 1; $index <= $datesCount; ++$index) {
$date = clone $startDate; $date = clone $startDate;
@@ -519,24 +526,24 @@ class Date
} }
/** /**
* Returns random date based on given start date. * Returns random date based on given start date
* *
* @param DateTime $startDate The start date. Start of the random date. * @param DateTime $startDate The start date. Start of the random date.
* @param int $start (optional) Start of random partition * @param int $start (optional) Start of random partition
* @param int $end (optional) End of random partition * @param int $end (optional) End of random partition
* @param string $intervalTemplate (optional) Template used to build date interval. The placeholder is replaced * @param string $intervalTemplate (optional) Template used to build date interval. The placeholder is replaced
* with next, iterated value. * with next, iterated value.
* * @throws Exception
* @return DateTime * @return DateTime
*/ */
public static function getRandomDate(DateTime $startDate = null, $start = 1, $end = 100, $intervalTemplate = 'P%sD') public static function getRandomDate(DateTime $startDate = null, $start = 1, $end = 100, $intervalTemplate = 'P%sD')
{ {
if ($startDate === null) { if (null === $startDate) {
$startDate = new DateTime(); $startDate = new DateTime();
} }
$start = (int) $start; $start = (int)$start;
$end = (int) $end; $end = (int)$end;
/* /*
* Incorrect end of random partition? * Incorrect end of random partition?
@@ -563,7 +570,6 @@ class Date
* @param string $dateFormat (optional) Format of date used to verify if given value is actually a date. * @param string $dateFormat (optional) Format of date used to verify if given value is actually a date.
* It should be format matched to the given value, e.g. "Y-m-d H:i" for * It should be format matched to the given value, e.g. "Y-m-d H:i" for
* "2015-01-01 10:00" value. * "2015-01-01 10:00" value.
*
* @return DateTime|bool * @return DateTime|bool
*/ */
public static function getDateTime($value, $allowCompoundFormats = false, $dateFormat = 'Y-m-d') public static function getDateTime($value, $allowCompoundFormats = false, $dateFormat = 'Y-m-d')
@@ -598,7 +604,7 @@ class Date
*/ */
$dateFromFormat = DateTime::createFromFormat($dateFormat, $value); $dateFromFormat = DateTime::createFromFormat($dateFormat, $value);
if ($dateFromFormat === false) { if (false === $dateFromFormat) {
/* /*
* Nothing to do more, because: * Nothing to do more, because:
* a) instance of the DateTime was created * a) instance of the DateTime was created
@@ -666,13 +672,12 @@ class Date
} }
/** /**
* Returns information if given value is valid date. * Returns information if given value is valid date
* *
* @param mixed $value The value which maybe is a date * @param mixed $value The value which maybe is a date
* @param bool $allowCompoundFormats (optional) If is set to true, the compound formats used to create an * @param bool $allowCompoundFormats (optional) If is set to true, the compound formats used to create an
* instance of DateTime class are allowed (e.g. "now", "last day of next * instance of DateTime class are allowed (e.g. "now", "last day of next
* month", "yyyy"). Otherwise - not and every incorrect value is refused. * month", "yyyy"). Otherwise - not and every incorrect value is refused.
*
* @return bool * @return bool
*/ */
public static function isValidDate($value, $allowCompoundFormats = false) public static function isValidDate($value, $allowCompoundFormats = false)
@@ -681,10 +686,9 @@ class Date
} }
/** /**
* Returns information if given format of date is valid. * Returns information if given format of date is valid
* *
* @param string $format The validated format of date * @param string $format The validated format of date
*
* @return bool * @return bool
*/ */
public static function isValidDateFormat($format) public static function isValidDateFormat($format)

View File

@@ -11,18 +11,17 @@ namespace Meritoo\Common\Utilities;
use Generator; use Generator;
/** /**
* Useful methods for the Generator class (only static functions). * Useful methods for the Generator class (only static functions)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class GeneratorUtility class GeneratorUtility
{ {
/** /**
* Returns elements of generator. * Returns elements of generator
* *
* @param Generator $generator The generator who elements should be returned * @param Generator $generator The generator who elements should be returned
*
* @return array * @return array
*/ */
public static function getGeneratorElements(Generator $generator) public static function getGeneratorElements(Generator $generator)

View File

@@ -9,22 +9,21 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
/** /**
* Useful locale methods. * Useful locale methods
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Locale class Locale
{ {
/** /**
* Sets locale for given category using given language and country code. * Sets locale for given category using given language and country code
* *
* @param int $category Named constant specifying the category of the functions affected by the locale * @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. * setting. It's the same constant as required by setlocale() function.
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr". * @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode (optional) Country code, in ISO 3166-1 alpha-2 format, e.g. "FR" * @param string $countryCode (optional) Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* * @return false|string
* @return bool
* *
* Available categories (values of $category argument): * Available categories (values of $category argument):
* - LC_ALL for all of the below * - LC_ALL for all of the below
@@ -37,7 +36,7 @@ class Locale
*/ */
public static function setLocale($category, $languageCode, $countryCode = '') public static function setLocale($category, $languageCode, $countryCode = '')
{ {
$category = (int) $category; $category = (int)$category;
if (is_string($languageCode)) { if (is_string($languageCode)) {
$languageCode = trim($languageCode); $languageCode = trim($languageCode);
@@ -58,18 +57,37 @@ class Locale
} }
$localeLongForm = self::getLongForm($languageCode, $countryCode); $localeLongForm = self::getLongForm($languageCode, $countryCode);
setlocale($category, $localeLongForm);
return true; return setlocale($category, $localeLongForm);
} }
/** /**
* Returns long form of the locale. * Returns locale for given category
*
* @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.
* @return string
*
* Available categories (values of $category argument):
* - LC_ALL for all of the below
* - LC_COLLATE for string comparison, see strcoll()
* - LC_CTYPE for character classification and conversion, for example strtoupper()
* - LC_MONETARY for localeconv()
* - LC_NUMERIC for decimal separator (See also localeconv())
* - LC_TIME for date and time formatting with strftime()
* - LC_MESSAGES for system responses (available if PHP was compiled with libintl)
*/
public static function getLocale($category)
{
return setlocale($category, '0');
}
/**
* Returns long form of the locale
* *
* @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr". * @param string $languageCode Language code, in ISO 639-1 format. Short form of the locale, e.g. "fr".
* @param string $countryCode (optional) Country code, in ISO 3166-1 alpha-2 format, e.g. "FR" * @param string $countryCode (optional) Country code, in ISO 3166-1 alpha-2 format, e.g. "FR"
* @param string $encoding (optional) Encoding of the final locale * @param string $encoding (optional) Encoding of the final locale
*
* @return string * @return string
* *
* Example: * Example:

815
src/Utilities/MimeTypes.php Normal file
View File

@@ -0,0 +1,815 @@
<?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;
/**
* Useful methods for mime types of files
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class MimeTypes
{
/**
* Mime types data
*
* @var array
*/
private static $mimeTypes = [
'7z' => 'application/x-7z-compressed',
'ez' => 'application/andrew-inset',
'atom' => 'application/atom+xml',
'atomcat' => 'application/atomcat+xml',
'atomsvc' => 'application/atomsvc+xml',
'ccxml' => 'application/ccxml+xml',
'davmount' => 'application/davmount+xml',
'ecma' => 'application/ecmascript',
'pfr' => 'application/font-tdpfr',
'stk' => 'application/hyperstudio',
'js' => 'application/javascript',
'json' => 'application/json',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'mrc' => 'application/marc',
'ma' => 'application/mathematica',
'nb' => 'application/mathematica',
'mb' => 'application/mathematica',
'mathml' => 'application/mathml+xml',
'mbox' => 'application/mbox',
'mscml' => 'application/mediaservercontrol+xml',
'mp4s' => 'application/mp4',
'dot' => 'application/msword',
'doc' => 'application/msword',
/*
* MS Office system file format MIME types
* http://technet.microsoft.com/en-us/library/ee309278%28office.12%29.aspx
*/
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'mxf' => 'application/mxf',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'class' => 'application/octet-stream',
'so' => 'application/octet-stream',
'iso' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'dist' => 'application/octet-stream',
'distz' => 'application/octet-stream',
'pkg' => 'application/octet-stream',
'bpk' => 'application/octet-stream',
'dump' => 'application/octet-stream',
'elc' => 'application/octet-stream',
'scpt' => 'application/octet-stream',
'oda' => 'application/oda',
'ogg' => 'application/ogg',
'pdf' => 'application/pdf',
'pgp' => 'application/pgp-encrypted',
'asc' => 'application/pgp-signature',
'sig' => 'application/pgp-signature',
'prf' => 'application/pics-rules',
'p10' => 'application/pkcs10',
'p7m' => 'application/pkcs7-mime',
'p7c' => 'application/pkcs7-mime',
'p7s' => 'application/pkcs7-signature',
'cer' => 'application/pkix-cert',
'crl' => 'application/pkix-crl',
'pkipath' => 'application/pkix-pkipath',
'pki' => 'application/pkixcmp',
'pls' => 'application/pls+xml',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'cww' => 'application/prs.cww',
'rdf' => 'application/rdf+xml',
'rif' => 'application/reginfo+xml',
'rnc' => 'application/relax-ng-compact-syntax',
'rl' => 'application/resource-lists+xml',
'rs' => 'application/rls-services+xml',
'rsd' => 'application/rsd+xml',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'sbml' => 'application/sbml+xml',
'sdp' => 'application/sdp',
'setpay' => 'application/set-payment-initiation',
'setreg' => 'application/set-registration-initiation',
'shf' => 'application/shf+xml',
'smi' => 'application/smil+xml',
'smil' => 'application/smil+xml',
'gram' => 'application/srgs',
'grxml' => 'application/srgs+xml',
'ssml' => 'application/ssml+xml',
'plb' => 'application/vnd.3gpp.pic-bw-large',
'psb' => 'application/vnd.3gpp.pic-bw-small',
'pvb' => 'application/vnd.3gpp.pic-bw-var',
'pwn' => 'application/vnd.3m.post-it-notes',
'aso' => 'application/vnd.accpac.simply.aso',
'imp' => 'application/vnd.accpac.simply.imp',
'acu' => 'application/vnd.acucobol',
'atc' => 'application/vnd.acucorp',
'acutc' => 'application/vnd.acucorp',
'xdp' => 'application/vnd.adobe.xdp+xml',
'xfdf' => 'application/vnd.adobe.xfdf',
'ami' => 'application/vnd.amiga.ami',
'cii' => 'application/vnd.anser-web-certificate-issue-initiation',
'fti' => 'application/vnd.anser-web-funds-transfer-initiation',
'atx' => 'application/vnd.antix.game-component',
'mpkg' => 'application/vnd.apple.installer+xml',
'aep' => 'application/vnd.audiograph',
'mpm' => 'application/vnd.blueice.multipass',
'bmi' => 'application/vnd.bmi',
'rep' => 'application/vnd.businessobjects',
'cdxml' => 'application/vnd.chemdraw+xml',
'mmd' => 'application/vnd.chipnuts.karaoke-mmd',
'cdy' => 'application/vnd.cinderella',
'cla' => 'application/vnd.claymore',
'c4g' => 'application/vnd.clonk.c4group',
'c4d' => 'application/vnd.clonk.c4group',
'c4f' => 'application/vnd.clonk.c4group',
'c4p' => 'application/vnd.clonk.c4group',
'c4u' => 'application/vnd.clonk.c4group',
'csp' => 'application/vnd.commonspace',
'cst' => 'application/vnd.commonspace',
'cdbcmsg' => 'application/vnd.contact.cmsg',
'cmc' => 'application/vnd.cosmocaller',
'clkx' => 'application/vnd.crick.clicker',
'clkk' => 'application/vnd.crick.clicker.keyboard',
'clkp' => 'application/vnd.crick.clicker.palette',
'clkt' => 'application/vnd.crick.clicker.template',
'clkw' => 'application/vnd.crick.clicker.wordbank',
'wbs' => 'application/vnd.criticaltools.wbs+xml',
'pml' => 'application/vnd.ctc-posml',
'ppd' => 'application/vnd.cups-ppd',
'curl' => 'application/vnd.curl',
'rdz' => 'application/vnd.data-vision.rdz',
'dna' => 'application/vnd.dna',
'mlp' => 'application/vnd.dolby.mlp',
'dpg' => 'application/vnd.dpgraph',
'dfac' => 'application/vnd.dreamfactory',
'mag' => 'application/vnd.ecowin.chart',
'nml' => 'application/vnd.enliven',
'esf' => 'application/vnd.epson.esf',
'msf' => 'application/vnd.epson.msf',
'qam' => 'application/vnd.epson.quickanime',
'slt' => 'application/vnd.epson.salt',
'ssf' => 'application/vnd.epson.ssf',
'es3' => 'application/vnd.eszigno3+xml',
'et3' => 'application/vnd.eszigno3+xml',
'ez2' => 'application/vnd.ezpix-album',
'ez3' => 'application/vnd.ezpix-package',
'fdf' => 'application/vnd.fdf',
'gph' => 'application/vnd.flographit',
'ftc' => 'application/vnd.fluxtime.clip',
'fm' => 'application/vnd.framemaker',
'frame' => 'application/vnd.framemaker',
'maker' => 'application/vnd.framemaker',
'fnc' => 'application/vnd.frogans.fnc',
'ltf' => 'application/vnd.frogans.ltf',
'fsc' => 'application/vnd.fsc.weblaunch',
'oas' => 'application/vnd.fujitsu.oasys',
'oa2' => 'application/vnd.fujitsu.oasys2',
'oa3' => 'application/vnd.fujitsu.oasys3',
'fg5' => 'application/vnd.fujitsu.oasysgp',
'bh2' => 'application/vnd.fujitsu.oasysprs',
'ddd' => 'application/vnd.fujixerox.ddd',
'xdw' => 'application/vnd.fujixerox.docuworks',
'xbd' => 'application/vnd.fujixerox.docuworks.binder',
'fzs' => 'application/vnd.fuzzysheet',
'txd' => 'application/vnd.genomatix.tuxedo',
'kml' => 'application/vnd.google-earth.kml+xml',
'kmz' => 'application/vnd.google-earth.kmz',
'gqf' => 'application/vnd.grafeq',
'gqs' => 'application/vnd.grafeq',
'gac' => 'application/vnd.groove-account',
'ghf' => 'application/vnd.groove-help',
'gim' => 'application/vnd.groove-identity-message',
'grv' => 'application/vnd.groove-injector',
'gtm' => 'application/vnd.groove-tool-message',
'tpl' => 'application/vnd.groove-tool-template',
'vcg' => 'application/vnd.groove-vcard',
'zmm' => 'application/vnd.handheld-entertainment+xml',
'hbci' => 'application/vnd.hbci',
'les' => 'application/vnd.hhe.lesson-player',
'hpgl' => 'application/vnd.hp-hpgl',
'hpid' => 'application/vnd.hp-hpid',
'hps' => 'application/vnd.hp-hps',
'jlt' => 'application/vnd.hp-jlyt',
'pcl' => 'application/vnd.hp-pcl',
'pclxl' => 'application/vnd.hp-pclxl',
'x3d' => 'application/vnd.hzn-3d-crossword',
'mpy' => 'application/vnd.ibm.minipay',
'afp' => 'application/vnd.ibm.modcap',
'listafp' => 'application/vnd.ibm.modcap',
'list3820' => 'application/vnd.ibm.modcap',
'irm' => 'application/vnd.ibm.rights-management',
'sc' => 'application/vnd.ibm.secure-container',
'igl' => 'application/vnd.igloader',
'ivp' => 'application/vnd.immervision-ivp',
'ivu' => 'application/vnd.immervision-ivu',
'xpw' => 'application/vnd.intercon.formnet',
'xpx' => 'application/vnd.intercon.formnet',
'qbo' => 'application/vnd.intu.qbo',
'qfx' => 'application/vnd.intu.qfx',
'rcprofile' => 'application/vnd.ipunplugged.rcprofile',
'irp' => 'application/vnd.irepository.package+xml',
'xpr' => 'application/vnd.is-xpr',
'jam' => 'application/vnd.jam',
'rms' => 'application/vnd.jcp.javame.midlet-rms',
'jisp' => 'application/vnd.jisp',
'ktz' => 'application/vnd.kahootz',
'ktr' => 'application/vnd.kahootz',
'karbon' => 'application/vnd.kde.karbon',
'chrt' => 'application/vnd.kde.kchart',
'kfo' => 'application/vnd.kde.kformula',
'flw' => 'application/vnd.kde.kivio',
'kon' => 'application/vnd.kde.kontour',
'kpr' => 'application/vnd.kde.kpresenter',
'kpt' => 'application/vnd.kde.kpresenter',
'ksp' => 'application/vnd.kde.kspread',
'kwd' => 'application/vnd.kde.kword',
'kwt' => 'application/vnd.kde.kword',
'htke' => 'application/vnd.kenameaapp',
'kia' => 'application/vnd.kidspiration',
'kne' => 'application/vnd.kinar',
'knp' => 'application/vnd.kinar',
'skp' => 'application/vnd.koan',
'skd' => 'application/vnd.koan',
'skt' => 'application/vnd.koan',
'skm' => 'application/vnd.koan',
'lbd' => 'application/vnd.llamagraphics.life-balance.desktop',
'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml',
'123' => 'application/vnd.lotus-1-2-3',
'apr' => 'application/vnd.lotus-approach',
'pre' => 'application/vnd.lotus-freelance',
'nsf' => 'application/vnd.lotus-notes',
'org' => 'application/vnd.lotus-organizer',
'scm' => 'application/vnd.lotus-screencam',
'lwp' => 'application/vnd.lotus-wordpro',
'portpkg' => 'application/vnd.macports.portpkg',
'mcd' => 'application/vnd.mcd',
'mc1' => 'application/vnd.medcalcdata',
'cdkey' => 'application/vnd.mediastation.cdkey',
'mwf' => 'application/vnd.mfer',
'mfm' => 'application/vnd.mfmp',
'flo' => 'application/vnd.micrografx.flo',
'igx' => 'application/vnd.micrografx.igx',
'mif' => 'application/vnd.mif',
'daf' => 'application/vnd.mobius.daf',
'dis' => 'application/vnd.mobius.dis',
'mbk' => 'application/vnd.mobius.mbk',
'mqy' => 'application/vnd.mobius.mqy',
'msl' => 'application/vnd.mobius.msl',
'plc' => 'application/vnd.mobius.plc',
'txf' => 'application/vnd.mobius.txf',
'mpn' => 'application/vnd.mophun.application',
'mpc' => 'application/vnd.mophun.certificate',
'xul' => 'application/vnd.mozilla.xul+xml',
'cil' => 'application/vnd.ms-artgalry',
'asf' => 'application/vnd.ms-asf',
'cab' => 'application/vnd.ms-cab-compressed',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlm' => 'application/vnd.ms-excel',
'xla' => 'application/vnd.ms-excel',
'xlc' => 'application/vnd.ms-excel',
'xlt' => 'application/vnd.ms-excel',
'xlw' => 'application/vnd.ms-excel',
'eot' => 'application/vnd.ms-fontobject',
'chm' => 'application/vnd.ms-htmlhelp',
'ims' => 'application/vnd.ms-ims',
'lrm' => 'application/vnd.ms-lrm',
'ppt' => 'application/vnd.ms-powerpoint',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pps' => 'application/vnd.ms-powerpoint',
'pot' => 'application/vnd.ms-powerpoint',
'mpp' => 'application/vnd.ms-project',
'mpt' => 'application/vnd.ms-project',
'wps' => 'application/vnd.ms-works',
'wks' => 'application/vnd.ms-works',
'wcm' => 'application/vnd.ms-works',
'wdb' => 'application/vnd.ms-works',
'wpl' => 'application/vnd.ms-wpl',
'xps' => 'application/vnd.ms-xpsdocument',
'mseq' => 'application/vnd.mseq',
'mus' => 'application/vnd.musician',
'nlu' => 'application/vnd.neurolanguage.nlu',
'nnd' => 'application/vnd.noblenet-directory',
'nns' => 'application/vnd.noblenet-sealer',
'nnw' => 'application/vnd.noblenet-web',
'ngdat' => 'application/vnd.nokia.n-gage.data',
'n-gage' => 'application/vnd.nokia.n-gage.symbian.install',
'rpst' => 'application/vnd.nokia.radio-preset',
'rpss' => 'application/vnd.nokia.radio-presets',
'edm' => 'application/vnd.novadigm.edm',
'edx' => 'application/vnd.novadigm.edx',
'ext' => 'application/vnd.novadigm.ext',
'odc' => 'application/vnd.oasis.opendocument.chart',
'otc' => 'application/vnd.oasis.opendocument.chart-template',
'odf' => 'application/vnd.oasis.opendocument.formula',
'otf' => 'application/vnd.oasis.opendocument.formula-template',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'odi' => 'application/vnd.oasis.opendocument.image',
'oti' => 'application/vnd.oasis.opendocument.image-template',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'odt' => 'application/vnd.oasis.opendocument.text',
'otm' => 'application/vnd.oasis.opendocument.text-master',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'xo' => 'application/vnd.olpc-sugar',
'dd2' => 'application/vnd.oma.dd2+xml',
'oxt' => 'application/vnd.openofficeorg.extension',
'dp' => 'application/vnd.osgi.dp',
'prc' => 'application/vnd.palm',
'pdb' => 'application/vnd.palm',
'pqa' => 'application/vnd.palm',
'oprc' => 'application/vnd.palm',
'str' => 'application/vnd.pg.format',
'ei6' => 'application/vnd.pg.osasli',
'efif' => 'application/vnd.picsel',
'plf' => 'application/vnd.pocketlearn',
'pbd' => 'application/vnd.powerbuilder6',
'box' => 'application/vnd.previewsystems.box',
'mgz' => 'application/vnd.proteus.magazine',
'qps' => 'application/vnd.publishare-delta-tree',
'ptid' => 'application/vnd.pvi.ptid1',
'qxd' => 'application/vnd.quark.quarkxpress',
'qxt' => 'application/vnd.quark.quarkxpress',
'qwd' => 'application/vnd.quark.quarkxpress',
'qwt' => 'application/vnd.quark.quarkxpress',
'qxl' => 'application/vnd.quark.quarkxpress',
'qxb' => 'application/vnd.quark.quarkxpress',
'mxl' => 'application/vnd.recordare.musicxml',
'rm' => 'application/vnd.rn-realmedia',
'see' => 'application/vnd.seemail',
'sema' => 'application/vnd.sema',
'semd' => 'application/vnd.semd',
'semf' => 'application/vnd.semf',
'ifm' => 'application/vnd.shana.informed.formdata',
'itp' => 'application/vnd.shana.informed.formtemplate',
'iif' => 'application/vnd.shana.informed.interchange',
'ipk' => 'application/vnd.shana.informed.package',
'twd' => 'application/vnd.simtech-mindmapper',
'twds' => 'application/vnd.simtech-mindmapper',
'mmf' => 'application/vnd.smaf',
'sdkm' => 'application/vnd.solent.sdkm+xml',
'sdkd' => 'application/vnd.solent.sdkm+xml',
'dxp' => 'application/vnd.spotfire.dxp',
'sfs' => 'application/vnd.spotfire.sfs',
'sus' => 'application/vnd.sus-calendar',
'susp' => 'application/vnd.sus-calendar',
'svd' => 'application/vnd.svd',
'xsm' => 'application/vnd.syncml+xml',
'bdm' => 'application/vnd.syncml.dm+wbxml',
'xdm' => 'application/vnd.syncml.dm+xml',
'tao' => 'application/vnd.tao.intent-module-archive',
'tmo' => 'application/vnd.tmobile-livetv',
'tpt' => 'application/vnd.trid.tpt',
'mxs' => 'application/vnd.triscape.mxs',
'tra' => 'application/vnd.trueapp',
'ufd' => 'application/vnd.ufdl',
'ufdl' => 'application/vnd.ufdl',
'utz' => 'application/vnd.uiq.theme',
'umj' => 'application/vnd.umajin',
'unityweb' => 'application/vnd.unity',
'uoml' => 'application/vnd.uoml+xml',
'vcx' => 'application/vnd.vcx',
'vsd' => 'application/vnd.visio',
'vst' => 'application/vnd.visio',
'vss' => 'application/vnd.visio',
'vsw' => 'application/vnd.visio',
'vis' => 'application/vnd.visionary',
'vsf' => 'application/vnd.vsf',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'wtb' => 'application/vnd.webturbo',
'wpd' => 'application/vnd.wordperfect',
'wqd' => 'application/vnd.wqd',
'stf' => 'application/vnd.wt.stf',
'xar' => 'application/vnd.xara',
'xfdl' => 'application/vnd.xfdl',
'hvd' => 'application/vnd.yamaha.hv-dic',
'hvs' => 'application/vnd.yamaha.hv-script',
'hvp' => 'application/vnd.yamaha.hv-voice',
'saf' => 'application/vnd.yamaha.smaf-audio',
'spf' => 'application/vnd.yamaha.smaf-phrase',
'cmp' => 'application/vnd.yellowriver-custom-menu',
'zaz' => 'application/vnd.zzazz.deck+xml',
'vxml' => 'application/voicexml+xml',
'hlp' => 'application/winhlp',
'wsdl' => 'application/wsdl+xml',
'wspolicy' => 'application/wspolicy+xml',
'ace' => 'application/x-ace-compressed',
'bcpio' => 'application/x-bcpio',
'torrent' => 'application/x-bittorrent',
'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2',
'boz' => 'application/x-bzip2',
'vcd' => 'application/x-cdlink',
'chat' => 'application/x-chat',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'fgd' => 'application/x-director',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'jnlp' => 'application/x-java-jnlp-file',
'latex' => 'application/x-latex',
'wmd' => 'application/x-ms-wmd',
'wmz' => 'application/x-ms-wmz',
'mdb' => 'application/x-msaccess',
'obd' => 'application/x-msbinder',
'crd' => 'application/x-mscardfile',
'clp' => 'application/x-msclip',
'exe' => 'application/x-msdownload',
'dll' => 'application/x-msdownload',
'com' => 'application/x-msdownload',
'bat' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'mvb' => 'application/x-msmediaview',
'm13' => 'application/x-msmediaview',
'm14' => 'application/x-msmediaview',
'wmf' => 'application/x-msmetafile',
'mny' => 'application/x-msmoney',
'pub' => 'application/x-mspublisher',
'scd' => 'application/x-msschedule',
'trm' => 'application/x-msterminal',
'wri' => 'application/x-mswrite',
'nc' => 'application/x-netcdf',
'cdf' => 'application/x-netcdf',
'p12' => 'application/x-pkcs12',
'pfx' => 'application/x-pkcs12',
'p7b' => 'application/x-pkcs7-certificates',
'spc' => 'application/x-pkcs7-certificates',
'p7r' => 'application/x-pkcs7-certreqresp',
'rar' => 'application/x-rar-compressed',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sitx' => 'application/x-stuffitx',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texinfo' => 'application/x-texinfo',
'texi' => 'application/x-texinfo',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'der' => 'application/x-x509-ca-cert',
'crt' => 'application/x-x509-ca-cert',
'xenc' => 'application/xenc+xml',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'dtd' => 'application/xml-dtd',
'xop' => 'application/xop+xml',
'xslt' => 'application/xslt+xml',
'xspf' => 'application/xspf+xml',
'mxml' => 'application/xv+xml',
'xhvml' => 'application/xv+xml',
'xvml' => 'application/xv+xml',
'xvm' => 'application/xv+xml',
'zip' => 'application/zip',
'au' => 'audio/basic',
'snd' => 'audio/basic',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'kar' => 'audio/midi',
'rmi' => 'audio/midi',
'mp4a' => 'audio/mp4',
'm4a' => 'audio/mp4a-latm',
'm4p' => 'audio/mp4a-latm',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp2a' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'm2a' => 'audio/mpeg',
'm3a' => 'audio/mpeg',
'eol' => 'audio/vnd.digital-winds',
'lvp' => 'audio/vnd.lucent.voice',
'ecelp4800' => 'audio/vnd.nuera.ecelp4800',
'ecelp7470' => 'audio/vnd.nuera.ecelp7470',
'ecelp9600' => 'audio/vnd.nuera.ecelp9600',
'wav' => 'audio/wav',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'm3u' => 'audio/x-mpegurl',
'wax' => 'audio/x-ms-wax',
'wma' => 'audio/x-ms-wma',
'ram' => 'audio/x-pn-realaudio',
'ra' => 'audio/x-pn-realaudio',
'rmp' => 'audio/x-pn-realaudio-plugin',
'cdx' => 'chemical/x-cdx',
'cif' => 'chemical/x-cif',
'cmdf' => 'chemical/x-cmdf',
'cml' => 'chemical/x-cml',
'csml' => 'chemical/x-csml',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'cgm' => 'image/cgm',
'g3' => 'image/g3fax',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jp2' => 'image/jp2',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'pict' => 'image/pict',
'pic' => 'image/pict',
'pct' => 'image/pict',
'png' => 'image/png',
'btif' => 'image/prs.btif',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'psd' => 'image/vnd.adobe.photoshop',
'djvu' => 'image/vnd.djvu',
'djv' => 'image/vnd.djvu',
'dwg' => 'image/vnd.dwg',
'dxf' => 'image/vnd.dxf',
'fbs' => 'image/vnd.fastbidsheet',
'fpx' => 'image/vnd.fpx',
'fst' => 'image/vnd.fst',
'mmr' => 'image/vnd.fujixerox.edmics-mmr',
'rlc' => 'image/vnd.fujixerox.edmics-rlc',
'ico' => 'image/vnd.microsoft.icon',
'mdi' => 'image/vnd.ms-modi',
'npx' => 'image/vnd.net-fpx',
'wbmp' => 'image/vnd.wap.wbmp',
'xif' => 'image/vnd.xiff',
'ras' => 'image/x-cmu-raster',
'cmx' => 'image/x-cmx',
'pntg' => 'image/x-macpaint',
'pnt' => 'image/x-macpaint',
'mac' => 'image/x-macpaint',
'pcx' => 'image/x-pcx',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'qtif' => 'image/x-quicktime',
'qti' => 'image/x-quicktime',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'eml' => 'message/rfc822',
'mime' => 'message/rfc822',
'igs' => 'model/iges',
'iges' => 'model/iges',
'msh' => 'model/mesh',
'mesh' => 'model/mesh',
'silo' => 'model/mesh',
'dwf' => 'model/vnd.dwf',
'gdl' => 'model/vnd.gdl',
'gtw' => 'model/vnd.gtw',
'mts' => 'model/vnd.mts',
'vtu' => 'model/vnd.vtu',
'wrl' => 'model/vrml',
'vrml' => 'model/vrml',
'ics' => 'text/calendar',
'ifb' => 'text/calendar',
'css' => 'text/css',
'csv' => 'text/csv',
'html' => 'text/html',
'htm' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'conf' => 'text/plain',
'def' => 'text/plain',
'list' => 'text/plain',
'log' => 'text/plain',
'in' => 'text/plain',
'dsc' => 'text/prs.lines.tag',
'rtx' => 'text/richtext',
'sgml' => 'text/sgml',
'sgm' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
't' => 'text/troff',
'tr' => 'text/troff',
'roff' => 'text/troff',
'man' => 'text/troff',
'me' => 'text/troff',
'ms' => 'text/troff',
'uri' => 'text/uri-list',
'uris' => 'text/uri-list',
'urls' => 'text/uri-list',
'fly' => 'text/vnd.fly',
'flx' => 'text/vnd.fmi.flexstor',
'3dml' => 'text/vnd.in3d.3dml',
'spot' => 'text/vnd.in3d.spot',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
's' => 'text/x-asm',
'asm' => 'text/x-asm',
'c' => 'text/x-c',
'cc' => 'text/x-c',
'cxx' => 'text/x-c',
'cpp' => 'text/x-c',
'h' => 'text/x-c',
'hh' => 'text/x-c',
'dic' => 'text/x-c',
'f' => 'text/x-fortran',
'for' => 'text/x-fortran',
'f77' => 'text/x-fortran',
'f90' => 'text/x-fortran',
'p' => 'text/x-pascal',
'pas' => 'text/x-pascal',
'java' => 'text/x-java-source',
'etx' => 'text/x-setext',
'uu' => 'text/x-uuencode',
'vcs' => 'text/x-vcalendar',
'vcf' => 'text/x-vcard',
'3gp' => 'video/3gpp',
'3g2' => 'video/3gpp2',
'h261' => 'video/h261',
'h263' => 'video/h263',
'h264' => 'video/h264',
'jpgv' => 'video/jpeg',
'jpm' => 'video/jpm',
'jpgm' => 'video/jpm',
'mj2' => 'video/mj2',
'mjp2' => 'video/mj2',
'mp4' => 'video/mp4',
'mp4v' => 'video/mp4',
'mpg4' => 'video/mp4',
'm4v' => 'video/mp4',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'm1v' => 'video/mpeg',
'm2v' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'fvt' => 'video/vnd.fvt',
'mxu' => 'video/vnd.mpegurl',
'm4u' => 'video/vnd.mpegurl',
'viv' => 'video/vnd.vivo',
'dv' => 'video/x-dv',
'dif' => 'video/x-dv',
'fli' => 'video/x-fli',
'asx' => 'video/x-ms-asf',
'wm' => 'video/x-ms-wm',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wvx' => 'video/x-ms-wvx',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
];
/**
* Returns extensions for given mimes types
*
* @param array $mimesTypes The mimes types, e.g. ['video/mpeg', 'image/jpeg']
* @param bool $asUpperCase (optional) If is set to true, extensions are returned as upper case. Otherwise - lower
* case.
* @return array
*/
public static function getExtensions(array $mimesTypes, $asUpperCase = false)
{
if (empty($mimesTypes)) {
return [];
}
$extensions = [];
foreach ($mimesTypes as $mimeType) {
$extension = self::getExtension($mimeType);
/*
* No extension for given mime type?
* Nothing to do
*/
if (empty($extension)) {
continue;
}
/*
* Extensions should be returned as upper case?
*/
if ($asUpperCase) {
if (is_array($extension)) {
array_walk($extension, function (&$value) {
$value = strtoupper($value);
});
} else {
$extension = strtoupper($extension);
}
}
$extensions[$mimeType] = $extension;
}
return $extensions;
}
/**
* Returns extension for given mime type
*
* @param string $mimeType The mime type, e.g. "video/mpeg"
* @return string|array
*/
public static function getExtension($mimeType)
{
if (is_string($mimeType) && in_array($mimeType, self::$mimeTypes)) {
$data = Arrays::setKeysAsValues(self::$mimeTypes, false);
return $data[$mimeType];
}
return '';
}
/**
* Returns information whether file with the given path is an image
*
* @param string $path Path of the file to check
* @return bool
*/
public static function isImagePath($path)
{
$mimeType = self::getMimeType($path);
return self::isImage($mimeType);
}
/**
* Returns mime type of given file
*
* @param string $filePath Path of the file to check
* @throws \RuntimeException
* @return string
*/
public static function getMimeType($filePath)
{
/*
* The file does not exist?
* Nothing to do
*/
if (!is_string($filePath) || !is_readable($filePath)) {
return '';
}
/*
* 1st possibility: the finfo class
*/
if (class_exists('finfo')) {
$finfo = new \finfo();
return $finfo->file($filePath, FILEINFO_MIME_TYPE);
}
/*
* 2nd possibility: the mime_content_type function
*/
if (function_exists('mime_content_type')) {
return mime_content_type($filePath);
}
/*
* Oops, there is no possibility to read the mime type
*/
$template = 'Neither \'finfo\' class nor \'mime_content_type\' function exists. There is no way to read the'
. ' mime type of file \'%s\'.';
$message = sprintf($template, $filePath);
throw new \RuntimeException($message);
}
/**
* Returns information whether the given file type is an image
*
* @param string $mimeType The mime type of file
* @return bool
*/
public static function isImage($mimeType)
{
if (in_array($mimeType, self::$mimeTypes)) {
return (bool)preg_match('|^image/.+$|', $mimeType);
}
return false;
}
}

View File

@@ -9,26 +9,26 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
use Gedmo\Sluggable\Util\Urlizer; use Gedmo\Sluggable\Util\Urlizer;
use Symfony\Component\HttpFoundation\Cookie; use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException;
use Meritoo\Common\Exception\Regex\InvalidColorHexValueException;
use Transliterator; use Transliterator;
/** /**
* Miscellaneous methods (only static functions). * Miscellaneous methods (only static functions)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Miscellaneous class Miscellaneous
{ {
/** /**
* Returns directory's content (names of directories and files). * Returns directory's content (names of directories and files)
* *
* @param string $directoryPath Path of directory who content should be returned * @param string $directoryPath Path of directory who content should be returned
* @param bool $recursive (optional) If is set to true, sub-directories are also searched for content. * @param bool $recursive (optional) If is set to true, sub-directories are also searched for content.
* Otherwise - only content of given directory is returned. * Otherwise - only content of given directory is returned.
* @param int $maxFilesCount (optional) Maximum files that will be returned. If it's null, all files are * @param int $maxFilesCount (optional) Maximum files that will be returned. If it's null, all files are
* returned. * returned.
*
* @return array|null * @return array|null
*/ */
public static function getDirectoryContent($directoryPath, $recursive = false, $maxFilesCount = null) public static function getDirectoryContent($directoryPath, $recursive = false, $maxFilesCount = null)
@@ -66,7 +66,7 @@ class Miscellaneous
if (!empty($directoryContent)) { if (!empty($directoryContent)) {
foreach ($directoryContent as $fileName) { foreach ($directoryContent as $fileName) {
if ($fileName != '.' && $fileName != '..') { if ('.' != $fileName && '..' != $fileName) {
$content = null; $content = null;
if (!empty($startFileName) && !$startFileFound) { if (!empty($startFileName) && !$startFileFound) {
@@ -77,11 +77,11 @@ class Miscellaneous
continue; continue;
} }
if ($recursive && is_dir($directoryPath.$fileName)) { if ($recursive && is_dir($directoryPath . $fileName)) {
$content = self::getDirectoryContent($directoryPath.$fileName, true, $maxFilesCount - $count); $content = self::getDirectoryContent($directoryPath . $fileName, true, $maxFilesCount - $count);
} }
if ($content !== null) { if (null !== $content) {
$files[$fileName] = $content; $files[$fileName] = $content;
if (!empty($maxFilesCount)) { if (!empty($maxFilesCount)) {
@@ -106,10 +106,9 @@ class Miscellaneous
} }
/** /**
* Returns information if given path it's a file's path, if the path contains file name. * Returns information if given path it's a file's path, if the path contains file name
* *
* @param string $path The path to check * @param string $path The path to check
*
* @return bool * @return bool
*/ */
public static function isFilePath($path) public static function isFilePath($path)
@@ -120,16 +119,15 @@ class Miscellaneous
} }
/** /**
* Converts checkbox value to boolean. * Converts checkbox value to boolean
* *
* @param string $checkboxValue Checkbox value * @param string $checkboxValue Checkbox value
*
* @return bool * @return bool
*/ */
public static function checkboxValue2Boolean($checkboxValue) public static function checkboxValue2Boolean($checkboxValue)
{ {
$mapping = [ $mapping = [
'on' => true, 'on' => true,
'off' => false, 'off' => false,
]; ];
@@ -143,23 +141,21 @@ class Miscellaneous
} }
/** /**
* Converts checkbox value to integer. * Converts checkbox value to integer
* *
* @param string $checkboxValue Checkbox value * @param string $checkboxValue Checkbox value
*
* @return int * @return int
*/ */
public static function checkboxValue2Integer($checkboxValue) public static function checkboxValue2Integer($checkboxValue)
{ {
return (int) self::checkboxValue2Boolean($checkboxValue); return (int)self::checkboxValue2Boolean($checkboxValue);
} }
/** /**
* Returns name of file with given extension after verification if it contains the extension. * Returns name of file with given extension after verification if it contains the extension
* *
* @param string $fileName The file name to verify * @param string $fileName The file name to verify
* @param string $extension The extension to verify and include * @param string $extension The extension to verify and include
*
* @return string * @return string
*/ */
public static function includeFileExtension($fileName, $extension) public static function includeFileExtension($fileName, $extension)
@@ -172,11 +168,10 @@ class Miscellaneous
} }
/** /**
* Returns file extension. * Returns file extension
* *
* @param string $fileName File name * @param string $fileName File name
* @param bool $asLowerCase (optional) if true extension is returned as lowercase string * @param bool $asLowerCase (optional) if true extension is returned as lowercase string
*
* @return string * @return string
*/ */
public static function getFileExtension($fileName, $asLowerCase = false) public static function getFileExtension($fileName, $asLowerCase = false)
@@ -196,10 +191,9 @@ class Miscellaneous
} }
/** /**
* Returns file name from given path. * Returns file name from given path
* *
* @param string $path A path that contains file name * @param string $path A path that contains file name
*
* @return string * @return string
*/ */
public static function getFileNameFromPath($path) public static function getFileNameFromPath($path)
@@ -207,7 +201,7 @@ class Miscellaneous
$matches = []; $matches = [];
$pattern = sprintf('|([^\%s.]+\.[A-Za-z0-9.]+)$|', DIRECTORY_SEPARATOR); $pattern = sprintf('|([^\%s.]+\.[A-Za-z0-9.]+)$|', DIRECTORY_SEPARATOR);
if ((bool) preg_match($pattern, $path, $matches)) { if ((bool)preg_match($pattern, $path, $matches)) {
return $matches[1]; return $matches[1];
} }
@@ -215,12 +209,11 @@ class Miscellaneous
} }
/** /**
* Returns unique name for file based on given original name. * Returns unique name for file based on given original name
* *
* @param string $originalFileName Original name of the file * @param string $originalFileName Original name of the file
* @param int $objectId (optional) Object ID, the ID of database's row. May be included into the * @param int $objectId (optional) Object ID, the ID of database's row. May be included into the
* generated / unique name. * generated / unique name.
*
* @return string * @return string
*/ */
public static function getUniqueFileName($originalFileName, $objectId = 0) public static function getUniqueFileName($originalFileName, $objectId = 0)
@@ -268,17 +261,16 @@ class Miscellaneous
} }
/** /**
* Returns file name without extension. * Returns file name without extension
* *
* @param string $fileName The file name * @param string $fileName The file name
*
* @return string * @return string
*/ */
public static function getFileNameWithoutExtension($fileName) public static function getFileNameWithoutExtension($fileName)
{ {
$matches = []; $matches = [];
if (is_string($fileName) && (bool) preg_match('|(.+)\.(.+)|', $fileName, $matches)) { if (is_string($fileName) && (bool)preg_match('|(.+)\.(.+)|', $fileName, $matches)) {
return $matches[1]; return $matches[1];
} }
@@ -286,16 +278,15 @@ class Miscellaneous
} }
/** /**
* Converts value to non-negative integer (element of the set {0, 1, 2, 3, ...}). * Converts value to non-negative integer (element of the set {0, 1, 2, 3, ...})
* *
* @param mixed $value Value to convert * @param mixed $value Value to convert
* @param int $negativeReplacement (optional) Replacement for negative value * @param int $negativeReplacement (optional) Replacement for negative value
*
* @return int * @return int
*/ */
public static function value2NonNegativeInteger($value, $negativeReplacement = 0) public static function value2NonNegativeInteger($value, $negativeReplacement = 0)
{ {
$effect = (int) $value; $effect = (int)$value;
if ($effect < 0) { if ($effect < 0) {
return $negativeReplacement; return $negativeReplacement;
@@ -305,7 +296,7 @@ class Miscellaneous
} }
/** /**
* Displays variable content as preformatted text (fixed-width font and preserves both spaces and line breaks). * Displays variable content as preformatted text (fixed-width font and preserves both spaces and line breaks)
* *
* If xdebug php module is loaded, displays variable using var_dump(), otherwise <pre>var_dump()</pre>. * If xdebug php module is loaded, displays variable using var_dump(), otherwise <pre>var_dump()</pre>.
* You can pass as many variables as you wish. * You can pass as many variables as you wish.
@@ -333,10 +324,9 @@ class Miscellaneous
} }
/** /**
* Returns information if given PHP module is compiled and loaded. * Returns information if given PHP module is compiled and loaded
* *
* @param string $phpModuleName PHP module name * @param string $phpModuleName PHP module name
*
* @return bool * @return bool
*/ */
public static function isPhpModuleLoaded($phpModuleName) public static function isPhpModuleLoaded($phpModuleName)
@@ -347,14 +337,13 @@ class Miscellaneous
} }
/** /**
* Converts given string characters to latin characters. * Converts given string characters to latin characters
* *
* @param string $string String to convert * @param string $string String to convert
* @param bool $lowerCaseHuman (optional) If is set to true, converted string is returned as lowercase and * @param bool $lowerCaseHuman (optional) If is set to true, converted string is returned as lowercase and
* human-readable. Otherwise - as original. * human-readable. Otherwise - as original.
* @param string $replacementChar (optional) Replacement character for all non-latin characters and uppercase * @param string $replacementChar (optional) Replacement character for all non-latin characters and uppercase
* letters, if 2nd argument is set to true * letters, if 2nd argument is set to true
*
* @return string * @return string
*/ */
public static function toLatin($string, $lowerCaseHuman = true, $replacementChar = '-') public static function toLatin($string, $lowerCaseHuman = true, $replacementChar = '-')
@@ -377,7 +366,7 @@ class Miscellaneous
* Oops, cannot instantiate converter * Oops, cannot instantiate converter
* Nothing to do * Nothing to do
*/ */
if ($converter === null) { if (null === $converter) {
return ''; return '';
} }
@@ -406,12 +395,11 @@ class Miscellaneous
} }
/** /**
* Returns unique string. * Returns unique string
* *
* @param string $prefix (optional) Prefix of the unique string. May be used while generating the unique * @param string $prefix (optional) Prefix of the unique string. May be used while generating the unique
* string simultaneously on several hosts at the same microsecond. * string simultaneously on several hosts at the same microsecond.
* @param bool $hashed (optional) If is set to true, the unique string is hashed additionally. Otherwise - not. * @param bool $hashed (optional) If is set to true, the unique string is hashed additionally. Otherwise - not.
*
* @return string * @return string
*/ */
public static function getUniqueString($prefix = '', $hashed = false) public static function getUniqueString($prefix = '', $hashed = false)
@@ -435,7 +423,6 @@ class Miscellaneous
* @param string|array $replacement The string or an array of strings to replace. It may be: string or an array * @param string|array $replacement The string or an array of strings to replace. It may be: string or an array
* of strings. * of strings.
* @param bool $quoteStrings (optional) If is set to true, strings are surrounded with single quote sign * @param bool $quoteStrings (optional) If is set to true, strings are surrounded with single quote sign
*
* @return string * @return string
* *
* Example: * Example:
@@ -474,7 +461,7 @@ class Miscellaneous
* Value to find is neither a string nor an array OR it's an empty string? * Value to find is neither a string nor an array OR it's an empty string?
* Nothing to do * Nothing to do
*/ */
if ((!$searchIsString && !$searchIsArray) || ($searchIsString && strlen($search) == 0)) { if ((!$searchIsString && !$searchIsArray) || ($searchIsString && 0 == strlen($search))) {
return $effect; return $effect;
} }
@@ -489,7 +476,7 @@ class Miscellaneous
*/ */
if ($searchIsString && $replacementIsString) { if ($searchIsString && $replacementIsString) {
if ($quoteStrings) { if ($quoteStrings) {
$replacement = '\''.$replacement.'\''; $replacement = '\'' . $replacement . '\'';
} }
$effect = str_replace($search, $replacement, $subject); $effect = str_replace($search, $replacement, $subject);
@@ -501,7 +488,7 @@ class Miscellaneous
*/ */
if ($effect == $subject && ($bothAreStrings || $bothAreArrays)) { if ($effect == $subject && ($bothAreStrings || $bothAreArrays)) {
if ($quoteStrings && $replacementIsString) { if ($quoteStrings && $replacementIsString) {
$replacement = '\''.$replacement.'\''; $replacement = '\'' . $replacement . '\'';
} }
/* /*
@@ -543,7 +530,7 @@ class Miscellaneous
if ($quoteStrings) { if ($quoteStrings) {
foreach ($replacement as &$item) { foreach ($replacement as &$item) {
if (is_string($item)) { if (is_string($item)) {
$item = '\''.$item.'\''; $item = '\'' . $item . '\'';
} }
} }
@@ -563,7 +550,6 @@ class Miscellaneous
if ($subjectIsArray) { if ($subjectIsArray) {
$effect[] = $subEffect; $effect[] = $subEffect;
continue; continue;
} }
@@ -575,12 +561,11 @@ class Miscellaneous
} }
/** /**
* Returns new file name after adding prefix or suffix (or both of them) to the name. * Returns new file name after adding prefix or suffix (or both of them) to the name
* *
* @param string $fileName The file name * @param string $fileName The file name
* @param string $prefix File name prefix * @param string $prefix File name prefix
* @param string $suffix File name suffix * @param string $suffix File name suffix
*
* @return string * @return string
*/ */
public static function getNewFileName($fileName, $prefix, $suffix) public static function getNewFileName($fileName, $prefix, $suffix)
@@ -598,7 +583,7 @@ class Miscellaneous
} }
/** /**
* Returns operating system name PHP is running on. * Returns operating system name PHP is running on
* *
* @return string * @return string
*/ */
@@ -608,12 +593,11 @@ class Miscellaneous
} }
/** /**
* Returns part of string preserving words. * Returns part of string preserving words
* *
* @param string $text The string / text * @param string $text The string / text
* @param int $maxLength Maximum length of given string * @param int $maxLength Maximum length of given string
* @param string $suffix (optional) The suffix to add at the end of string * @param string $suffix (optional) The suffix to add at the end of string
*
* @return string * @return string
*/ */
public static function substringToWord($text, $maxLength, $suffix = '...') public static function substringToWord($text, $maxLength, $suffix = '...')
@@ -629,7 +613,7 @@ class Miscellaneous
$effect = mb_substr($text, 0, $maxLength, 'utf-8'); $effect = mb_substr($text, 0, $maxLength, 'utf-8');
$lastSpacePosition = mb_strrpos($effect, ' ', 'utf-8'); $lastSpacePosition = mb_strrpos($effect, ' ', 'utf-8');
if ($lastSpacePosition !== false) { if (false !== $lastSpacePosition) {
$effect = mb_substr($effect, 0, $lastSpacePosition, 'utf-8'); $effect = mb_substr($effect, 0, $lastSpacePosition, 'utf-8');
} }
@@ -640,14 +624,13 @@ class Miscellaneous
} }
/** /**
* Breaks long text. * Breaks long text
* *
* @param string $text The text to check and break * @param string $text The text to check and break
* @param int $perLine (optional) Characters count per line * @param int $perLine (optional) Characters count per line. Default: 100.
* @param string $separator (optional) Separator that is placed beetwen lines * @param string $separator (optional) Separator that is placed between lines. Default: "<br>".
* @param string $encoding (optional) Character encoding. Used by mb_substr(). * @param string $encoding (optional) Character encoding. Used by mb_substr(). Default: "UTF-8".
* @param int $proportionalAberration (optional) Proportional aberration for chars (percent value) * @param int $proportionalAberration (optional) Proportional aberration for chars (percent value). Default: 20.
*
* @return string * @return string
*/ */
public static function breakLongText( public static function breakLongText(
@@ -734,30 +717,40 @@ class Miscellaneous
* *
* @param string $directoryPath Directory path * @param string $directoryPath Directory path
* @param bool $contentOnly (optional) If is set to true, only content of the directory is removed, not * @param bool $contentOnly (optional) If is set to true, only content of the directory is removed, not
* directory. Otherwise - directory is removed too. * directory itself. Otherwise - directory is removed too (default behaviour).
* * @return bool|null
* @return bool
*/ */
public static function removeDirectory($directoryPath, $contentOnly = false) public static function removeDirectory($directoryPath, $contentOnly = false)
{ {
/*
* Directory does not exist?
* Nothing to do
*/
if (!file_exists($directoryPath)) { if (!file_exists($directoryPath)) {
return true; return null;
} }
/*
* It's not a directory?
* Let's treat it like file
*/
if (!is_dir($directoryPath)) { if (!is_dir($directoryPath)) {
return unlink($directoryPath); return unlink($directoryPath);
} }
foreach (scandir($directoryPath) as $item) { foreach (scandir($directoryPath) as $item) {
if ($item == '.' || $item == '..') { if ('.' == $item || '..' == $item) {
continue; continue;
} }
if (!self::removeDirectory($directoryPath.DIRECTORY_SEPARATOR.$item)) { if (!self::removeDirectory($directoryPath . DIRECTORY_SEPARATOR . $item)) {
return false; return false;
} }
} }
/*
* Directory should be removed too?
*/
if (!$contentOnly) { if (!$contentOnly) {
return rmdir($directoryPath); return rmdir($directoryPath);
} }
@@ -766,23 +759,21 @@ class Miscellaneous
} }
/** /**
* Returns information if value is decimal. * Returns information if value is decimal
* *
* @param mixed $value The value to check * @param mixed $value The value to check
*
* @return bool * @return bool
*/ */
public static function isDecimal($value) public static function isDecimal($value)
{ {
return is_scalar($value) && floor($value) !== (float) $value; return is_scalar($value) && floor($value) !== (float)$value;
} }
/** /**
* Returns the string in camel case. * Returns the string in camel case
* *
* @param string $string The string to convert e.g. this-is-eXamplE (return: thisIsExample) * @param string $string The string to convert e.g. this-is-eXamplE (return: thisIsExample)
* @param string $separator (optional) Separator used to find parts of the string, e.g. '-' or ',' * @param string $separator (optional) Separator used to find parts of the string, e.g. '-' or ','
*
* @return string * @return string
*/ */
public static function getCamelCase($string, $separator = ' ') public static function getCamelCase($string, $separator = ' ')
@@ -797,7 +788,7 @@ class Miscellaneous
foreach ($members as $key => $value) { foreach ($members as $key => $value) {
$value = mb_strtolower($value); $value = mb_strtolower($value);
if ($key == 0) { if (0 == $key) {
$effect .= self::lowercaseFirst($value); $effect .= self::lowercaseFirst($value);
} else { } else {
$effect .= self::uppercaseFirst($value); $effect .= self::uppercaseFirst($value);
@@ -808,11 +799,10 @@ class Miscellaneous
} }
/** /**
* Make a string's first character lowercase. * Make a string's first character lowercase
* *
* @param string $text The text to get first character lowercase * @param string $text The text to get first character lowercase
* @param bool|null $restLowercase (optional) Information that to do with rest of given string * @param bool|null $restLowercase (optional) Information that to do with rest of given string
*
* @return string * @return string
* *
* Values of the $restLowercase argument: * Values of the $restLowercase argument:
@@ -834,7 +824,7 @@ class Miscellaneous
if ($restLowercase) { if ($restLowercase) {
$effect = mb_strtolower($effect); $effect = mb_strtolower($effect);
} elseif ($restLowercase === false) { } elseif (false === $restLowercase) {
$effect = mb_strtoupper($effect); $effect = mb_strtoupper($effect);
} }
@@ -844,18 +834,17 @@ class Miscellaneous
$first = mb_strtolower($effect[0]); $first = mb_strtolower($effect[0]);
$rest = mb_substr($effect, 1); $rest = mb_substr($effect, 1);
$effect = $first.$rest; $effect = $first . $rest;
} }
return $effect; return $effect;
} }
/** /**
* Make a string's first character uppercase. * Make a string's first character uppercase
* *
* @param string $text The text to get uppercase * @param string $text The text to get uppercase
* @param bool|null $restLowercase (optional) Information that to do with rest of given string * @param bool|null $restLowercase (optional) Information that to do with rest of given string
*
* @return string * @return string
* *
* Values of the $restLowercase argument: * Values of the $restLowercase argument:
@@ -873,7 +862,7 @@ class Miscellaneous
if ($restLowercase) { if ($restLowercase) {
$effect = mb_strtolower($effect); $effect = mb_strtolower($effect);
} elseif ($restLowercase === false) { } elseif (false === $restLowercase) {
$effect = mb_strtoupper($effect); $effect = mb_strtoupper($effect);
} }
@@ -883,18 +872,17 @@ class Miscellaneous
$first = mb_strtoupper($effect[0]); $first = mb_strtoupper($effect[0]);
$rest = mb_substr($effect, 1); $rest = mb_substr($effect, 1);
$effect = $first.$rest; $effect = $first . $rest;
} }
return $effect; return $effect;
} }
/** /**
* Quotes given value with apostrophes or quotation marks. * Quotes given value with apostrophes or quotation marks
* *
* @param mixed $value The value to quote * @param mixed $value The value to quote
* @param bool $useApostrophe (optional) If is set to true, apostrophes are used. Otherwise - quotation marks. * @param bool $useApostrophe (optional) If is set to true, apostrophes are used. Otherwise - quotation marks.
*
* @return string * @return string
*/ */
public static function quoteValue($value, $useApostrophe = true) public static function quoteValue($value, $useApostrophe = true)
@@ -913,10 +901,9 @@ class Miscellaneous
} }
/** /**
* Returns size (of file or directory) in human readable format. * Returns size (of file or directory) in human readable format
* *
* @param int $sizeInBytes The size in bytes * @param int $sizeInBytes The size in bytes
*
* @return string * @return string
*/ */
public static function getHumanReadableSize($sizeInBytes) public static function getHumanReadableSize($sizeInBytes)
@@ -932,7 +919,7 @@ class Miscellaneous
$index = floor(log($sizeInBytes, 1024)); $index = floor(log($sizeInBytes, 1024));
$size = round($sizeInBytes / pow(1024, $index), 2); $size = round($sizeInBytes / pow(1024, $index), 2);
$unit = $units[(int) $index]; $unit = $units[(int)$index];
return sprintf('%s %s', $size, $unit); return sprintf('%s %s', $size, $unit);
} }
@@ -943,7 +930,6 @@ class Miscellaneous
* *
* @param string $string The string to check * @param string $string The string to check
* @param string $separator The separator which divides elements of string * @param string $separator The separator which divides elements of string
*
* @return string * @return string
*/ */
public static function getStringWithoutLastElement($string, $separator) public static function getStringWithoutLastElement($string, $separator)
@@ -957,11 +943,10 @@ class Miscellaneous
} }
/** /**
* Returns elements of given string divided by given separator. * Returns elements of given string divided by given separator
* *
* @param string $string The string to check * @param string $string The string to check
* @param string $separator The separator which divides elements of string * @param string $separator The separator which divides elements of string
*
* @return array * @return array
*/ */
public static function getStringElements($string, $separator) public static function getStringElements($string, $separator)
@@ -978,11 +963,10 @@ class Miscellaneous
} }
/** /**
* Returns the last element of given string divided by given separator. * Returns the last element of given string divided by given separator
* *
* @param string $string The string to check * @param string $string The string to check
* @param string $separator The separator which divides elements of string * @param string $separator The separator which divides elements of string
*
* @return string|null * @return string|null
*/ */
public static function getLastElementOfString($string, $separator) public static function getLastElementOfString($string, $separator)
@@ -1007,7 +991,6 @@ class Miscellaneous
* If the string is empty, contains only spaces, e.g. " ", nothing is done and the original string is returned. * If the string is empty, contains only spaces, e.g. " ", nothing is done and the original string is returned.
* *
* @param string $string The string to trim * @param string $string The string to trim
*
* @return string * @return string
*/ */
public static function trimSmart($string) public static function trimSmart($string)
@@ -1022,7 +1005,7 @@ class Miscellaneous
} }
/** /**
* Returns concatenated given paths. * Returns concatenated given paths
* *
* The paths may be passed as: * The paths may be passed as:
* - an array of paths / strings * - an array of paths / strings
@@ -1034,7 +1017,6 @@ class Miscellaneous
* *
* @param string|array $paths Paths co concatenate. As described above: an array of paths / strings or strings * @param string|array $paths Paths co concatenate. As described above: an array of paths / strings or strings
* passed as following arguments. * passed as following arguments.
*
* @return string * @return string
*/ */
public static function concatenatePaths($paths) public static function concatenatePaths($paths)
@@ -1062,6 +1044,8 @@ class Miscellaneous
$separator = DIRECTORY_SEPARATOR; $separator = DIRECTORY_SEPARATOR;
foreach ($paths as $path) { foreach ($paths as $path) {
$path = trim($path);
/* /*
* Empty paths are useless * Empty paths are useless
*/ */
@@ -1097,7 +1081,6 @@ class Miscellaneous
*/ */
if ($firstWindowsBased && empty($concatenated)) { if ($firstWindowsBased && empty($concatenated)) {
$concatenated = $path; $concatenated = $path;
continue; continue;
} }
@@ -1111,12 +1094,11 @@ class Miscellaneous
} }
/** /**
* Removes the starting / beginning directory's separator. * Removes the starting / beginning directory's separator
* *
* @param string $text Text that may contain a directory's separator at the start / beginning * @param string $text Text that may contain a directory's separator at the start / beginning
* @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), separator * @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), separator
* provided by operating system will be used. * provided by operating system will be used.
*
* @return string * @return string
*/ */
public static function removeStartingDirectorySeparator($text, $separator = '') public static function removeStartingDirectorySeparator($text, $separator = '')
@@ -1143,12 +1125,11 @@ class Miscellaneous
} }
/** /**
* Removes the ending directory's separator. * Removes the ending directory's separator
* *
* @param string $text Text that may contain a directory's separator at the end * @param string $text Text that may contain a directory's separator at the end
* @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), system's * @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), system's
* separator is used. * separator is used.
*
* @return string * @return string
*/ */
public static function removeEndingDirectorySeparator($text, $separator = '') public static function removeEndingDirectorySeparator($text, $separator = '')
@@ -1175,49 +1156,43 @@ class Miscellaneous
} }
/** /**
* Returns safely value of global variable, found in one of the global arrays / variables, e.g. $_GET. * Returns safely value of global variable, found in one of the global arrays / variables, e.g. $_GET
* *
* @param int $globalSourceType Represents the global array / variable. One of constants: INPUT_GET, INPUT_POST, * @param int $globalSourceType Represents the global array / variable. One of constants: INPUT_GET, INPUT_POST,
* INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV. * INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV.
* @param string $variableName Name of the variable to return value * @param string $variableName Name of the variable to return value
*
* @return mixed * @return mixed
*/ */
public static function getSafelyGlobalVariable($globalSourceType, $variableName) public static function getSafelyGlobalVariable($globalSourceType, $variableName)
{ {
$value = filter_input($globalSourceType, $variableName); $value = filter_input($globalSourceType, $variableName);
if ($value === null) { if (null === $value) {
$globalSource = null; $globalSource = null;
switch ($globalSourceType) { switch ($globalSourceType) {
case INPUT_GET: case INPUT_GET:
$globalSource = $_GET; $globalSource = $_GET;
break; break;
case INPUT_POST: case INPUT_POST:
$globalSource = $_POST; $globalSource = $_POST;
break; break;
case INPUT_COOKIE: case INPUT_COOKIE:
$globalSource = $_COOKIE; $globalSource = $_COOKIE;
break; break;
case INPUT_SERVER: case INPUT_SERVER:
$globalSource = $_SERVER; $globalSource = $_SERVER;
break; break;
case INPUT_ENV: case INPUT_ENV:
$globalSource = $_ENV; $globalSource = $_ENV;
break; break;
} }
if ($globalSource !== null && isset($globalSource[$variableName])) { if (null !== $globalSource && isset($globalSource[$variableName])) {
$value = $globalSource[$variableName]; $value = $globalSource[$variableName];
if (!ini_get('magic_quotes_gpc')) { if (!ini_get('magic_quotes_gpc')) {
@@ -1230,147 +1205,7 @@ class Miscellaneous
} }
/** /**
* Returns a CURL response with parsed HTTP headers as array with "headers", "cookies" and "content" keys. * Adds missing the "0" characters to given number until given length is reached
*
* The headers and cookies are parsed and returned as an array, and an array of Cookie objects. Returned array looks
* like this example:
* <code>
* [
* 'headers' => [
* 'Content-Type' => 'text/html; charset=UTF-8',
* ...
* ],
* 'cookies' => [
* new Symfony\Component\HttpFoundation\Cookie(),
* new Symfony\Component\HttpFoundation\Cookie(),
* ...
* ],
* 'content' => '<html>...</html>'
* ]
* </code>
*
* If you want to attach HTTP headers into response content by CURL you need to set "CURLOPT_HEADER" option
* to "true". To read exact length of HTTP headers from CURL you can use "curl_getinfo()" function
* and read "CURLINFO_HEADER_SIZE" option.
*
* @param string $response the full content of response, including HTTP headers
* @param int $headerSize The length of HTTP headers in content
*
* @return array
*/
public static function getCurlResponseWithHeaders($response, $headerSize)
{
$headerContent = mb_substr($response, 0, $headerSize);
$content = mb_substr($response, $headerSize);
$headers = [];
$cookies = [];
/*
* Let's transform headers content into two arrays: headers and cookies
*/
foreach (explode("\r\n", $headerContent) as $i => $line) {
/*
* First line is only HTTP status and is unneeded so skip it
*/
if ($i === 0) {
continue;
}
if (Regex::contains($line, ':')) {
list($key, $value) = explode(': ', $line);
/*
* If the header is a "set-cookie" let's save it to "cookies" array
*/
if ($key === 'Set-Cookie') {
$cookieParameters = explode(';', $value);
$name = '';
$value = '';
$expire = 0;
$path = '/';
$domain = null;
$secure = false;
$httpOnly = true;
foreach ($cookieParameters as $j => $parameter) {
$param = explode('=', $parameter);
/*
* First parameter will be always a cookie name and it's value. It is not needed to run
* further actions for them, so save the values and move to next parameter.
*/
if ($j === 0) {
$name = trim($param[0]);
$value = trim($param[1]);
continue;
}
/*
* Now there would be the rest of cookie parameters, names of params are sent different way so
* I need to lowercase the names and remove unneeded spaces.
*/
$paramName = mb_strtolower(trim($param[0]));
$paramValue = true;
/*
* Some parameters don't have value e.g. "secure", but the value for them if they're specified
* is "true". Otherwise - just read a value for parameter if exists.
*/
if (array_key_exists(1, $param)) {
$paramValue = trim($param[1]);
}
switch ($paramName) {
case 'expires':
$expire = $paramValue;
break;
case 'path':
$path = $paramValue;
break;
case 'domain':
$domain = $paramValue;
break;
case 'secure':
$secure = $paramValue;
break;
case 'httponly':
$httpOnly = $paramValue;
break;
}
}
/*
* Create new Cookie object and add it to "cookies" array.
* I must skip to next header as cookies shouldn't be saved in "headers" array.
*/
$cookies[] = new Cookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
continue;
}
/*
* Save response header which is not a cookie
*/
$headers[$key] = $value;
}
}
return [
'headers' => $headers,
'cookies' => $cookies,
'content' => $content,
];
}
/**
* Adds missing the "0" characters to given number until given length is reached.
* *
* Example: * Example:
* - number: 201 * - number: 201
@@ -1383,7 +1218,6 @@ class Miscellaneous
* @param mixed $number Number for who the "0" characters should be inserted * @param mixed $number Number for who the "0" characters should be inserted
* @param int $length Wanted length of final number * @param int $length Wanted length of final number
* @param bool $before (optional) If false, 0 characters will be inserted after given number * @param bool $before (optional) If false, 0 characters will be inserted after given number
*
* @return string * @return string
*/ */
public static function fillMissingZeros($number, $length, $before = true) public static function fillMissingZeros($number, $length, $before = true)
@@ -1405,24 +1239,22 @@ class Miscellaneous
for ($i = ($length - $textLength); 0 < $i; --$i) { for ($i = ($length - $textLength); 0 < $i; --$i) {
if ($before) { if ($before) {
$text = '0'.$text; $text = '0' . $text;
continue; continue;
} }
$text = $text.'0'; $text = $text . '0';
} }
return $text; return $text;
} }
/** /**
* Returns information if given value is located in interval between given utmost left and right values. * Returns information if given value is located in interval between given utmost left and right values
* *
* @param int|float $value Value to verify * @param int|float $value Value to verify
* @param int|float $left Left utmost value of interval * @param int|float $left Left utmost value of interval
* @param int|float $right Right utmost value of interval * @param int|float $right Right utmost value of interval
*
* @return bool * @return bool
*/ */
public static function isBetween($value, $left, $right) public static function isBetween($value, $left, $right)
@@ -1435,7 +1267,6 @@ class Miscellaneous
* If it's an object, full class name is returned. * If it's an object, full class name is returned.
* *
* @param mixed $variable Variable who type should be returned * @param mixed $variable Variable who type should be returned
*
* @return string * @return string
*/ */
public static function getType($variable) public static function getType($variable)
@@ -1454,12 +1285,11 @@ class Miscellaneous
* @param int $colorComponent Color's component to verify. Decimal value, e.g. 255. * @param int $colorComponent Color's component to verify. Decimal value, e.g. 255.
* @param bool $asHexadecimal (optional) If is set to true, hexadecimal value is returned (default behaviour). * @param bool $asHexadecimal (optional) If is set to true, hexadecimal value is returned (default behaviour).
* Otherwise - decimal. * Otherwise - decimal.
*
* @return int|string * @return int|string
*/ */
public static function getValidColorComponent($colorComponent, $asHexadecimal = true) public static function getValidColorComponent($colorComponent, $asHexadecimal = true)
{ {
$colorComponent = (int) $colorComponent; $colorComponent = (int)$colorComponent;
if ($colorComponent < 0 || $colorComponent > 255) { if ($colorComponent < 0 || $colorComponent > 255) {
$colorComponent = 0; $colorComponent = 0;
@@ -1468,7 +1298,7 @@ class Miscellaneous
if ($asHexadecimal) { if ($asHexadecimal) {
$hexadecimal = dechex($colorComponent); $hexadecimal = dechex($colorComponent);
if (strlen($hexadecimal) == 1) { if (1 == strlen($hexadecimal)) {
return sprintf('0%s', $hexadecimal, $hexadecimal); return sprintf('0%s', $hexadecimal, $hexadecimal);
} }
@@ -1479,10 +1309,11 @@ class Miscellaneous
} }
/** /**
* Returns inverted value of color for given color. * Returns inverted value of color for given color
* *
* @param string $color Hexadecimal value of color to invert (with or without hash), e.g. "dd244c" or "#22a5fe" * @param string $color Hexadecimal value of color to invert (with or without hash), e.g. "dd244c" or "#22a5fe"
* * @throws IncorrectColorHexLengthException
* @throws InvalidColorHexValueException
* @return string * @return string
*/ */
public static function getInvertedColor($color) public static function getInvertedColor($color)
@@ -1524,4 +1355,37 @@ class Miscellaneous
return $invertedColor; return $invertedColor;
} }
/**
* Returns project's root path.
* Looks for directory that contains composer.json.
*
* @return string
*/
public static function getProjectRootPath()
{
$projectRootPath = '';
$fileName = 'composer.json';
$directoryPath = __DIR__;
/*
* Path of directory it's not the path of last directory?
*/
while (DIRECTORY_SEPARATOR !== $directoryPath) {
$filePath = static::concatenatePaths($directoryPath, $fileName);
/*
* Is here file we are looking for?
* Maybe it's a project's root path
*/
if (file_exists($filePath)) {
$projectRootPath = $directoryPath;
}
$directoryPath = dirname($directoryPath);
}
return $projectRootPath;
}
} }

View File

@@ -10,15 +10,16 @@ namespace Meritoo\Common\Utilities;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManager; use Doctrine\ORM\EntityManager;
use Doctrine\ORM\OptimisticLockException;
use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\Query\Parameter; use Doctrine\ORM\Query\Parameter;
use Doctrine\ORM\QueryBuilder; use Doctrine\ORM\QueryBuilder;
/** /**
* Useful methods for query builder (the Doctrine's QueryBuilder class). * Useful methods for query builder (the Doctrine's QueryBuilder class)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class QueryBuilderUtility class QueryBuilderUtility
{ {
@@ -27,13 +28,16 @@ class QueryBuilderUtility
* If null is returned, alias was not found. * If null is returned, alias was not found.
* *
* @param QueryBuilder $queryBuilder The query builder to retrieve root alias * @param QueryBuilder $queryBuilder The query builder to retrieve root alias
*
* @return null|string * @return null|string
*/ */
public static function getRootAlias(QueryBuilder $queryBuilder) public static function getRootAlias(QueryBuilder $queryBuilder)
{ {
$aliases = $queryBuilder->getRootAliases(); $aliases = $queryBuilder->getRootAliases();
/*
* No aliases?
* Nothing to do
*/
if (empty($aliases)) { if (empty($aliases)) {
return null; return null;
} }
@@ -43,18 +47,22 @@ class QueryBuilderUtility
/** /**
* Returns alias of given property joined in given query builder * 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. * It's also information if given property is already joined in given query builder.
* *
* @param QueryBuilder $queryBuilder The query builder to verify * @param QueryBuilder $queryBuilder The query builder to verify
* @param string $property Name of property that maybe is joined * @param string $property Name of property that maybe is joined
*
* @return null|string * @return null|string
*/ */
public static function getJoinedPropertyAlias(QueryBuilder $queryBuilder, $property) public static function getJoinedPropertyAlias(QueryBuilder $queryBuilder, $property)
{ {
$joins = $queryBuilder->getDQLPart('join'); $joins = $queryBuilder->getDQLPart('join');
/*
* No joins?
* Nothing to do
*/
if (empty($joins)) { if (empty($joins)) {
return null; return null;
} }
@@ -77,14 +85,13 @@ class QueryBuilderUtility
} }
/** /**
* Sets the WHERE criteria in given query builder. * Sets the WHERE criteria in given query builder
* *
* @param QueryBuilder $queryBuilder The query builder * @param QueryBuilder $queryBuilder The query builder
* @param array $criteria (optional) The criteria used in WHERE clause. It may simple array with pairs * @param array $criteria (optional) The criteria used in WHERE clause. It may simple array with pairs
* key-value or an array of arrays where second element of sub-array is the * key-value or an array of arrays where second element of sub-array is the
* comparison operator. Example below. * comparison operator. Example below.
* @param string $alias (optional) Alias used in the query * @param string $alias (optional) Alias used in the query
*
* @return QueryBuilder * @return QueryBuilder
* *
* Example of the $criteria argument: * Example of the $criteria argument:
@@ -102,52 +109,62 @@ class QueryBuilderUtility
*/ */
public static function setCriteria(QueryBuilder $queryBuilder, array $criteria = [], $alias = '') public static function setCriteria(QueryBuilder $queryBuilder, array $criteria = [], $alias = '')
{ {
if (!empty($criteria)) { /*
if (empty($alias)) { * No criteria used in WHERE clause?
$alias = self::getRootAlias($queryBuilder); * 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)) { foreach ($criteria as $column => $value) {
if (count($value) == 2) { $compareOperator = '=';
$compareOperator = $value[1];
}
$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); $value = $value[0];
if ($value === null) {
$predicate = $queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $column));
unset($criteria[$column]);
} else {
$queryBuilder->setParameter($column, $value);
}
$queryBuilder = $queryBuilder->andWhere($predicate);
} }
$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; return $queryBuilder;
} }
/** /**
* Deletes given entities. * Deletes given entities
* *
* @param EntityManager $entityManager The entity manager * @param EntityManager $entityManager The entity manager
* @param array|ArrayCollection $entities The entities to delete * @param array|ArrayCollection $entities The entities to delete
* @param bool $flushDeleted (optional) If is set to true, flushes the deleted objects. * @param bool $flushDeleted (optional) If is set to true, flushes the deleted objects (default
* Otherwise - not. * behaviour). Otherwise - not.
* * @throws OptimisticLockException
* @return bool * @return bool
*/ */
public static function deleteEntities(EntityManager $entityManager, $entities, $flushDeleted = true) public static function deleteEntities(EntityManager $entityManager, $entities, $flushDeleted = true)
{ {
/* /*
* No entities found? * No entities provided?
* Nothing to do * Nothing to do
*/ */
if (empty($entities)) { if (empty($entities)) {
@@ -173,25 +190,30 @@ class QueryBuilderUtility
* Attention. Existing parameters will be overridden. * Attention. Existing parameters will be overridden.
* *
* @param QueryBuilder $queryBuilder The query builder * @param QueryBuilder $queryBuilder The query builder
* @param array|ArrayCollection $parameters Parameters to add. Collection of instances of * @param array|ArrayCollection $parameters Parameters to add. Collection of Doctrine\ORM\Query\Parameter
* Doctrine\ORM\Query\Parameter class or an array with key-value pairs. * instances or an array with key-value pairs.
*
* @return QueryBuilder * @return QueryBuilder
*/ */
public static function addParameters(QueryBuilder $queryBuilder, $parameters) public static function addParameters(QueryBuilder $queryBuilder, $parameters)
{ {
if (!empty($parameters)) { /*
foreach ($parameters as $key => $parameter) { * No parameters?
$name = $key; * Nothing to do
$value = $parameter; */
if (empty($parameters)) {
return $queryBuilder;
}
if ($parameter instanceof Parameter) { foreach ($parameters as $key => $parameter) {
$name = $parameter->getName(); $name = $key;
$value = $parameter->getValue(); $value = $parameter;
}
$queryBuilder->setParameter($name, $value); if ($parameter instanceof Parameter) {
$name = $parameter->getName();
$value = $parameter->getValue();
} }
$queryBuilder->setParameter($name, $value);
} }
return $queryBuilder; return $queryBuilder;

View File

@@ -8,9 +8,9 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Util\ClassUtils; use Doctrine\Common\Util\ClassUtils;
use Doctrine\Common\Util\Inflector; use Doctrine\Common\Util\Inflector;
use Meritoo\Common\Collection\Collection;
use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException; use Meritoo\Common\Exception\Reflection\CannotResolveClassNameException;
use Meritoo\Common\Exception\Reflection\MissingChildClassesException; use Meritoo\Common\Exception\Reflection\MissingChildClassesException;
use Meritoo\Common\Exception\Reflection\TooManyChildClassesException; use Meritoo\Common\Exception\Reflection\TooManyChildClassesException;
@@ -21,20 +21,20 @@ use ReflectionObject;
use ReflectionProperty; use ReflectionProperty;
/** /**
* Useful reflection methods. * Useful reflection methods
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Reflection class Reflection
{ {
/** /**
* Returns names of methods for given class / object. * Returns names of methods for given class / object
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @param bool $withoutInheritance (optional) If is set to true, only methods for given class are returned. * @param bool $withoutInheritance (optional) If is set to true, only methods for given class are returned.
* Otherwise - all methods, with inherited methods too. * Otherwise - all methods, with inherited methods too.
* * @throws ReflectionException
* @return array * @return array
*/ */
public static function getMethods($class, $withoutInheritance = false) public static function getMethods($class, $withoutInheritance = false)
@@ -62,10 +62,10 @@ class Reflection
} }
/** /**
* Returns constants of given class / object. * Returns constants of given class / object
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* * @throws ReflectionException
* @return array * @return array
*/ */
public static function getConstants($class) public static function getConstants($class)
@@ -76,11 +76,11 @@ class Reflection
} }
/** /**
* Returns maximum constant from all constants of given class / object. * Returns maximum integer value of constant of given class / object.
* Values of constants should be integers. * Constants whose values are integers are considered only.
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* * @throws ReflectionException
* @return int|null * @return int|null
*/ */
public static function getMaxNumberConstant($class) public static function getMaxNumberConstant($class)
@@ -103,11 +103,11 @@ class Reflection
} }
/** /**
* Returns information if given class / object has given method. * Returns information if given class / object has given method
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @param string $method Name of the method to find * @param string $method Name of the method to find
* * @throws ReflectionException
* @return bool * @return bool
*/ */
public static function hasMethod($class, $method) public static function hasMethod($class, $method)
@@ -118,11 +118,11 @@ class Reflection
} }
/** /**
* Returns information if given class / object has given property. * Returns information if given class / object has given property
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @param string $property Name of the property to find * @param string $property Name of the property to find
* * @throws ReflectionException
* @return bool * @return bool
*/ */
public static function hasProperty($class, $property) public static function hasProperty($class, $property)
@@ -133,11 +133,11 @@ class Reflection
} }
/** /**
* Returns information if given class / object has given constant. * Returns information if given class / object has given constant
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @param string $constant Name of the constant to find * @param string $constant Name of the constant to find
* * @throws ReflectionException
* @return bool * @return bool
*/ */
public static function hasConstant($class, $constant) public static function hasConstant($class, $constant)
@@ -148,11 +148,11 @@ class Reflection
} }
/** /**
* Returns value of given constant. * Returns value of given constant
* *
* @param object|string $class The object or name of object's class * @param object|string $class The object or name of object's class
* @param string $constant Name of the constant that contains a value * @param string $constant Name of the constant that contains a value
* * @throws ReflectionException
* @return mixed * @return mixed
*/ */
public static function getConstantValue($class, $constant) public static function getConstantValue($class, $constant)
@@ -175,7 +175,7 @@ class Reflection
* dot-separated, e.g. "invoice.user.email". * dot-separated, e.g. "invoice.user.email".
* @param bool $force (optional) If is set to true, try to retrieve value even if the object doesn't have * @param bool $force (optional) If is set to true, try to retrieve value even if the object doesn't have
* property. Otherwise - not. * property. Otherwise - not.
* * @throws ReflectionException
* @return mixed * @return mixed
*/ */
public static function getPropertyValue($object, $property, $force = false) public static function getPropertyValue($object, $property, $force = false)
@@ -206,10 +206,10 @@ class Reflection
* while using "project.name" as property - $project has $name property ($project exists in the Deal class) * while using "project.name" as property - $project has $name property ($project exists in the Deal class)
* and the $project equals null * and the $project equals null
* *
* Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * Meritoo <github@meritoo.pl>
* 2016-11-07 * 2016-11-07
*/ */
if ($object !== null) { if (null !== $object) {
unset($exploded[0]); unset($exploded[0]);
$property = implode('.', $exploded); $property = implode('.', $exploded);
@@ -237,33 +237,45 @@ class Reflection
if ($class->hasProperty($property) || $force) { if ($class->hasProperty($property) || $force) {
$property = Inflector::classify($property); $property = Inflector::classify($property);
$methodPrefixes = [ $getterPrefixes = [
'get', 'get',
'has', 'has',
'is', 'is',
]; ];
foreach ($methodPrefixes as $prefix) { foreach ($getterPrefixes as $prefix) {
$method = sprintf('%s%s', $prefix, $property); $getterName = sprintf('%s%s', $prefix, $property);
if ($class->hasMethod($method)) { if ($class->hasMethod($getterName)) {
$value = $object->{$method}(); $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; $valueFound = true;
break; break;
} }
} }
} }
if (!$valueFound && $reflectionProperty !== null) { if (!$valueFound && null !== $reflectionProperty) {
/* /*
* Oops, we have got exception. * Oops, value of the property is still unknown
* *
* 3rd try: * 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); $reflectionProperty->setAccessible(true);
$value = $reflectionProperty->getValue($object); $value = $reflectionProperty->getValue($object);
$reflectionProperty->setAccessible(false);
} }
} }
} }
@@ -280,11 +292,19 @@ class Reflection
* @param string $property Name of the property that contains a value * @param string $property Name of the property that contains a value
* @param bool $force (optional) If is set to true, try to retrieve value even if the * @param bool $force (optional) If is set to true, try to retrieve value even if the
* object does not have property. Otherwise - not. * object does not have property. Otherwise - not.
* * @throws ReflectionException
* @return array * @return array
*/ */
public static function getPropertyValues($objects, $property, $force = false) public static function getPropertyValues($objects, $property, $force = false)
{ {
/*
* No objects?
* Nothing to do
*/
if (empty($objects)) {
return [];
}
if ($objects instanceof Collection) { if ($objects instanceof Collection) {
$objects = $objects->toArray(); $objects = $objects->toArray();
} }
@@ -295,7 +315,7 @@ class Reflection
foreach ($objects as $entity) { foreach ($objects as $entity) {
$value = self::getPropertyValue($entity, $property, $force); $value = self::getPropertyValue($entity, $property, $force);
if ($value !== null) { if (null !== $value) {
$values[] = $value; $values[] = $value;
} }
} }
@@ -304,12 +324,11 @@ class Reflection
} }
/** /**
* Returns a class name for given source. * Returns a class name for given source
* *
* @param array|object|string $source An array of objects, namespaces, object or namespace * @param array|object|string $source An array of objects, namespaces, object or namespace
* @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise - * @param bool $withoutNamespace (optional) If is set to true, namespace is omitted. Otherwise -
* not, full name of class is returned, with namespace. * not, full name of class is returned, with namespace.
*
* @return string|null * @return string|null
*/ */
public static function getClassName($source, $withoutNamespace = false) public static function getClassName($source, $withoutNamespace = false)
@@ -356,7 +375,7 @@ class Reflection
if ($withoutNamespace) { if ($withoutNamespace) {
$classOnly = Miscellaneous::getLastElementOfString($name, '\\'); $classOnly = Miscellaneous::getLastElementOfString($name, '\\');
if ($classOnly !== null) { if (null !== $classOnly) {
$name = $classOnly; $name = $classOnly;
} }
@@ -367,10 +386,9 @@ class Reflection
} }
/** /**
* Returns namespace of class for given source. * Returns namespace of class for given source
* *
* @param array|object|string $source An array of objects, namespaces, object or namespace * @param array|object|string $source An array of objects, namespaces, object or namespace
*
* @return string * @return string
*/ */
public static function getClassNamespace($source) public static function getClassNamespace($source)
@@ -391,11 +409,10 @@ class Reflection
} }
/** /**
* Returns information if given interface is implemented by given class / object. * Returns information if given interface is implemented by given class / object
* *
* @param array|object|string $source An array of objects, namespaces, object or namespace * @param array|object|string $source An array of objects, namespaces, object or namespace
* @param string $interface The interface that should be implemented * @param string $interface The interface that should be implemented
*
* @return bool * @return bool
*/ */
public static function isInterfaceImplemented($source, $interface) public static function isInterfaceImplemented($source, $interface)
@@ -407,11 +424,10 @@ class Reflection
} }
/** /**
* Returns information if given child class is a subclass of given parent class. * Returns information if given child class is a subclass of given parent class
* *
* @param array|object|string $childClass The child class. An array of objects, namespaces, object or namespace. * @param array|object|string $childClass The child class. An array of objects, namespaces, object or namespace.
* @param array|object|string $parentClass The parent class. An array of objects, namespaces, object or namespace. * @param array|object|string $parentClass The parent class. An array of objects, namespaces, object or namespace.
*
* @return bool * @return bool
*/ */
public static function isChildOfClass($childClass, $parentClass) public static function isChildOfClass($childClass, $parentClass)
@@ -421,7 +437,7 @@ class Reflection
$parents = class_parents($childClassName); $parents = class_parents($childClassName);
if (is_array($parents)) { if (is_array($parents) && 0 < count($parents)) {
return in_array($parentClassName, $parents); return in_array($parentClassName, $parents);
} }
@@ -429,35 +445,49 @@ class Reflection
} }
/** /**
* Returns given object properties. * 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.
* @throws ReflectionException
* @return array|ReflectionProperty * @return array|ReflectionProperty
*/ */
public static function getProperties($source, $filter = null) public static function getProperties($source, $filter = null, $includeParents = false)
{ {
$className = self::getClassName($source); $className = self::getClassName($source);
$reflection = new ReflectionClass($className); $reflection = new ReflectionClass($className);
if ($filter === null) { if (null === $filter) {
$filter = ReflectionProperty::IS_PRIVATE $filter = ReflectionProperty::IS_PRIVATE
+ ReflectionProperty::IS_PROTECTED + ReflectionProperty::IS_PROTECTED
+ ReflectionProperty::IS_PUBLIC + ReflectionProperty::IS_PUBLIC
+ ReflectionProperty::IS_STATIC; + 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 * @param array|object|string $source An array of objects, namespaces, object or namespace
* * @throws ReflectionException
* @return ReflectionClass * @return ReflectionClass|bool
*/ */
public static function getParentClass($source) public static function getParentClass($source)
{ {
@@ -473,10 +503,8 @@ class Reflection
* *
* @param array|object|string $class Class who child classes should be returned. An array of objects, strings, * @param array|object|string $class Class who child classes should be returned. An array of objects, strings,
* object or string. * object or string.
*
* @return array|null
*
* @throws CannotResolveClassNameException * @throws CannotResolveClassNameException
* @return array|null
*/ */
public static function getChildClasses($class) public static function getChildClasses($class)
{ {
@@ -495,8 +523,8 @@ class Reflection
/* /*
* Oops, cannot resolve class * Oops, cannot resolve class
*/ */
if ($className === null) { if (null === $className) {
throw new CannotResolveClassNameException($class); throw CannotResolveClassNameException::create($class);
} }
$childClasses = []; $childClasses = [];
@@ -530,11 +558,9 @@ class Reflection
* *
* @param array|object|string $parentClass Class who child class should be returned. An array of objects, * @param array|object|string $parentClass Class who child class should be returned. An array of objects,
* namespaces, object or namespace. * namespaces, object or namespace.
*
* @return mixed
*
* @throws MissingChildClassesException * @throws MissingChildClassesException
* @throws TooManyChildClassesException * @throws TooManyChildClassesException
* @return mixed
*/ */
public static function getOneChildClass($parentClass) public static function getOneChildClass($parentClass)
{ {
@@ -545,7 +571,7 @@ class Reflection
* Oops, the base / parent class hasn't child class * Oops, the base / parent class hasn't child class
*/ */
if (empty($childClasses)) { if (empty($childClasses)) {
throw new MissingChildClassesException($parentClass); throw MissingChildClassesException::create($parentClass);
} }
/* /*
@@ -553,20 +579,20 @@ class Reflection
* Oops, the base / parent class has too many child classes * Oops, the base / parent class has too many child classes
*/ */
if (count($childClasses) > 1) { if (count($childClasses) > 1) {
throw new TooManyChildClassesException($parentClass, $childClasses); throw TooManyChildClassesException::create($parentClass, $childClasses);
} }
return trim($childClasses[0]); return trim($childClasses[0]);
} }
/** /**
* Returns property, the ReflectionProperty instance, of given object. * Returns property, the ReflectionProperty instance, of given object
* *
* @param array|object|string $class An array of objects, namespaces, object or namespace * @param array|object|string $class An array of objects, namespaces, object or namespace
* @param string $property Name of the property * @param string $property Name of the property
* @param int $filter (optional) Filter of properties. Uses ReflectionProperty class constants. * @param int $filter (optional) Filter of properties. Uses ReflectionProperty class constants.
* By default all properties are allowed / processed. * By default all properties are allowed / processed.
* * @throws ReflectionException
* @return null|ReflectionProperty * @return null|ReflectionProperty
*/ */
public static function getProperty($class, $property, $filter = null) public static function getProperty($class, $property, $filter = null)
@@ -587,16 +613,14 @@ class Reflection
} }
/** /**
* Returns information if given class / object uses / implements given trait. * Returns information if given class / object uses / implements given trait
* *
* @param array|object|string $class An array of objects, namespaces, object or namespace * @param array|object|string $class An array of objects, namespaces, object or namespace
* @param array|string $trait An array of strings or string * @param array|string $trait An array of strings or string
* @param bool $verifyParents If is set to true, parent classes are verified if they use given * @param bool $verifyParents If is set to true, parent classes are verified if they use given
* trait. Otherwise - not. * trait. Otherwise - not.
*
* @return bool|null
*
* @throws CannotResolveClassNameException * @throws CannotResolveClassNameException
* @return bool|null
*/ */
public static function usesTrait($class, $trait, $verifyParents = false) public static function usesTrait($class, $trait, $verifyParents = false)
{ {
@@ -607,7 +631,7 @@ class Reflection
* Oops, cannot resolve class * Oops, cannot resolve class
*/ */
if (empty($className)) { if (empty($className)) {
throw new CannotResolveClassNameException($class); throw CannotResolveClassNameException::create($class);
} }
/* /*
@@ -625,7 +649,7 @@ class Reflection
if (!$uses && $verifyParents) { if (!$uses && $verifyParents) {
$parentClassName = self::getParentClassName($className); $parentClassName = self::getParentClassName($className);
if ($parentClassName !== null) { if (null !== $parentClassName) {
return self::usesTrait($parentClassName, $trait, true); return self::usesTrait($parentClassName, $trait, true);
} }
} }
@@ -638,7 +662,7 @@ class Reflection
* If given class does not extend another, returns null. * If given class does not extend another, returns null.
* *
* @param array|object|string $class An array of objects, namespaces, object or namespace * @param array|object|string $class An array of objects, namespaces, object or namespace
* * @throws ReflectionException
* @return string|null * @return string|null
*/ */
public static function getParentClassName($class) public static function getParentClassName($class)
@@ -647,7 +671,7 @@ class Reflection
$reflection = new ReflectionClass($className); $reflection = new ReflectionClass($className);
$parentClass = $reflection->getParentClass(); $parentClass = $reflection->getParentClass();
if ($parentClass === null || $parentClass === false) { if (null === $parentClass || false === $parentClass) {
return null; return null;
} }

View File

@@ -12,38 +12,40 @@ use Meritoo\Common\Exception\Regex\IncorrectColorHexLengthException;
use Meritoo\Common\Exception\Regex\InvalidColorHexValueException; use Meritoo\Common\Exception\Regex\InvalidColorHexValueException;
/** /**
* Useful regular expressions methods. * Useful regular expressions methods
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Regex class Regex
{ {
/** /**
* Patterns used to validate / verify values. * Patterns used to validate / verify values
* *
* @var array * @var array
*/ */
private static $patterns = [ private static $patterns = [
'email' => '/[\w-]{2,}@[\w-]+\.[\w]{2,}+/', 'email' => '/^[\w-.]{2,}@[\w-]+\.[\w]{2,}+$/',
'phone' => '/^\+?[0-9 ]+$/', 'phone' => '/^\+?[0-9 ]+$/',
'camelCasePart' => '/([a-z]|[A-Z]){1}[a-z]*/', 'camelCasePart' => '/([a-z]|[A-Z]){1}[a-z]*/',
'urlProtocol' => '/^([a-z]+:\/\/)', 'urlProtocol' => '/^([a-z]+:\/\/)',
'urlDomain' => '([\da-z\.-]+)\.([a-z\.]{2,6})(\/)?([\w\.\-]*)?(\?)?([\w \.\-\/=&]*)\/?$/i', 'urlDomain' => '([\da-z\.-]+)\.([a-z\.]{2,6})(\/)?([\w\.\-]*)?(\?)?([\w \.\-\/=&]*)\/?$/i',
'letterOrDigit' => '/[a-zA-Z0-9]+/', 'letterOrDigit' => '/[a-zA-Z0-9]+/',
'htmlEntity' => '/&[a-z0-9]+;/', 'htmlEntity' => '/&[a-z0-9]+;/',
'fileName' => '/.+\.\w+$/', 'htmlAttribute' => '/([\w-]+)="([\w -]+)"/',
'isQuoted' => '/^[\'"]{1}.+[\'"]{1}$/', 'fileName' => '/.+\.\w+$/',
'isQuoted' => '/^[\'"]{1}.+[\'"]{1}$/',
'windowsBasedPath' => '/^[A-Z]{1}:\\\.*$/', 'windowsBasedPath' => '/^[A-Z]{1}:\\\.*$/',
'money' => '/^[-+]?\d+([\.,]{1}\d*)?$/', 'money' => '/^[-+]?\d+([\.,]{1}\d*)?$/',
'color' => '/^[a-f0-9]{6}$/i', 'color' => '/^[a-f0-9]{6}$/i',
'bundleName' => '/^(([A-Z]{1}[a-z0-9]+)((?2))*)(Bundle)$/',
'binaryValue' => '/[^\x20-\x7E\t\r\n]/',
]; ];
/** /**
* Returns information if given e-mail address is valid. * Returns information if given e-mail address is valid
* *
* @param string $email E-mail address to validate / verify * @param string $email E-mail address to validate / verify
*
* @return bool * @return bool
* *
* Examples: * Examples:
@@ -57,158 +59,215 @@ class Regex
*/ */
public static function isValidEmail($email) public static function isValidEmail($email)
{ {
/*
* Not a string?
* Nothing to do
*/
if (!is_string($email)) {
return false;
}
$pattern = self::getEmailPattern(); $pattern = self::getEmailPattern();
return (bool) preg_match($pattern, $email); return (bool)preg_match($pattern, $email);
} }
/** /**
* Returns information if given tax ID (in polish: NIP) is valid. * Returns information if given tax ID is valid (in Poland it's named "NIP")
*
* @param string $taxidString Tax ID (NIP) string
* *
* @param string $taxIdString Tax ID (NIP) string
* @return bool * @return bool
*/ */
public static function isValidTaxid($taxidString) public static function isValidTaxId($taxIdString)
{ {
if (!empty($taxidString)) { /*
$weights = [ * Not a string?
6, * Nothing to do
5, */
7, if (!is_string($taxIdString)) {
2, return false;
3, }
4,
5,
6,
7,
];
$taxid = preg_replace('/[\s-]/', '', $taxidString);
$sum = 0;
if (strlen($taxid) == 10 && is_numeric($taxid)) { /*
for ($x = 0; $x <= 8; ++$x) { * Empty/Unknown value?
$sum += $taxid[$x] * $weights[$x]; * Nothing to do
} */
if (empty($taxIdString)) {
return false;
}
if ((($sum % 11) % 10) == $taxid[9]) { $taxId = preg_replace('/[\s-]/', '', $taxIdString);
return true;
} /*
} * Tax ID is not 10 characters length OR is not numeric?
* Nothing to do
*/
if (10 !== strlen($taxId) || !is_numeric($taxId)) {
return false;
}
$weights = [
6,
5,
7,
2,
3,
4,
5,
6,
7,
];
$sum = 0;
for ($x = 0; $x <= 8; ++$x) {
$sum += $taxId[$x] * $weights[$x];
}
/*
* Last number it's not a remainder from dividing per 11?
* Nothing to do
*/
if ($sum % 11 == $taxId[9]) {
return true;
} }
return false; return false;
} }
/** /**
* Returns information if given url address is valid. * Returns information if given url address is valid
* *
* @param string $url The url to validate / verify * @param string $url The url to validate / verify
* @param bool $requireProtocol (optional) If is set to true, the protocol is required to be passed in the url. * @param bool $requireProtocol (optional) If is set to true, the protocol is required to be passed in the url.
* Otherwise - not. * Otherwise - not.
*
* @return bool * @return bool
*/ */
public static function isValidUrl($url, $requireProtocol = false) public static function isValidUrl($url, $requireProtocol = false)
{ {
/*
* Not a string?
* Nothing to do
*/
if (!is_string($url)) {
return false;
}
$pattern = self::getUrlPattern($requireProtocol); $pattern = self::getUrlPattern($requireProtocol);
return (bool) preg_match($pattern, $url); return (bool)preg_match($pattern, $url);
} }
/** /**
* Returns information if given phone number is valid. * Returns information if given phone number is valid
* *
* @param string $phoneNumber The phone number to validate / verify * @param string $phoneNumber The phone number to validate / verify
*
* @return bool * @return bool
*/ */
public static function isValidPhoneNumber($phoneNumber) public static function isValidPhoneNumber($phoneNumber)
{ {
/*
* Not a string?
* Nothing to do
*/
if (!is_string($phoneNumber)) {
return false;
}
$pattern = self::getPhoneNumberPattern(); $pattern = self::getPhoneNumberPattern();
return (bool) preg_match($pattern, $phoneNumber); return (bool)preg_match($pattern, trim($phoneNumber));
} }
/** /**
* Returns array values that matches given pattern (or values that keys matches). * Returns array values that match given pattern (or values that keys match the pattern)
* *
* @param string $pattern Pattern to match * @param string $pattern Pattern to match
* @param array $dataArray The array * @param array $array The array (scalar values only)
* @param bool $itsKeyPattern (optional) If is set to true, keys are checks if they match pattern. Otherwise - * @param bool $itsKeyPattern (optional) If is set to true, keys will be checked if they match pattern.
* values are checks. * Otherwise - values will be checked (default behaviour).
*
* @return array * @return array
*/ */
public static function getArrayValuesByPattern($pattern, $dataArray, $itsKeyPattern = false) public static function getArrayValuesByPattern($pattern, array $array, $itsKeyPattern = false)
{ {
/*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return [];
}
if ($itsKeyPattern) { if ($itsKeyPattern) {
$effect = []; $effect = [];
if (!empty($dataArray)) { foreach ($array as $key => $value) {
$matches = []; if ((bool)preg_match($pattern, $key)) {
$effect[$key] = $value;
foreach ($dataArray as $key => $value) {
if (preg_match($pattern, $key, $matches)) {
$effect[$key] = $value;
}
} }
} }
return $effect; return $effect;
} }
return preg_grep($pattern, $dataArray); return preg_grep($pattern, $array);
} }
/** /**
* Filters array by given expression and column. * Filters array by given expression and column
* *
* Expression can be simple compare expression, like ' == 2', or regular expression. * Expression can be simple compare expression, like " == 2", or regular expression.
* Returns filtered array. * Returns filtered array.
* *
* @param array $array The array that should be filtered * @param array $array The 2-dimensional array that should be filtered
* @param string $arrayColumnKey Column name * @param string $arrayColumnKey Column name
* @param string $filterExpression Filter expression, e.g. '== 2' or '!= \'home\'' * @param string $filterExpression Simple filter expression (e.g. "== 2" or "!= \'home\'") or regular
* @param bool $itsRegularExpression (optional) If is set to true, means that filter expression is a * expression (e.g. "/\d+/" or "/[a-z]+[,;]{2,}/")
* regular expression * @param bool $itsRegularExpression (optional) If is set to true, means that filter expression is a regular
* * expression. Otherwise - not (default behaviour).
* @return array * @return array
*/ */
public static function arrayFilter($array, $arrayColumnKey, $filterExpression, $itsRegularExpression = false) public static function arrayFilter($array, $arrayColumnKey, $filterExpression, $itsRegularExpression = false)
{ {
$effect = []; /*
* No elements?
* Nothing to do
*/
if (empty($array)) {
return [];
}
if (!empty($array)) { $effect = $array;
$effect = $array;
foreach ($effect as $key => &$item) { foreach ($effect as $key => &$item) {
if (isset($item[$arrayColumnKey])) { if (!isset($item[$arrayColumnKey])) {
$value = $item[$arrayColumnKey]; continue;
}
if ($itsRegularExpression) { $value = $item[$arrayColumnKey];
$matches = [];
$pattern = '|'.$filterExpression.'|';
$matchesCount = preg_match($pattern, $value, $matches);
$remove = $matchesCount == 0; if ($itsRegularExpression) {
$matchesCount = preg_match($filterExpression, $value);
$remove = 0 == $matchesCount;
} else {
if (is_string($value)) {
$value = sprintf('\'%s\'', $value);
} elseif (is_bool($value)) {
if (true === $value) {
$value = 'true';
} else { } else {
if ($value == '') { $value = 'false';
$value = '\'\'';
} elseif (is_string($value)) {
$value = '\''.$value.'\'';
}
eval('$isTrue = '.$value.$filterExpression.';');
/* @var bool $isTrue */
$remove = !$isTrue;
}
if ($remove) {
unset($effect[$key]);
} }
} }
eval(sprintf('$isEqual = %s%s;', $value, $filterExpression));
/* @var bool $isEqual */
$remove = !$isEqual;
}
if ($remove) {
unset($effect[$key]);
} }
} }
@@ -216,38 +275,41 @@ class Regex
} }
/** /**
* Perform regular expression match with many given patterns. * Performs regular expression match with many given patterns.
* Returns information if given $subject matches one or all given $patterns. * Returns information if given $subject matches one or all given $patterns.
* *
* @param array|string $patterns The patterns to match * @param array|string $patterns The patterns to match
* @param string $subject The string to check * @param string $subject The string to check
* @param bool $mustAllMatch (optional) If is set to true, $subject must match all $patterns. Otherwise - * @param bool $mustAllMatch (optional) If is set to true, $subject must match all $patterns. Otherwise -
* not. * not (default behaviour).
*
* @return bool * @return bool
*/ */
public static function pregMultiMatch($patterns, $subject, $mustAllMatch = false) public static function pregMultiMatch($patterns, $subject, $mustAllMatch = false)
{ {
/*
* No patterns?
* Nothing to do
*/
if (empty($patterns)) {
return false;
}
$effect = false; $effect = false;
$patterns = Arrays::makeArray($patterns); $patterns = Arrays::makeArray($patterns);
if (!empty($patterns)) { if ($mustAllMatch) {
$effect = true;
}
foreach ($patterns as $pattern) {
$matched = (bool)preg_match_all($pattern, $subject);
if ($mustAllMatch) { if ($mustAllMatch) {
$effect = true; $effect = $effect && $matched;
} } else {
if ($matched) {
foreach ($patterns as $pattern) { $effect = $matched;
$matches = []; break;
$matched = (bool) preg_match_all($pattern, $subject, $matches);
if ($mustAllMatch) {
$effect = $effect && $matched;
} else {
if ($matched) {
$effect = $matched;
break;
}
} }
} }
} }
@@ -256,12 +318,11 @@ class Regex
} }
/** /**
* Returns string in human readable style generated from given camel case string / text. * Returns string in human readable style generated from given camel case string / text
* *
* @param string $string The string / text to convert * @param string $string The string / text to convert
* @param bool $applyUpperCaseFirst (optional) If is set to true, first word / element from the converted * @param bool $applyUpperCaseFirst (optional) If is set to true, first word / element from the converted
* string is uppercased. Otherwise - not. * string is uppercased. Otherwise - not.
*
* @return string * @return string
*/ */
public static function camelCase2humanReadable($string, $applyUpperCaseFirst = false) public static function camelCase2humanReadable($string, $applyUpperCaseFirst = false)
@@ -286,10 +347,9 @@ class Regex
} }
/** /**
* Returns parts of given camel case string / text. * Returns parts of given camel case string / text
* *
* @param string $string The string / text to retrieve parts * @param string $string The string / text to retrieve parts
*
* @return array * @return array
*/ */
public static function getCamelCaseParts($string) public static function getCamelCaseParts($string)
@@ -302,12 +362,11 @@ class Regex
} }
/** /**
* Returns simple, lowercase string generated from given camel case string / text. * Returns simple, lowercase string generated from given camel case string / text
* *
* @param string $string The string / text to convert * @param string $string The string / text to convert
* @param string $separator (optional) Separator used to concatenate parts of the string, e.g. '-' or '_' * @param string $separator (optional) Separator used to concatenate parts of the string, e.g. '-' or '_'
* @param bool $applyLowercase (optional) If is set to true, returned string will be lowercased. Otherwise - not. * @param bool $applyLowercase (optional) If is set to true, returned string will be lowercased. Otherwise - not.
*
* @return string * @return string
*/ */
public static function camelCase2simpleLowercase($string, $separator = '', $applyLowercase = true) public static function camelCase2simpleLowercase($string, $separator = '', $applyLowercase = true)
@@ -326,7 +385,7 @@ class Regex
} }
/** /**
* Returns pattern used to validate / verify or get e-mail address. * Returns pattern used to validate / verify or get e-mail address
* *
* @return string * @return string
*/ */
@@ -336,7 +395,7 @@ class Regex
} }
/** /**
* Returns pattern used to validate / verify or get phone number. * Returns pattern used to validate / verify or get phone number
* *
* @return string * @return string
*/ */
@@ -346,7 +405,7 @@ class Regex
} }
/** /**
* Returns pattern used to validate / verify or get camel case parts of string. * Returns pattern used to validate / verify or get camel case parts of string
* *
* @return string * @return string
*/ */
@@ -356,11 +415,10 @@ class Regex
} }
/** /**
* Returns pattern used to validate / verify or get url address. * Returns pattern used to validate / verify or get url address
* *
* @param bool $requireProtocol (optional) If is set to true, the protocol is required to be passed in the url. * @param bool $requireProtocol (optional) If is set to true, the protocol is required to be passed in the url.
* Otherwise - not. * Otherwise - not.
*
* @return string * @return string
*/ */
public static function getUrlPattern($requireProtocol = false) public static function getUrlPattern($requireProtocol = false)
@@ -377,11 +435,10 @@ class Regex
} }
/** /**
* Returns information if given path is sub-path of another path, e.g. path file is owned by path of directory. * Returns information if given path is sub-path of another path, e.g. path file is owned by path of directory
* *
* @param string $subPath Path to verify, probably sub-path * @param string $subPath Path to verify, probably sub-path
* @param string $path Main / parent path * @param string $path Main / parent path
*
* @return bool * @return bool
*/ */
public static function isSubPathOf($subPath, $path) public static function isSubPathOf($subPath, $path)
@@ -408,11 +465,11 @@ class Regex
$pattern = sprintf('/^%s.*/', $prepared); $pattern = sprintf('/^%s.*/', $prepared);
return (bool) preg_match($pattern, $subPath); return (bool)preg_match($pattern, $subPath);
} }
/** /**
* Returns pattern used to validate / verify letter or digit. * Returns pattern used to validate / verify letter or digit
* *
* @return string * @return string
*/ */
@@ -422,66 +479,62 @@ class Regex
} }
/** /**
* Returns information if given character is a letter or digit. * Returns information if given character is a letter or digit
* *
* @param string $char Character to check * @param string $char Character to check
*
* @return bool * @return bool
*/ */
public static function isLetterOrDigit($char) public static function isLetterOrDigit($char)
{ {
$pattern = self::getLetterOrDigitPattern(); $pattern = self::getLetterOrDigitPattern();
return is_scalar($char) && (bool) preg_match($pattern, $char); return is_scalar($char) && (bool)preg_match($pattern, $char);
} }
/** /**
* Returns information if the string starts with given beginning / characters. * Returns information if the string starts with given beginning / characters
* *
* @param string $string String to check * @param string $string String to check
* @param string $beginning The beginning of string, one or more characters * @param string $beginning The beginning of string, one or more characters
*
* @return bool * @return bool
*/ */
public static function startsWith($string, $beginning) public static function startsWith($string, $beginning)
{ {
if (!empty($string) && !empty($beginning)) { if (!empty($string) && !empty($beginning)) {
if (strlen($beginning) == 1 && !self::isLetterOrDigit($beginning)) { if (1 == strlen($beginning) && !self::isLetterOrDigit($beginning)) {
$beginning = '\\'.$beginning; $beginning = '\\' . $beginning;
} }
$pattern = sprintf('|^%s|', $beginning); $pattern = sprintf('|^%s|', $beginning);
return (bool) preg_match($pattern, $string); return (bool)preg_match($pattern, $string);
} }
return false; return false;
} }
/** /**
* Returns information if the string ends with given ending / characters. * Returns information if the string ends with given ending / characters
* *
* @param string $string String to check * @param string $string String to check
* @param string $ending The ending of string, one or more characters * @param string $ending The ending of string, one or more characters
*
* @return bool * @return bool
*/ */
public static function endsWith($string, $ending) public static function endsWith($string, $ending)
{ {
if (strlen($ending) == 1 && !self::isLetterOrDigit($ending)) { if (1 == strlen($ending) && !self::isLetterOrDigit($ending)) {
$ending = '\\'.$ending; $ending = '\\' . $ending;
} }
return (bool) preg_match('|'.$ending.'$|', $string); return (bool)preg_match('|' . $ending . '$|', $string);
} }
/** /**
* Returns information if the string starts with directory's separator. * Returns information if the string starts with directory's separator
* *
* @param string $string String that may contain a directory's separator at the start / beginning * @param string $string String that may contain a directory's separator at the start / beginning
* @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), system's * @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), system's
* separator is used. * separator is used.
*
* @return bool * @return bool
*/ */
public static function startsWithDirectorySeparator($string, $separator = '') public static function startsWithDirectorySeparator($string, $separator = '')
@@ -494,12 +547,11 @@ class Regex
} }
/** /**
* Returns information if the string ends with directory's separator. * Returns information if the string ends with directory's separator
* *
* @param string $text String that may contain a directory's separator at the end * @param string $text String that may contain a directory's separator at the end
* @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), system's * @param string $separator (optional) The directory's separator, e.g. "/". If is empty (not provided), system's
* separator is used. * separator is used.
*
* @return string * @return string
*/ */
public static function endsWithDirectorySeparator($text, $separator = '') public static function endsWithDirectorySeparator($text, $separator = '')
@@ -512,20 +564,19 @@ class Regex
} }
/** /**
* Returns information if uri contains parameter. * Returns information if uri contains parameter
* *
* @param string $uri Uri string (e.g. $_SERVER['REQUEST_URI']) * @param string $uri Uri string (e.g. $_SERVER['REQUEST_URI'])
* @param string $parameterName Uri parameter name * @param string $parameterName Uri parameter name
*
* @return bool * @return bool
*/ */
public static function isSetUriParameter($uri, $parameterName) public static function isSetUriParameter($uri, $parameterName)
{ {
return (bool) preg_match('|[?&]{1}'.$parameterName.'=|', $uri); // e.g. ?name=phil&type=4 -> '$type=' return (bool)preg_match('|[?&]{1}' . $parameterName . '=|', $uri); // e.g. ?name=phil&type=4 -> '$type='
} }
/** /**
* Returns pattern used to validate / verify html entity. * Returns pattern used to validate / verify html entity
* *
* @return string * @return string
*/ */
@@ -535,38 +586,36 @@ class Regex
} }
/** /**
* Returns information if the string contains html entities. * Returns information if the string contains html entities
* *
* @param string $string String to check * @param string $string String to check
*
* @return bool * @return bool
*/ */
public static function containsEntities($string) public static function containsEntities($string)
{ {
$pattern = self::getHtmlEntityPattern(); $pattern = self::getHtmlEntityPattern();
return (bool) preg_match_all($pattern, $string); return (bool)preg_match_all($pattern, $string);
} }
/** /**
* Returns information if one string contains another string. * Returns information if one string contains another string
* *
* @param string $haystack The string to search in * @param string $haystack The string to search in
* @param string $needle The string to be search for * @param string $needle The string to be search for
*
* @return bool * @return bool
*/ */
public static function contains($haystack, $needle) public static function contains($haystack, $needle)
{ {
if (strlen($needle) == 1 && !self::isLetterOrDigit($needle)) { if (1 == strlen($needle) && !self::isLetterOrDigit($needle)) {
$needle = '\\'.$needle; $needle = '\\' . $needle;
} }
return (bool) preg_match('|.*'.$needle.'.*|', $haystack); return (bool)preg_match('|.*' . $needle . '.*|', $haystack);
} }
/** /**
* Returns pattern used to validate / verify name of file. * Returns pattern used to validate / verify name of file
* *
* @return string * @return string
*/ */
@@ -580,18 +629,17 @@ class Regex
* Verifies if given name contains a dot and an extension, e.g. "My File 001.jpg". * Verifies if given name contains a dot and an extension, e.g. "My File 001.jpg".
* *
* @param string $fileName Name of file to check. It may be path of file also. * @param string $fileName Name of file to check. It may be path of file also.
*
* @return bool * @return bool
*/ */
public static function isFileName($fileName) public static function isFileName($fileName)
{ {
$pattern = self::getFileNamePattern(); $pattern = self::getFileNamePattern();
return (bool) preg_match($pattern, $fileName); return (bool)preg_match($pattern, $fileName);
} }
/** /**
* Returns pattern used to validate / verify if value is quoted (by apostrophes or quotation marks). * Returns pattern used to validate / verify if value is quoted (by apostrophes or quotation marks)
* *
* @return string * @return string
*/ */
@@ -601,21 +649,20 @@ class Regex
} }
/** /**
* Returns information if given value is quoted (by apostrophes or quotation marks). * Returns information if given value is quoted (by apostrophes or quotation marks)
* *
* @param mixed $value The value to check * @param mixed $value The value to check
*
* @return bool * @return bool
*/ */
public static function isQuoted($value) public static function isQuoted($value)
{ {
$pattern = self::getIsQuotedPattern(); $pattern = self::getIsQuotedPattern();
return is_scalar($value) && (bool) preg_match($pattern, $value); return is_scalar($value) && (bool)preg_match($pattern, $value);
} }
/** /**
* Returns pattern used to validate / verify if given path is a Windows-based path, e.g. "C:\path\to\file.jpg". * Returns pattern used to validate / verify if given path is a Windows-based path, e.g. "C:\path\to\file.jpg"
* *
* @return string * @return string
*/ */
@@ -625,24 +672,22 @@ class Regex
} }
/** /**
* Returns information if given path is a Windows-based path, e.g. "C:\path\to\file.jpg". * Returns information if given path is a Windows-based path, e.g. "C:\path\to\file.jpg"
* *
* @param string $path The path to verify * @param string $path The path to verify
*
* @return bool * @return bool
*/ */
public static function isWindowsBasedPath($path) public static function isWindowsBasedPath($path)
{ {
$pattern = self::getWindowsBasedPathPattern(); $pattern = self::getWindowsBasedPathPattern();
return (bool) preg_match($pattern, $path); return (bool)preg_match($pattern, $path);
} }
/** /**
* Returns information if given NIP number is valid. * Returns information if given NIP number is valid
* *
* @param string $nip A given NIP number * @param string $nip A given NIP number
*
* @return bool * @return bool
* *
* @see https://pl.wikipedia.org/wiki/NIP#Znaczenie_numeru * @see https://pl.wikipedia.org/wiki/NIP#Znaczenie_numeru
@@ -678,13 +723,13 @@ class Regex
} }
$modulo = $sum % 11; $modulo = $sum % 11;
$numberControl = ($modulo == 10) ? 0 : $modulo; $numberControl = (10 == $modulo) ? 0 : $modulo;
return $numberControl == $nip[9]; return $numberControl == $nip[9];
} }
/** /**
* Returns pattern used to validate / verify if given value is money-related value. * Returns pattern used to validate / verify if given value is money-related value
* *
* @return string * @return string
*/ */
@@ -694,17 +739,24 @@ class Regex
} }
/** /**
* Returns information if given value is valid money-related value. * Returns information if given value is valid money-related value
* *
* @param mixed $value Value to verify * @param mixed $value Value to verify
*
* @return bool * @return bool
*/ */
public static function isValidMoneyValue($value) public static function isValidMoneyValue($value)
{ {
/*
* Not a scalar value?
* Nothing to do
*/
if (!is_scalar($value)) {
return false;
}
$pattern = self::getMoneyPattern(); $pattern = self::getMoneyPattern();
return (bool) preg_match($pattern, $value); return (bool)preg_match($pattern, $value);
} }
/** /**
@@ -714,40 +766,162 @@ class Regex
* @param string $color Color to verify * @param string $color Color to verify
* @param bool $throwException (optional) If is set to true, throws an exception if given color is invalid * @param bool $throwException (optional) If is set to true, throws an exception if given color is invalid
* (default behaviour). Otherwise - not. * (default behaviour). Otherwise - not.
*
* @return string|bool
*
* @throws IncorrectColorHexLengthException * @throws IncorrectColorHexLengthException
* @throws InvalidColorHexValueException * @throws InvalidColorHexValueException
* @return string|bool
*/ */
public static function getValidColorHexValue($color, $throwException = true) public static function getValidColorHexValue($color, $throwException = true)
{ {
/*
* Not a scalar value?
* Nothing to do
*/
if (!is_scalar($color)) {
return false;
}
$color = Miscellaneous::replace($color, '/#/', ''); $color = Miscellaneous::replace($color, '/#/', '');
$length = strlen($color); $length = strlen($color);
if ($length === 3) { /*
$color = Miscellaneous::replace($color, '/(.)(.)(.)/', '$1$1$2$2$3$3'); * Color is not 3 or 6 characters long?
} else { * Nothing to do
if ($length !== 6) { */
if ($throwException) { if (3 !== $length && 6 !== $length) {
throw new IncorrectColorHexLengthException($color);
}
return false;
}
}
$pattern = self::$patterns['color'];
$match = (bool) preg_match($pattern, $color);
if (!$match) {
if ($throwException) { if ($throwException) {
throw new InvalidColorHexValueException($color); throw new IncorrectColorHexLengthException($color);
} }
return false; return false;
} }
return strtolower($color); /*
* Color is 3 characters long?
* Let's make it 6 characters long
*/
if (3 === $length) {
$color = Miscellaneous::replace($color, '/(.)(.)(.)/', '$1$1$2$2$3$3');
}
$pattern = self::$patterns['color'];
$match = (bool)preg_match($pattern, $color);
/*
* It's valid color
* Nothing to do more
*/
if ($match) {
return strtolower($color);
}
if ($throwException) {
throw new InvalidColorHexValueException($color);
}
return false;
}
/**
* Returns information if given name of bundle is valid
*
* @param string $bundleName Full name of bundle to verify, e.g. "MyExtraBundle"
* @return bool
*/
public static function isValidBundleName($bundleName)
{
/*
* Not a string?
* Nothing to do
*/
if (!is_string($bundleName)) {
return false;
}
$pattern = self::getBundleNamePattern();
return (bool)preg_match($pattern, $bundleName);
}
/**
* Returns pattern used to validate / verify name of bundle
*
* @return string
*/
public static function getBundleNamePattern()
{
return self::$patterns['bundleName'];
}
/**
* Returns pattern used to validate / verify html attribute
*
* @return string
*/
public static function getHtmlAttributePattern()
{
return self::$patterns['htmlAttribute'];
}
/**
* Returns information if given html attribute is valid
*
* @param string $htmlAttribute The html attribute to verify
* @return bool
*/
public static function isValidHtmlAttribute($htmlAttribute)
{
/*
* Not a string?
* Nothing to do
*/
if (!is_string($htmlAttribute)) {
return false;
}
$pattern = self::getHtmlAttributePattern();
return (bool)preg_match($pattern, $htmlAttribute);
}
/**
* Returns information if given html attributes are valid
*
* @param string $htmlAttributes The html attributes to verify
* @return bool
*/
public static function areValidHtmlAttributes($htmlAttributes)
{
/*
* Not a string?
* Nothing to do
*/
if (!is_string($htmlAttributes)) {
return false;
}
$pattern = self::getHtmlAttributePattern();
return (bool)preg_match_all($pattern, $htmlAttributes);
}
/**
* Returns information if given value is a binary value
*
* @param string $value Value to verify
* @return bool
*/
public static function isBinaryValue($value)
{
/*
* Not a string?
* Nothing to do
*/
if (!is_string($value)) {
return false;
}
$pattern = self::$patterns['binaryValue'];
return (bool)preg_match($pattern, $value);
} }
} }

View File

@@ -0,0 +1,235 @@
<?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;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
/**
* Useful methods for repository
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class Repository
{
/**
* Name of key responsible for sorting/position of an item in array
*
* @var string
*/
const POSITION_KEY = 'position';
/**
* Replenishes positions of given items
*
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $asLast (optional) If is set to true, items are placed at the end (default behaviour). Otherwise -
* at top.
* @param bool $force (optional) If is set to true, positions are set even there is no extreme position.
* Otherwise - if extreme position is unknown (is null) replenishment is stopped / skipped
* (default behaviour).
*/
public static function replenishPositions(array &$items, $asLast = true, $force = false)
{
$position = self::getExtremePosition($items, $asLast);
/*
* Extreme position is unknown, but it's required?
* Use 0 as default/start value
*/
if (null === $position && $force) {
$position = 0;
}
/*
* Extreme position is unknown or there are no items to sort?
* Nothing to do
*/
if (null === $position || empty($items)) {
return;
}
foreach ($items as &$item) {
/*
* The item is not sortable?
*/
if (!self::isSortable($item)) {
continue;
}
/*
* Position has been set?
* Nothing to do
*/
if (self::isSorted($item)) {
continue;
}
/*
* Calculate position
*/
if ($asLast) {
++$position;
} else {
--$position;
}
/*
* It's an object?
* Use proper method to set position
*/
if (is_object($item)) {
$item->setPosition($position);
continue;
}
/*
* It's an array
* Use proper key to set position
*/
$item[static::POSITION_KEY] = $position;
}
}
/**
* Returns extreme position (max or min) of given items
*
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $max (optional) If is set to true, maximum value is returned. Otherwise - minimum.
* @return int
*/
public static function getExtremePosition(array $items, $max = true)
{
/*
* No items?
* Nothing to do
*/
if (empty($items)) {
return null;
}
$extreme = null;
foreach ($items as $item) {
/*
* The item is not sortable?
*/
if (!self::isSortable($item)) {
continue;
}
$position = null;
/*
* Let's grab the position
*/
if (is_object($item)) {
$position = $item->getPosition();
} elseif (array_key_exists(static::POSITION_KEY, $item)) {
$position = $item[static::POSITION_KEY];
}
/*
* Maximum value is expected?
*/
if ($max) {
/*
* Position was found and it's larger than previously found position (the extreme position)?
*/
if (null === $extreme || (null !== $position && $position > $extreme)) {
$extreme = $position;
}
continue;
}
/*
* Minimum value is expected here.
* Position was found and it's smaller than previously found position (the extreme position)?
*/
if (null === $extreme || (null !== $position && $position < $extreme)) {
$extreme = $position;
}
}
return $extreme;
}
/**
* Returns query builder for given entity's repository.
* The entity should contain given property, e.g. "name".
*
* @param EntityRepository $repository Repository of the entity
* @param string $property (optional) Name of property used by the ORDER BY clause
* @param string $direction (optional) Direction used by the ORDER BY clause ("ASC" or "DESC")
* @return QueryBuilder
*/
public static function getEntityOrderedQueryBuilder(
EntityRepository $repository,
$property = 'name',
$direction = 'ASC'
) {
$alias = 'qb';
return $repository
->createQueryBuilder($alias)
->orderBy(sprintf('%s.%s', $alias, $property), $direction);
}
/**
* Returns information if given item is sortable
*
* Sortable means it's an:
* - array
* or
* - object and has getPosition() and setPosition()
*
* @param mixed $item An item to verify (object who has "getPosition()" and "setPosition()" methods or an array)
* @return bool
*/
private static function isSortable($item)
{
return is_array($item)
||
(
is_object($item)
&&
Reflection::hasMethod($item, 'getPosition')
&&
Reflection::hasMethod($item, 'setPosition')
);
}
/**
* Returns information if given item is sorted (position has been set)
*
* @param mixed $item An item to verify (object who has "getPosition()" and "setPosition()" methods or an array)
* @return bool
*/
private static function isSorted($item)
{
/*
* Given item is not sortable?
*/
if (!self::isSortable($item)) {
return false;
}
/*
* It's an object or it's an array
* and position has been set?
*/
return
(is_object($item) && null !== $item->getPosition())
||
(is_array($item) && isset($item[static::POSITION_KEY]));
}
}

View File

@@ -9,58 +9,78 @@
namespace Meritoo\Common\Utilities; namespace Meritoo\Common\Utilities;
/** /**
* Useful uri methods (only static functions). * Useful uri methods (only static functions)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Uri class Uri
{ {
/** /**
* Returns full uri string. * Returns full uri string
* *
* @param bool $withoutHost (optional) If is set to true, means that host / server name is omitted * @param bool $withoutHost (optional) If is set to true, means that host / server name is omitted
*
* @return string * @return string
*/ */
public static function getFullUri($withoutHost = false) public static function getFullUri($withoutHost = false)
{ {
$effect = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'REQUEST_URI'); $requestedUrl = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'REQUEST_URI');
if ($withoutHost) { /*
return $effect; * Unknown requested url?
* Nothing to do
*/
if (empty($requestedUrl)) {
return '';
} }
return self::getServerNameOrIp(true).$effect; /*
* Without host / server name?
* All is done
*/
if ($withoutHost) {
return $requestedUrl;
}
return self::getServerNameOrIp(true) . $requestedUrl;
} }
/** /**
* Returns server name or IP address. * Returns server name or IP address
* *
* @param bool $withProtocol (optional) If is set to true, protocol name is included. Otherwise isn't. * @param bool $withProtocol (optional) If is set to true, protocol name is included. Otherwise isn't.
*
* @return string * @return string
*/ */
public static function getServerNameOrIp($withProtocol = false) public static function getServerNameOrIp($withProtocol = false)
{ {
$protocol = ''; $host = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_HOST');
if ($withProtocol) { /*
$protocol .= self::getProtocolName().'://'; * Unknown host / server?
* Nothing to do
*/
if (empty($host)) {
return '';
} }
return $protocol.Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_HOST'); /*
* With protocol?
* Let's include the protocol
*/
if ($withProtocol) {
return sprintf('%s://%s', self::getProtocolName(), $host);
}
return $host;
} }
/** /**
* Returns protocol name. * Returns protocol name
* *
* @return string * @return string
*/ */
public static function getProtocolName() public static function getProtocolName()
{ {
$effect = '';
$matches = []; $matches = [];
$protocolData = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'SERVER_PROTOCOL'); // e.g. HTTP/1.1 $protocolData = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'SERVER_PROTOCOL'); // e.g. HTTP/1.1
$matchCount = preg_match('|(.+)\/(.+)|', $protocolData, $matches); $matchCount = preg_match('|(.+)\/(.+)|', $protocolData, $matches);
@@ -70,31 +90,28 @@ class Uri
* $matches[2] - protocol version, e.g. 1.1 * $matches[2] - protocol version, e.g. 1.1
*/ */
if ($matchCount > 0) { /*
$effect = strtolower($matches[1]); * Oops, cannot match protocol
*/
if (0 == $matchCount) {
return '';
} }
return $effect; return strtolower($matches[1]);
} }
/** /**
* Returns http referer uri. * Returns http referer uri
* *
* @return string * @return string
*/ */
public static function getRefererUri() public static function getRefererUri()
{ {
$effect = ''; return Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_REFERER');
if (filter_has_var(INPUT_SERVER, 'HTTP_REFERER')) {
$effect = Miscellaneous::getSafelyGlobalVariable(INPUT_SERVER, 'HTTP_REFERER');
}
return $effect;
} }
/** /**
* Returns user's IP address. * Returns user's IP address
* *
* @return string * @return string
*/ */
@@ -104,11 +121,10 @@ class Uri
} }
/** /**
* Returns name and version of user's web browser. * Returns name and version of user's web browser
* *
* @param bool $withVersion (optional) If is set to true, version of the browser is returned too. Otherwise - * @param bool $withVersion (optional) If is set to true, version of the browser is returned too. Otherwise -
* name only. * name only.
*
* @return string * @return string
*/ */
public static function getUserWebBrowserName($withVersion = false) public static function getUserWebBrowserName($withVersion = false)
@@ -117,9 +133,9 @@ class Uri
$knownBrowsers = [ $knownBrowsers = [
'Firefox/([\d\.]+)$' => 'Mozilla Firefox', 'Firefox/([\d\.]+)$' => 'Mozilla Firefox',
'OPR/([\d\.]+)$' => 'Opera', 'OPR/([\d\.]+)$' => 'Opera',
'Chrome/([\d\.]+)$' => 'Google Chrome', 'Chrome/([\d\.]+)$' => 'Google Chrome',
'Safari/([\d\.]+)$' => 'Apple Safari', 'Safari/([\d\.]+)$' => 'Apple Safari',
]; ];
foreach ($knownBrowsers as $pattern => $browserName) { foreach ($knownBrowsers as $pattern => $browserName) {
@@ -141,7 +157,7 @@ class Uri
} }
/** /**
* Returns user's web browser information. * Returns user's web browser information
* *
* @return string * @return string
* *
@@ -167,7 +183,7 @@ class Uri
} }
/** /**
* Returns name of user's operating system. * Returns name of user's operating system
* *
* @return string * @return string
*/ */
@@ -177,8 +193,8 @@ class Uri
$knownSystems = [ $knownSystems = [
'Linux' => 'Linux', 'Linux' => 'Linux',
'Win' => 'Windows', 'Win' => 'Windows',
'Mac' => 'Mac OS', 'Mac' => 'Mac OS',
]; ];
foreach ($knownSystems as $pattern => $systemName) { foreach ($knownSystems as $pattern => $systemName) {
@@ -194,7 +210,7 @@ class Uri
} }
/** /**
* Returns information if running server is localhost. * Returns information if running server is localhost
* *
* @return bool * @return bool
*/ */
@@ -210,27 +226,50 @@ class Uri
} }
/** /**
* Returns information if given url is external, from another server / domain. * Returns information if given url is external, from another server / domain
* *
* @param string $url The url to check * @param string $url The url to check
*
* @return bool * @return bool
*/ */
public static function isExternalUrl($url) public static function isExternalUrl($url)
{ {
/*
* Unknown url or it's just slash?
* Nothing to do
*/
if (empty($url) || '/' === $url) {
return false;
}
$currentUrl = self::getServerNameOrIp(true); $currentUrl = self::getServerNameOrIp(true);
$url = self::replenishProtocol($url); $url = self::replenishProtocol($url);
return !Regex::contains($currentUrl, $url); /*
* Let's prepare pattern of current url
*/
$search = [
':',
'/',
'.',
];
$replace = [
'\:',
'\/',
'\.',
];
$currentUrlPattern = str_replace($search, $replace, $currentUrl);
return !Regex::contains($url, $currentUrlPattern);
} }
/** /**
* Replenishes protocol in the given url. * Replenishes protocol in the given url
* *
* @param string $url The url to check and replenish * @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 * @param string $protocol (optional) The protocol which is replenished. If is empty, protocol of current request
* is used. * is used.
*
* @return string * @return string
*/ */
public static function replenishProtocol($url, $protocol = '') public static function replenishProtocol($url, $protocol = '')
@@ -269,16 +308,23 @@ class Uri
} }
/** /**
* Returns url to resource secured by given htpasswd login and password. * Returns url to resource secured by given htpasswd login and password
* *
* @param string $url A path / url to some resource, e.g. page, image, css file * @param string $url A path / url to some resource, e.g. page, image, css file
* @param string $user (optional) User name used to log in * @param string $user (optional) User name used to log in
* @param string $password (optional) User password used to log in * @param string $password (optional) User password used to log in
*
* @return string * @return string
*/ */
public static function getSecuredUrl($url, $user = '', $password = '') public static function getSecuredUrl($url, $user = '', $password = '')
{ {
/*
* Url is not provided?
* Nothing to do
*/
if (empty($url)) {
return '';
}
$protocol = self::getProtocolName(); $protocol = self::getProtocolName();
$host = self::getServerNameOrIp(); $host = self::getServerNameOrIp();
@@ -286,7 +332,7 @@ class Uri
$url = sprintf('/%s', $url); $url = sprintf('/%s', $url);
} }
$url = $host.$url; $url = $host . $url;
if (!empty($user) && !empty($password)) { if (!empty($user) && !empty($password)) {
$url = sprintf('%s:%s@%s', $user, $password, $url); $url = sprintf('%s:%s@%s', $user, $password, $url);
@@ -301,14 +347,13 @@ class Uri
* *
* @param string $url Url string * @param string $url Url string
* @param string $protocol (optional) Protocol string * @param string $protocol (optional) Protocol string
*
* @return string * @return string
*/ */
public static function addProtocolToUrl($url, $protocol = 'http') public static function addProtocolToUrl($url, $protocol = 'http')
{ {
$pattern = sprintf('/^%s.*/', $protocol); $pattern = sprintf('/^%s.*/', $protocol);
if ((bool) preg_match($pattern, $url)) { if ((bool)preg_match($pattern, $url)) {
return $url; return $url;
} }

View File

@@ -13,10 +13,10 @@ use DOMXPath;
use SimpleXMLElement; use SimpleXMLElement;
/** /**
* Useful XML-related methods (only static functions). * Useful XML-related methods (only static functions)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class Xml class Xml
{ {
@@ -26,7 +26,6 @@ class Xml
* *
* @param SimpleXMLElement $element1 First element to merge * @param SimpleXMLElement $element1 First element to merge
* @param SimpleXMLElement $element2 Second element to merge * @param SimpleXMLElement $element2 Second element to merge
*
* @return SimpleXMLElement * @return SimpleXMLElement
*/ */
public static function mergeNodes(SimpleXMLElement $element1, SimpleXMLElement $element2) public static function mergeNodes(SimpleXMLElement $element1, SimpleXMLElement $element2)
@@ -41,7 +40,7 @@ class Xml
$query = $path->query('/*/*'); $query = $path->query('/*/*');
$nodesCount = $query->length; $nodesCount = $query->length;
if ($nodesCount == 0) { if (0 == $nodesCount) {
return $element1; return $element1;
} }

View File

@@ -9,34 +9,35 @@
namespace Meritoo\Common\Test\Collection; namespace Meritoo\Common\Test\Collection;
use ArrayIterator; use ArrayIterator;
use Generator;
use Meritoo\Common\Collection\Collection; use Meritoo\Common\Collection\Collection;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class CollectionTest extends BaseTestCase class CollectionTest extends BaseTestCase
{ {
/** /**
* An empty collection. * An empty collection
* *
* @var Collection * @var Collection
*/ */
private $emptyCollection; private $emptyCollection;
/** /**
* Simple collection. * Simple collection
* *
* @var Collection * @var Collection
*/ */
private $simpleCollection; private $simpleCollection;
/** /**
* Elements of simple collection. * Elements of simple collection
* *
* @var array * @var array
*/ */
@@ -129,22 +130,39 @@ class CollectionTest extends BaseTestCase
static::assertInstanceOf(ArrayIterator::class, $this->simpleCollection->getIterator()); static::assertInstanceOf(ArrayIterator::class, $this->simpleCollection->getIterator());
} }
public function testAdd() /**
* @param mixed $element The element to add
* @param int $expectedCount Expected count of elements in collection
* @param int $expectedIndex Expected index of added element in collection
* @param Collection $collection The collection
*
* @dataProvider provideElementToAdd
*/
public function testAddWithoutIndex($element, $expectedCount, $expectedIndex, Collection $collection)
{ {
$this->emptyCollection->add('test1'); $collection->add($element);
static::assertTrue($this->emptyCollection->has('test1')); static::assertTrue($collection->has($element));
static::assertEquals(1, $this->emptyCollection->count()); static::assertEquals($expectedCount, $collection->count());
static::assertEquals('test1', $this->emptyCollection[0]); static::assertEquals($element, $collection[$expectedIndex]);
} }
public function testAddWithIndex() /**
* @param mixed $element The element to add
* @param mixed $index Index of element to add
* @param int $expectedCount Expected count of elements in collection
* @param int $expectedIndex Expected index of added element in collection
* @param Collection $collection The collection
*
* @dataProvider provideElementToAddWithIndex
*/
public function testAddWithIndex($element, $index, $expectedCount, $expectedIndex, Collection $collection)
{ {
$this->emptyCollection->add('test2', 1234); $collection->add($element, $index);
static::assertTrue($this->emptyCollection->has('test2')); static::assertTrue($collection->has($element));
static::assertEquals(1, $this->emptyCollection->count()); static::assertEquals($expectedCount, $collection->count());
static::assertEquals('test2', $this->emptyCollection[1234]); static::assertEquals($element, $collection[$expectedIndex]);
} }
public function testAddMultipleUsingEmptyArray() public function testAddMultipleUsingEmptyArray()
@@ -306,7 +324,88 @@ class CollectionTest extends BaseTestCase
public function testExistsVisibilityAndArguments() public function testExistsVisibilityAndArguments()
{ {
$this->verifyMethodVisibilityAndArguments(Collection::class, 'exists', OopVisibilityType::IS_PRIVATE, 1, 1); static::assertMethodVisibilityAndArguments(Collection::class, 'exists', OopVisibilityType::IS_PRIVATE, 1, 1);
}
/**
* Provides element to add to collection
*
* @return Generator
*/
public function provideElementToAdd()
{
$collection = new Collection();
yield[
'test1',
1,
0,
$collection,
];
yield[
'test2',
2,
1,
$collection,
];
yield[
'test3',
3,
2,
$collection,
];
}
/**
* Provides element with index to add to collection
*
* @return Generator
*/
public function provideElementToAddWithIndex()
{
$collection = new Collection();
yield[
'test1',
'aa',
1,
'aa',
$collection,
];
yield[
'test2',
'oo',
2,
'oo',
$collection,
];
yield[
'test3',
null,
3,
0,
$collection,
];
yield[
'test4',
'',
4,
1,
$collection,
];
yield[
'test5',
'vv',
5,
'vv',
$collection,
];
} }
/** /**

View File

@@ -9,17 +9,23 @@
namespace Meritoo\Common\Test\Exception\Base; namespace Meritoo\Common\Test\Exception\Base;
use Meritoo\Common\Exception\Base\UnknownTypeException; use Meritoo\Common\Exception\Base\UnknownTypeException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\Base\BaseType; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class UnknownTypeExceptionTest extends PHPUnit_Framework_TestCase class UnknownTypeExceptionTest extends BaseTestCase
{ {
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownTestTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testWithoutException() public function testWithoutException()
{ {
self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2')); self::assertEquals('Test 2', (new TestService())->getTranslatedType('test_2'));
@@ -27,16 +33,16 @@ class UnknownTypeExceptionTest extends PHPUnit_Framework_TestCase
public function testTheException() public function testTheException()
{ {
$this->expectException(UnknownTestTypeException::class); $this->setExpectedException(UnknownTestTypeException::class);
self::assertEmpty((new TestService())->getTranslatedType('test_3')); self::assertEmpty((new TestService())->getTranslatedType('test_3'));
} }
} }
/** /**
* Type of something (for testing purposes). * Type of something (for testing purposes)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class TestType extends BaseType class TestType extends BaseType
{ {
@@ -46,40 +52,42 @@ class TestType extends BaseType
} }
/** /**
* An exception used while type of something is unknown (for testing purposes). * An exception used while type of something is unknown (for testing purposes)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class UnknownTestTypeException extends UnknownTypeException class UnknownTestTypeException extends UnknownTypeException
{ {
/** /**
* Class constructor. * Creates exception
* *
* @param int|string $unknownType The unknown type of something (for testing purposes) * @param string $unknownType The unknown type of something (for testing purposes)
* @return UnknownTestTypeException
*/ */
public function __construct($unknownType) public static function createException($unknownType)
{ {
parent::__construct($unknownType, new TestType(), 'type of something used for testing'); /* @var UnknownTestTypeException $exception */
$exception = parent::create($unknownType, new TestType(), 'type of something used for testing');
return $exception;
} }
} }
/** /**
* Service used together with type of something (for testing purposes). * Service used together with type of something (for testing purposes)
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class TestService class TestService
{ {
/** /**
* Returns translated type (for testing purposes). * Returns translated type (for testing purposes)
* *
* @param string $type Type of something (for testing purposes) * @param string $type Type of something (for testing purposes)
*
* @return string
*
* @throws UnknownTestTypeException * @throws UnknownTestTypeException
* @return string
*/ */
public function getTranslatedType($type) public function getTranslatedType($type)
{ {

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\Type\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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class UnknownDatePartTypeExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownDatePartTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $unknownDatePart Type of date part, e.g. "year". One of DatePartType class constants.
* @param string $value Incorrect value
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideDatePartAndValue
*/
public function testMessage($unknownDatePart, $value, $expectedMessage)
{
$exception = UnknownDatePartTypeException::createException($unknownDatePart, $value);
static::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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class EmptyFileExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $emptyFilePath Path of the empty file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testMessage($emptyFilePath, $expectedMessage)
{
$exception = EmptyFileException::create($emptyFilePath);
static::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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class EmptyFilePathExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(EmptyFilePathException::class, OopVisibilityType::IS_PUBLIC, 3);
}
public function testConstructorMessage()
{
$exception = EmptyFilePathException::create();
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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class NotExistingFileExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(NotExistingFileException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $notExistingFilePath Path of not existing (or not readable) file
* @param string $expectedMessage Expected exception's message
*
* @dataProvider providePathOfFile
*/
public function testConstructorMessage($notExistingFilePath, $expectedMessage)
{
$exception = NotExistingFileException::create($notExistingFilePath);
static::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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class DisabledMethodExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(DisabledMethodException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $disabledMethod Name of the disabled method
* @param string $alternativeMethod Name of the alternative method
* @param string $expectedMessage Expected exception's message
*
* @internal param string $emptyFilePath Path of the empty file
* @dataProvider provideMethodsNames
*/
public function testConstructorMessage($disabledMethod, $alternativeMethod, $expectedMessage)
{
$exception = DisabledMethodException::create($disabledMethod, $alternativeMethod);
static::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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class CannotResolveClassNameExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(CannotResolveClassNameException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @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 = CannotResolveClassNameException::create($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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class MissingChildClassesExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(MissingChildClassesException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @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 = MissingChildClassesException::create($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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class TooManyChildClassesExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(TooManyChildClassesException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @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 = TooManyChildClassesException::create($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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class IncorrectColorHexLengthExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(IncorrectColorHexLengthException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $color Incorrect hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = IncorrectColorHexLengthException::create($color);
static::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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidColorHexValueExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidColorHexValueException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $color Invalid hexadecimal value of color
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideColor
*/
public function testConstructorMessage($color, $expectedMessage)
{
$exception = InvalidColorHexValueException::create($color);
static::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,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\Regex;
use Generator;
use Meritoo\Common\Exception\Regex\InvalidHtmlAttributesException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\OopVisibilityType;
/**
* Test case of an exception used while html attributes are invalid
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidHtmlAttributesExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidHtmlAttributesException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $htmlAttributes Invalid html attributes
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideHtmlAttributes
*/
public function testConstructorMessage($htmlAttributes, $expectedMessage)
{
$exception = InvalidHtmlAttributesException::create($htmlAttributes);
static::assertEquals($expectedMessage, $exception->getMessage());
}
/**
* Provides html attributes
*
* @return Generator
*/
public function provideHtmlAttributes()
{
$template = 'HTML attributes \'%s\' are invalid. Is there everything ok?';
yield[
'abc = def',
sprintf($template, 'abc = def'),
];
yield[
'abc = def ghi = jkl',
sprintf($template, 'abc = def ghi = jkl'),
];
yield[
'abc=def ghi=jkl',
sprintf($template, 'abc=def ghi=jkl'),
];
}
}

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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class InvalidUrlExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(InvalidUrlException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $url Invalid url
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUrl
*/
public function testConstructorMessage($url, $expectedMessage)
{
$exception = InvalidUrlException::create($url);
static::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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class UnknownOopVisibilityTypeExceptionTest extends BaseTestCase
{
public function testConstructorVisibilityAndArguments()
{
static::assertConstructorVisibilityAndArguments(UnknownOopVisibilityTypeException::class, OopVisibilityType::IS_PUBLIC, 3);
}
/**
* @param string $unknownType Unknown OOP-related visibility
* @param string $expectedMessage Expected exception's message
*
* @dataProvider provideUnknownType
*/
public function testConstructorMessage($unknownType, $expectedMessage)
{
$exception = UnknownOopVisibilityTypeException::createException($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,40 +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 Meritoo\Common\Utilities\Bundle;
use PHPUnit_Framework_TestCase;
/**
* 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

@@ -1,129 +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 Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Locale;
/**
* Tests of the useful locale methods.
*
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl>
* @copyright Meritoo.pl
*/
class LocaleTest extends BaseTestCase
{
/**
* @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

@@ -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

@@ -1,291 +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\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

@@ -1,79 +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 Meritoo\Common\Test\Base\BaseTestCase;
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 BaseTestCase
{
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,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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class SimpleTestCase extends BaseTestCase
{
}

View File

@@ -9,17 +9,22 @@
namespace Meritoo\Common\Test\Type\Base; namespace Meritoo\Common\Test\Type\Base;
use Generator; use Generator;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\Base\BaseType; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class BaseTypeTest extends PHPUnit_Framework_TestCase class BaseTypeTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(BaseType::class);
}
/** /**
* @param BaseType $type Type of something * @param BaseType $type Type of something
* @param array $expectedTypes Expected concrete types of given instance of type * @param array $expectedTypes Expected concrete types of given instance of type
@@ -45,7 +50,7 @@ class BaseTypeTest extends PHPUnit_Framework_TestCase
} }
/** /**
* Provides type of something for testing the getAll() method. * Provides type of something for testing the getAll() method
* *
* @return Generator * @return Generator
*/ */
@@ -66,7 +71,7 @@ class BaseTypeTest extends PHPUnit_Framework_TestCase
} }
/** /**
* Provides type of something for testing the isCorrectType() method. * Provides type of something for testing the isCorrectType() method
* *
* @return Generator * @return Generator
*/ */
@@ -177,20 +182,20 @@ class BaseTypeTest extends PHPUnit_Framework_TestCase
} }
/** /**
* Empty type of something used for testing. * Empty type of something used for testing
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class TestEmptyType extends BaseType class TestEmptyType extends BaseType
{ {
} }
/** /**
* Type of something used for testing. * Type of something used for testing
* *
* @author Krzysztof Niziol <krzysztof.niziol@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class TestType extends BaseType class TestType extends BaseType
{ {

View File

@@ -12,10 +12,10 @@ use Meritoo\Common\Test\Base\BaseTypeTestCase;
use Meritoo\Common\Type\DatePartType; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class DatePartTypeTest extends BaseTypeTestCase class DatePartTypeTest extends BaseTypeTestCase
{ {
@@ -25,12 +25,12 @@ class DatePartTypeTest extends BaseTypeTestCase
protected function getAllExpectedTypes() protected function getAllExpectedTypes()
{ {
return [ return [
'DAY' => DatePartType::DAY, 'DAY' => DatePartType::DAY,
'HOUR' => DatePartType::HOUR, 'HOUR' => DatePartType::HOUR,
'MINUTE' => DatePartType::MINUTE, 'MINUTE' => DatePartType::MINUTE,
'MONTH' => DatePartType::MONTH, 'MONTH' => DatePartType::MONTH,
'SECOND' => DatePartType::SECOND, 'SECOND' => DatePartType::SECOND,
'YEAR' => DatePartType::YEAR, 'YEAR' => DatePartType::YEAR,
]; ];
} }

View File

@@ -6,25 +6,25 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Meritoo\Common\Test\Utilities; namespace Meritoo\Common\Test\Type;
use DateTime; use DateTime;
use Generator; 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\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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class DatePeriodTest extends BaseTestCase class DatePeriodTest extends BaseTypeTestCase
{ {
public function testConstructorVisibilityAndArguments() 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()); 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 DatePeriod $period The date period to verify
* @param string $format Format used to format the date * @param string $format Format used to format the date
@@ -110,7 +83,7 @@ class DatePeriodTest extends BaseTestCase
} }
/** /**
* Provides the start and end date of date period. * Provides the start and end date of date period
* *
* @return Generator * @return Generator
*/ */
@@ -143,37 +116,7 @@ class DatePeriodTest extends BaseTestCase
} }
/** /**
* Provides incorrect period. * Provides period and incorrect format of date to verify
*
* @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 * @return Generator
*/ */
@@ -199,7 +142,7 @@ class DatePeriodTest extends BaseTestCase
} }
/** /**
* Provides period and format of date to verify. * Provides period and format of date to verify
* *
* @return Generator * @return Generator
*/ */
@@ -270,4 +213,68 @@ class DatePeriodTest extends BaseTestCase
'2002-02-02 00:00', '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; namespace Meritoo\Common\Test\Utilities;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Arrays; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class ArraysTest extends PHPUnit_Framework_TestCase class ArraysTest extends BaseTestCase
{ {
private $simpleArray; private $simpleArray;
private $simpleArrayWithKeys; private $simpleArrayWithKeys;
@@ -25,6 +25,11 @@ class ArraysTest extends PHPUnit_Framework_TestCase
private $complexArray; private $complexArray;
private $superComplexArray; private $superComplexArray;
public function testConstructor()
{
static::assertHasNoConstructor(Arrays::class);
}
public function testValues2string() public function testValues2string()
{ {
/* /*
@@ -67,8 +72,8 @@ class ArraysTest extends PHPUnit_Framework_TestCase
self::assertEquals('', Arrays::values2csv($this->simpleArray)); self::assertEquals('', Arrays::values2csv($this->simpleArray));
self::assertEquals("lorem,ipsum,dolor,sit,amet\n" self::assertEquals("lorem,ipsum,dolor,sit,amet\n"
."consectetur,adipiscing,elit\n" . "consectetur,adipiscing,elit\n"
.'donec,sagittis,fringilla,eleifend', Arrays::values2csv($this->twoDimensionsArray)); . 'donec,sagittis,fringilla,eleifend', Arrays::values2csv($this->twoDimensionsArray));
} }
public function testGetFirstKey() public function testGetFirstKey()
@@ -175,7 +180,7 @@ class ArraysTest extends PHPUnit_Framework_TestCase
{ {
$effect = [ $effect = [
'nullam' => 'donec', 'nullam' => 'donec',
'x' => [ 'x' => [
'vitae' => [ 'vitae' => [
'x' => 'quis', 'x' => 'quis',
], ],
@@ -188,7 +193,7 @@ class ArraysTest extends PHPUnit_Framework_TestCase
self::assertEquals([ self::assertEquals([
'x' => 'sit', 'x' => 'sit',
4 => 'amet', 4 => 'amet',
], Arrays::replaceArrayKeys($this->simpleArray, '|[0-3]+|', 'x')); ], Arrays::replaceArrayKeys($this->simpleArray, '|[0-3]+|', 'x'));
} }
@@ -370,19 +375,19 @@ letsTest[2] = value_2;';
'lorem' => 0, 'lorem' => 0,
'ipsum' => 1, 'ipsum' => 1,
'dolor' => 2, 'dolor' => 2,
'sit' => 3, 'sit' => 3,
'amet' => 4, 'amet' => 4,
], ],
[ [
'consectetur' => 0, 'consectetur' => 0,
'adipiscing' => 1, 'adipiscing' => 1,
'elit' => 2, 'elit' => 2,
], ],
[ [
'donec' => 0, 'donec' => 0,
'sagittis' => 1, 'sagittis' => 1,
'fringilla' => 2, 'fringilla' => 2,
'eleifend' => 3, 'eleifend' => 3,
], ],
]; ];
@@ -428,16 +433,16 @@ letsTest[2] = value_2;';
*/ */
$array = [ $array = [
'light' => '#fff', 'light' => '#fff',
'dark' => '#000', 'dark' => '#000',
]; ];
self::assertEquals($array, Arrays::string2array('light:#fff|dark:#000')); self::assertEquals($array, Arrays::string2array('light:#fff|dark:#000'));
self::assertEquals($array, Arrays::string2array('light: #fff | dark: #000')); self::assertEquals($array, Arrays::string2array('light: #fff | dark: #000'));
$array = [ $array = [
'red' => '#f00', 'red' => '#f00',
'green' => '#0f0', 'green' => '#0f0',
'blue' => '#00f', 'blue' => '#00f',
]; ];
self::assertEquals($array, Arrays::string2array('red:#f00|green:#0f0|blue:#00f')); self::assertEquals($array, Arrays::string2array('red:#f00|green:#0f0|blue:#00f'));
@@ -489,12 +494,12 @@ letsTest[2] = value_2;';
$keys16 = [ $keys16 = [
'a' => 'lorem', 'a' => 'lorem',
11 => 'amet', 11 => 'amet',
]; ];
$keys17 = [ $keys17 = [
'a' => 'lorem', 'a' => 'lorem',
11 => 'amet', 11 => 'amet',
'c' => 'sit__', 'c' => 'sit__',
]; ];
@@ -518,16 +523,16 @@ letsTest[2] = value_2;';
* Using default separator and other default arguments * Using default separator and other default arguments
*/ */
$expected = [ $expected = [
'lorem.ipsum.dolor' => 'sit', 'lorem.ipsum.dolor' => 'sit',
'lorem.ipsum.diam.non' => 'egestas', 'lorem.ipsum.diam.non' => 'egestas',
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'mollis' => 1234, 'mollis' => 1234,
2 => [], 2 => [],
'sit.nullam' => 'donec', 'sit.nullam' => 'donec',
'sit.aliquet.vitae.ligula' => 'quis', 'sit.aliquet.vitae.ligula' => 'quis',
'sit.0' => 'elit', 'sit.0' => 'elit',
'amet.0' => 'iaculis', 'amet.0' => 'iaculis',
'amet.1' => 'primis', 'amet.1' => 'primis',
]; ];
self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray)); self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray));
@@ -537,16 +542,16 @@ letsTest[2] = value_2;';
*/ */
$separator = ' -> '; $separator = ' -> ';
$expected = [ $expected = [
sprintf('lorem%sipsum%sdolor', $separator, $separator) => 'sit', sprintf('lorem%sipsum%sdolor', $separator, $separator) => 'sit',
sprintf('lorem%sipsum%sdiam%snon', $separator, $separator, $separator) => 'egestas', sprintf('lorem%sipsum%sdiam%snon', $separator, $separator, $separator) => 'egestas',
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'mollis' => 1234, 'mollis' => 1234,
2 => [], 2 => [],
sprintf('sit%snullam', $separator) => 'donec', sprintf('sit%snullam', $separator) => 'donec',
sprintf('sit%saliquet%svitae%sligula', $separator, $separator, $separator) => 'quis', sprintf('sit%saliquet%svitae%sligula', $separator, $separator, $separator) => 'quis',
sprintf('sit%s0', $separator) => 'elit', sprintf('sit%s0', $separator) => 'elit',
sprintf('amet%s0', $separator) => 'iaculis', sprintf('amet%s0', $separator) => 'iaculis',
sprintf('amet%s1', $separator) => 'primis', sprintf('amet%s1', $separator) => 'primis',
]; ];
self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray, $separator)); self::assertEquals($expected, Arrays::getLastElementsPaths($this->complexArray, $separator));
@@ -555,16 +560,16 @@ letsTest[2] = value_2;';
* Special exception: do not use, stop recursive on the "diam" key * Special exception: do not use, stop recursive on the "diam" key
*/ */
$expected = [ $expected = [
'lorem.ipsum.dolor' => 'sit', 'lorem.ipsum.dolor' => 'sit',
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'mollis' => 1234, 'mollis' => 1234,
2 => [], 2 => [],
'sit.nullam' => 'donec', 'sit.nullam' => 'donec',
'sit.aliquet.vitae.ligula' => 'quis', 'sit.aliquet.vitae.ligula' => 'quis',
'sit.0' => 'elit', 'sit.0' => 'elit',
'amet.0' => 'iaculis', 'amet.0' => 'iaculis',
'amet.1' => 'primis', 'amet.1' => 'primis',
'lorem.ipsum.diam' => [ 'lorem.ipsum.diam' => [
'non' => 'egestas', 'non' => 'egestas',
], ],
]; ];
@@ -579,17 +584,17 @@ letsTest[2] = value_2;';
*/ */
$expected = [ $expected = [
'lorem . ipsum . dolor' => 'sit', 'lorem . ipsum . dolor' => 'sit',
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'mollis' => 1234, 'mollis' => 1234,
2 => [], 2 => [],
'sit . nullam' => 'donec', 'sit . nullam' => 'donec',
'sit . 0' => 'elit', 'sit . 0' => 'elit',
'amet . 0' => 'iaculis', 'amet . 0' => 'iaculis',
'amet . 1' => 'primis', 'amet . 1' => 'primis',
'lorem . ipsum . diam' => [ 'lorem . ipsum . diam' => [
'non' => 'egestas', 'non' => 'egestas',
], ],
'sit . aliquet' => [ 'sit . aliquet' => [
'vitae' => [ 'vitae' => [
'ligula' => 'quis', 'ligula' => 'quis',
], ],
@@ -623,12 +628,12 @@ letsTest[2] = value_2;';
2, 2,
3, 3,
], ],
'primis > 0' => [ 'primis > 0' => [
'in', 'in',
'faucibus', 'faucibus',
'orci', 'orci',
], ],
'primis > 1' => [ 'primis > 1' => [
'luctus', 'luctus',
'et', 'et',
'ultrices', 'ultrices',
@@ -653,14 +658,14 @@ letsTest[2] = value_2;';
*/ */
$expected = [ $expected = [
'lorem > ipsum > dolor' => 'sit', 'lorem > ipsum > dolor' => 'sit',
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'mollis' => 1234, 'mollis' => 1234,
2 => [], 2 => [],
'sit > nullam' => 'donec', 'sit > nullam' => 'donec',
'sit > 0' => 'elit', 'sit > 0' => 'elit',
'amet > 0' => 'iaculis', 'amet > 0' => 'iaculis',
'amet > 1' => 'primis', 'amet > 1' => 'primis',
'lorem > ipsum > diam' => [ 'lorem > ipsum > diam' => [
'non' => 'egestas', 'non' => 'egestas',
], ],
'sit > aliquet > vitae' => [ 'sit > aliquet > vitae' => [
@@ -679,7 +684,7 @@ letsTest[2] = value_2;';
* Stop building of paths on these paths (verify paths only) * Stop building of paths on these paths (verify paths only)
*/ */
$expected = [ $expected = [
'ipsum > quis > vestibulum > porta-1' => [ 'ipsum > quis > vestibulum > porta-1' => [
'turpis', 'turpis',
'urna', 'urna',
], ],
@@ -691,13 +696,13 @@ letsTest[2] = value_2;';
], ],
], ],
], ],
'ipsum > quis > vestibulum > porta-3 > 0' => 1, 'ipsum > quis > vestibulum > porta-3 > 0' => 1,
'ipsum > quis > vestibulum > porta-3 > 1' => 2, 'ipsum > quis > vestibulum > porta-3 > 1' => 2,
'ipsum > quis > vestibulum > porta-3 > 2' => 3, 'ipsum > quis > vestibulum > porta-3 > 2' => 3,
'primis > 0 > 0' => 'in', 'primis > 0 > 0' => 'in',
'primis > 0 > 1' => 'faucibus', 'primis > 0 > 1' => 'faucibus',
'primis > 0 > 2' => 'orci', 'primis > 0 > 2' => 'orci',
'primis > 1' => [ 'primis > 1' => [
'luctus', 'luctus',
'et', 'et',
'ultrices', 'ultrices',
@@ -716,7 +721,7 @@ letsTest[2] = value_2;';
* Stop building of paths if path contains any of these part (verify part of paths only) * Stop building of paths if path contains any of these part (verify part of paths only)
*/ */
$expected = [ $expected = [
'ipsum > quis > vestibulum > porta-1' => [ 'ipsum > quis > vestibulum > porta-1' => [
'turpis', 'turpis',
'urna', 'urna',
], ],
@@ -726,15 +731,15 @@ letsTest[2] = value_2;';
'aliquam', 'aliquam',
], ],
], ],
'ipsum > quis > vestibulum > porta-3 > 0' => 1, 'ipsum > quis > vestibulum > porta-3 > 0' => 1,
'ipsum > quis > vestibulum > porta-3 > 1' => 2, 'ipsum > quis > vestibulum > porta-3 > 1' => 2,
'ipsum > quis > vestibulum > porta-3 > 2' => 3, 'ipsum > quis > vestibulum > porta-3 > 2' => 3,
'primis > 0' => [ 'primis > 0' => [
'in', 'in',
'faucibus', 'faucibus',
'orci', 'orci',
], ],
'primis > 1' => [ 'primis > 1' => [
'luctus', 'luctus',
'et', 'et',
'ultrices', 'ultrices',
@@ -830,7 +835,7 @@ letsTest[2] = value_2;';
]; ];
$existingKeys = [ $existingKeys = [
'simpleArray' => [ 'simpleArray' => [
1, 1,
3, 3,
4, 4,
@@ -839,11 +844,11 @@ letsTest[2] = value_2;';
'dolor', 'dolor',
'amet', 'amet',
], ],
'twoDimensionsArray' => [ 'twoDimensionsArray' => [
2, 2,
3, 3,
], ],
'complexArray' => [ 'complexArray' => [
'sit', 'sit',
'aliquet', 'aliquet',
'vitae', 'vitae',
@@ -883,7 +888,7 @@ letsTest[2] = value_2;';
2, 2,
2, 2,
], ],
'complexArray' => [ 'complexArray' => [
[ [
'lorem', 'lorem',
'ipsum', 'ipsum',
@@ -989,22 +994,22 @@ letsTest[2] = value_2;';
* Positive case - multi-dimensions array * Positive case - multi-dimensions array
*/ */
$effect = [ $effect = [
'amet' => [ 'amet' => [
'iaculis', 'iaculis',
'primis', 'primis',
], ],
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'lorem' => [ 'lorem' => [
'ipsum' => [ 'ipsum' => [
'dolor' => 'sit', 'dolor' => 'sit',
'diam' => [ 'diam' => [
'non' => 'egestas', 'non' => 'egestas',
], ],
], ],
], ],
'mollis' => 1234, 'mollis' => 1234,
'sit' => [ 'sit' => [
'nullam' => 'donec', 'nullam' => 'donec',
'aliquet' => [ 'aliquet' => [
'vitae' => [ 'vitae' => [
'ligula' => 'quis', 'ligula' => 'quis',
@@ -1012,7 +1017,7 @@ letsTest[2] = value_2;';
], ],
'elit', 'elit',
], ],
2 => [], 2 => [],
]; ];
self::assertEquals($effect, Arrays::ksortRecursive($this->complexArray)); self::assertEquals($effect, Arrays::ksortRecursive($this->complexArray));
@@ -1021,23 +1026,23 @@ letsTest[2] = value_2;';
* Positive case - multi-dimensions array - with options of ksort() function * Positive case - multi-dimensions array - with options of ksort() function
*/ */
$effect = [ $effect = [
2 => [], 2 => [],
'amet' => [ 'amet' => [
'iaculis', 'iaculis',
'primis', 'primis',
], ],
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'lorem' => [ 'lorem' => [
'ipsum' => [ 'ipsum' => [
'dolor' => 'sit', 'dolor' => 'sit',
'diam' => [ 'diam' => [
'non' => 'egestas', 'non' => 'egestas',
], ],
], ],
], ],
'mollis' => 1234, 'mollis' => 1234,
'sit' => [ 'sit' => [
'nullam' => 'donec', 'nullam' => 'donec',
'aliquet' => [ 'aliquet' => [
'vitae' => [ 'vitae' => [
'ligula' => 'quis', 'ligula' => 'quis',
@@ -1086,7 +1091,7 @@ letsTest[2] = value_2;';
'dolor', 'dolor',
'sit', 'sit',
], ],
'amet' => [ 'amet' => [
'consectetur', 'consectetur',
'adipiscing' => [ 'adipiscing' => [
'elit' => [ 'elit' => [
@@ -1105,10 +1110,10 @@ letsTest[2] = value_2;';
'sit', 'sit',
Arrays::POSITION_KEY_NAME => 1, Arrays::POSITION_KEY_NAME => 1,
], ],
'amet' => [ 'amet' => [
'consectetur', 'consectetur',
'adipiscing' => [ 'adipiscing' => [
'elit' => [ 'elit' => [
'cras', 'cras',
'quis', 'quis',
'ligula', 'ligula',
@@ -1233,7 +1238,7 @@ letsTest[2] = value_2;';
$sorted = [ $sorted = [
'dolor' => 'sit', 'dolor' => 'sit',
'amet' => 'consectetur', 'amet' => 'consectetur',
'Lorem' => 'ipsum', 'Lorem' => 'ipsum',
]; ];
@@ -1306,9 +1311,9 @@ letsTest[2] = value_2;';
* An array with elements that contain separator * An array with elements that contain separator
*/ */
$array = [ $array = [
'lorem'.$separator, 'lorem' . $separator,
'ipsum', 'ipsum',
$separator.'dolor', $separator . 'dolor',
]; ];
self::assertEquals(implode($separator, [ self::assertEquals(implode($separator, [
@@ -1658,7 +1663,7 @@ letsTest[2] = value_2;';
} }
/** /**
* Provides simple array to set/replace values with keys. * Provides simple array to set/replace values with keys
* *
* @return \Generator * @return \Generator
*/ */
@@ -1691,14 +1696,14 @@ letsTest[2] = value_2;';
'Lorem' => 0, 'Lorem' => 0,
'ipsum' => 1, 'ipsum' => 1,
'dolor' => 2, 'dolor' => 2,
'sit' => 3, 'sit' => 3,
'amet' => 4, 'amet' => 4,
], ],
]; ];
} }
/** /**
* Provides an array with duplicated values to set/replace values with keys. * Provides an array with duplicated values to set/replace values with keys
* *
* @return \Generator * @return \Generator
*/ */
@@ -1708,18 +1713,18 @@ letsTest[2] = value_2;';
[ [
'lorem' => 'ipsum', 'lorem' => 'ipsum',
'dolor' => 'ipsum', 'dolor' => 'ipsum',
'sit' => 'amet', 'sit' => 'amet',
'diam' => 'non', 'diam' => 'non',
'elit' => 'non', 'elit' => 'non',
'in' => 'non', 'in' => 'non',
], ],
[ [
'ipsum' => [ 'ipsum' => [
'lorem', 'lorem',
'dolor', 'dolor',
], ],
'amet' => 'sit', 'amet' => 'sit',
'non' => [ 'non' => [
'diam', 'diam',
'elit', 'elit',
'in', 'in',
@@ -1729,14 +1734,14 @@ letsTest[2] = value_2;';
yield[ yield[
[ [
'lorem' => [ 'lorem' => [
'diam' => 'non', 'diam' => 'non',
'elit' => 'non', 'elit' => 'non',
'in' => 'non', 'in' => 'non',
], ],
'dolor1' => 'ipsum', 'dolor1' => 'ipsum',
'dolor2' => 'ipsum', 'dolor2' => 'ipsum',
'sit' => 'amet', 'sit' => 'amet',
], ],
[ [
'lorem' => [ 'lorem' => [
@@ -1750,7 +1755,7 @@ letsTest[2] = value_2;';
'dolor1', 'dolor1',
'dolor2', 'dolor2',
], ],
'amet' => 'sit', 'amet' => 'sit',
], ],
]; ];
} }
@@ -1773,7 +1778,7 @@ letsTest[2] = value_2;';
$this->simpleArrayWithKeys = [ $this->simpleArrayWithKeys = [
'Lorem' => 'ipsum', 'Lorem' => 'ipsum',
'dolor' => 'sit', 'dolor' => 'sit',
'amet' => 'consectetur', 'amet' => 'consectetur',
]; ];
$this->twoDimensionsArray = [ $this->twoDimensionsArray = [
@@ -1798,19 +1803,19 @@ letsTest[2] = value_2;';
]; ];
$this->complexArray = [ $this->complexArray = [
'lorem' => [ 'lorem' => [
'ipsum' => [ 'ipsum' => [
'dolor' => 'sit', 'dolor' => 'sit',
'diam' => [ 'diam' => [
'non' => 'egestas', 'non' => 'egestas',
], ],
], ],
], ],
'consectetur' => 'adipiscing', 'consectetur' => 'adipiscing',
'mollis' => 1234, 'mollis' => 1234,
2 => [], 2 => [],
'sit' => [ 'sit' => [
'nullam' => 'donec', 'nullam' => 'donec',
'aliquet' => [ 'aliquet' => [
'vitae' => [ 'vitae' => [
'ligula' => 'quis', 'ligula' => 'quis',
@@ -1818,14 +1823,14 @@ letsTest[2] = value_2;';
], ],
'elit', 'elit',
], ],
'amet' => [ 'amet' => [
'iaculis', 'iaculis',
'primis', 'primis',
], ],
]; ];
$this->superComplexArray = [ $this->superComplexArray = [
'ipsum' => [ 'ipsum' => [
'quis' => [ 'quis' => [
'vestibulum' => [ 'vestibulum' => [
'porta-1' => [ 'porta-1' => [

View File

@@ -0,0 +1,252 @@
<?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 Generator;
use Meritoo\Common\Exception\Bundle\IncorrectBundleNameException;
use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Bundle;
/**
* Test case of the useful methods for bundle
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
*/
class BundleTest extends BaseTestCase
{
public function testConstructor()
{
static::assertHasNoConstructor(Bundle::class);
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
*
* @throws IncorrectBundleNameException
* @dataProvider provideEmptyViewPathAndBundle
*/
public function testGetBundleViewPathUsingEmptyPathAndBundle($viewPath, $bundleName)
{
self::assertNull(Bundle::getBundleViewPath($viewPath, $bundleName));
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
*
* @dataProvider provideViewPathAndIncorrectBundleName
*/
public function testGetBundleViewPathUsingIncorrectBundleName($viewPath, $bundleName)
{
$template = 'Name of bundle \'%s\' is incorrect. It should start with big letter and end with "Bundle". Is'
. ' there everything ok?';
$message = sprintf($template, $bundleName);
$this->setExpectedException(IncorrectBundleNameException::class, $message);
Bundle::getBundleViewPath($viewPath, $bundleName);
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $expected Expected path to view / template
*
* @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundle
*/
public function testGetBundleViewPathUsingDefaultExtension($viewPath, $bundleName, $expected)
{
self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName));
}
/**
* @param string $viewPath Path of the view / template, e.g. "MyDirectory/my-template"
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $extension (optional) Extension of the view / template
* @param string $expected Expected path to view / template
*
* @throws IncorrectBundleNameException
* @dataProvider provideViewPathAndBundleAndExtension
*/
public function testGetBundleViewPathUsingCustomExtension($viewPath, $bundleName, $extension, $expected)
{
self::assertEquals($expected, Bundle::getBundleViewPath($viewPath, $bundleName, $extension));
}
/**
* @param mixed $emptyValue Empty value, e.g. ""
*
* @throws IncorrectBundleNameException
* @dataProvider provideEmptyValue
*/
public function testGetShortBundleNameUsingEmptyValue($emptyValue)
{
$this->setExpectedException(IncorrectBundleNameException::class);
Bundle::getShortBundleName($emptyValue);
}
/**
* @param string $bundleName Full name of the bundle, e.g. "MyExtraBundle"
*
* @throws IncorrectBundleNameException
* @dataProvider provideIncorrectBundleName
*/
public function testGetShortBundleNameUsingIncorrectBundleName($bundleName)
{
$this->setExpectedException(IncorrectBundleNameException::class);
Bundle::getShortBundleName($bundleName);
}
/**
* @param string $fullBundleName Full name of the bundle, e.g. "MyExtraBundle"
* @param string $shortBundleName Short name of bundle (without "Bundle")
*
* @throws IncorrectBundleNameException
* @dataProvider provideFullAndShortBundleName
*/
public function testGetShortBundleName($fullBundleName, $shortBundleName)
{
self::assertEquals($shortBundleName, Bundle::getShortBundleName($fullBundleName));
}
/**
* Provides empty path of the view / template and/or name of bundle
*
* @return Generator
*/
public function provideEmptyViewPathAndBundle()
{
yield[
'',
'',
];
yield[
'test',
'',
];
yield[
'',
'test',
];
}
/**
* Provides path of the view / template and incorrect name of bundle
*
* @return Generator
*/
public function provideViewPathAndIncorrectBundleName()
{
yield[
'User:Active',
'myExtra',
];
yield[
'User:Active',
'MyExtra',
];
yield[
'User:Active',
'MySuperExtraGorgeous',
];
}
/**
* Provides path of the view / template and name of bundle
*
* @return Generator
*/
public function provideViewPathAndBundle()
{
yield[
'User',
'MyExtraBundle',
'@MyExtra/User.html.twig',
];
yield[
'User:Active',
'MyExtraBundle',
'@MyExtra/User/Active.html.twig',
];
yield[
'User:Active',
'MySuperExtraGorgeousBundle',
'@MySuperExtraGorgeous/User/Active.html.twig',
];
}
/**
* Provides path of the view / template, name of bundle and extension of the view / template
*
* @return Generator
*/
public function provideViewPathAndBundleAndExtension()
{
yield[
'User:Active',
'MyExtraBundle',
'',
null,
];
yield[
'User:Active',
'MyExtraBundle',
'js.twig',
'@MyExtra/User/Active.js.twig',
];
}
/**
* Provides incorrect name of bundle
*
* @return Generator
*/
public function provideIncorrectBundleName()
{
yield[
'myExtra',
];
yield[
'MyExtra',
];
yield[
'MySuperExtraGorgeous',
];
}
/**
* Provides full and short name of bundle
*
* @return Generator
*/
public function provideFullAndShortBundleName()
{
yield[
'MyExtraBundle',
'MyExtra',
];
yield[
'MySuperExtraGorgeousBundle',
'MySuperExtraGorgeous',
];
}
}

View File

@@ -13,20 +13,25 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Composer; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class ComposerTest extends BaseTestCase class ComposerTest extends BaseTestCase
{ {
/** /**
* Path of existing composer.json used as source of data for tests. * Path of existing composer.json used as source of data for tests
* *
* @var string * @var string
*/ */
private $composerJsonPath; private $composerJsonPath;
public function testConstructor()
{
static::assertHasNoConstructor(Composer::class);
}
/** /**
* @param string $composerJsonPath Empty value, e.g. "" * @param string $composerJsonPath Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
@@ -59,7 +64,7 @@ class ComposerTest extends BaseTestCase
} }
/** /**
* Provides names and values of existing nodes. * Provides names and values of existing nodes
* *
* @return Generator * @return Generator
*/ */
@@ -83,6 +88,6 @@ class ComposerTest extends BaseTestCase
{ {
parent::setUp(); parent::setUp();
$this->composerJsonPath = $this->getFilePathToTests(Composer::FILE_NAME_MAIN); $this->composerJsonPath = $this->getFilePathForTesting(Composer::FILE_NAME_MAIN);
} }
} }

View File

@@ -11,18 +11,24 @@ namespace Meritoo\Common\Test\Utilities;
use DateInterval; use DateInterval;
use DateTime; use DateTime;
use Generator; use Generator;
use Meritoo\Common\Exception\Date\UnknownDatePartTypeException; use Meritoo\Common\Exception\Type\UnknownDatePartTypeException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Type\DatePeriod;
use Meritoo\Common\Utilities\Date; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class DateTest extends BaseTestCase class DateTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(Date::class);
}
/** /**
* @param mixed $value Empty value, e.g. "" * @param mixed $value Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
@@ -189,7 +195,7 @@ class DateTest extends BaseTestCase
public function testGetCurrentDayOfWeek() public function testGetCurrentDayOfWeek()
{ {
self::assertRegExp('/^[0-6]{1}$/', (string) Date::getCurrentDayOfWeek()); self::assertRegExp('/^[0-6]{1}$/', (string)Date::getCurrentDayOfWeek());
} }
public function testGetCurrentDayOfWeekName() public function testGetCurrentDayOfWeekName()
@@ -218,7 +224,7 @@ class DateTest extends BaseTestCase
*/ */
public function testGetDayOfWeekIncorrectValues($year, $month, $day) public function testGetDayOfWeekIncorrectValues($year, $month, $day)
{ {
$this->expectException(UnknownDatePartTypeException::class); $this->setExpectedException(UnknownDatePartTypeException::class);
self::assertEmpty(Date::getDayOfWeek($year, $month, $day)); self::assertEmpty(Date::getDayOfWeek($year, $month, $day));
} }
@@ -231,7 +237,7 @@ class DateTest extends BaseTestCase
*/ */
public function testGetDayOfWeek($year, $month, $day) public function testGetDayOfWeek($year, $month, $day)
{ {
self::assertRegExp('/^[0-6]{1}$/', (string) Date::getDayOfWeek($year, $month, $day)); self::assertRegExp('/^[0-6]{1}$/', (string)Date::getDayOfWeek($year, $month, $day));
} }
/** /**
@@ -260,10 +266,10 @@ class DateTest extends BaseTestCase
$dateEnd = '2017-01-02'; $dateEnd = '2017-01-02';
$effect = [ $effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0, Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0, Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 1, Date::DATE_DIFFERENCE_UNIT_DAYS => 1,
Date::DATE_DIFFERENCE_UNIT_HOURS => 0, Date::DATE_DIFFERENCE_UNIT_HOURS => 0,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 0, Date::DATE_DIFFERENCE_UNIT_MINUTES => 0,
]; ];
@@ -280,10 +286,10 @@ class DateTest extends BaseTestCase
* Difference of 1 day (using the relative date format) * Difference of 1 day (using the relative date format)
*/ */
$effect = [ $effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0, Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0, Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 1, Date::DATE_DIFFERENCE_UNIT_DAYS => 1,
Date::DATE_DIFFERENCE_UNIT_HOURS => 0, Date::DATE_DIFFERENCE_UNIT_HOURS => 0,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 0, Date::DATE_DIFFERENCE_UNIT_MINUTES => 0,
]; ];
@@ -301,10 +307,10 @@ class DateTest extends BaseTestCase
$dateEnd = '2017-01-02 14:15'; $dateEnd = '2017-01-02 14:15';
$effect = [ $effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0, Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0, Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 1, Date::DATE_DIFFERENCE_UNIT_DAYS => 1,
Date::DATE_DIFFERENCE_UNIT_HOURS => 2, Date::DATE_DIFFERENCE_UNIT_HOURS => 2,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 15, Date::DATE_DIFFERENCE_UNIT_MINUTES => 15,
]; ];
@@ -330,10 +336,10 @@ class DateTest extends BaseTestCase
$dateEnd = '2017-02-11 16:30'; $dateEnd = '2017-02-11 16:30';
$effect = [ $effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0, Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 1, Date::DATE_DIFFERENCE_UNIT_MONTHS => 1,
Date::DATE_DIFFERENCE_UNIT_DAYS => 41, Date::DATE_DIFFERENCE_UNIT_DAYS => 41,
Date::DATE_DIFFERENCE_UNIT_HOURS => 4, Date::DATE_DIFFERENCE_UNIT_HOURS => 4,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 30, Date::DATE_DIFFERENCE_UNIT_MINUTES => 30,
]; ];
@@ -362,10 +368,10 @@ class DateTest extends BaseTestCase
$dateEnd = $dateStart; $dateEnd = $dateStart;
$effect = [ $effect = [
Date::DATE_DIFFERENCE_UNIT_YEARS => 0, Date::DATE_DIFFERENCE_UNIT_YEARS => 0,
Date::DATE_DIFFERENCE_UNIT_MONTHS => 0, Date::DATE_DIFFERENCE_UNIT_MONTHS => 0,
Date::DATE_DIFFERENCE_UNIT_DAYS => 0, Date::DATE_DIFFERENCE_UNIT_DAYS => 0,
Date::DATE_DIFFERENCE_UNIT_HOURS => 0, Date::DATE_DIFFERENCE_UNIT_HOURS => 0,
Date::DATE_DIFFERENCE_UNIT_MINUTES => 0, Date::DATE_DIFFERENCE_UNIT_MINUTES => 0,
]; ];
@@ -502,7 +508,36 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provides incorrect invalidCount of DateTime. * @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
* *
* @return Generator * @return Generator
*/ */
@@ -552,7 +587,7 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provides invalid format of date. * Provides invalid format of date
* *
* @return Generator * @return Generator
*/ */
@@ -570,7 +605,7 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provide empty dates for date difference. * Provide empty dates for date difference
* *
* @return Generator * @return Generator
*/ */
@@ -598,7 +633,7 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provides incorrect values of year, month and day. * Provides incorrect values of year, month and day
* *
* @return Generator * @return Generator
*/ */
@@ -648,7 +683,7 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provides values of year, month and day. * Provides values of year, month and day
* *
* @return Generator * @return Generator
*/ */
@@ -698,7 +733,7 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provides data for the random date with incorrect end of random partition. * Provides data for the random date with incorrect end of random partition
* *
* @return Generator * @return Generator
*/ */
@@ -712,7 +747,7 @@ class DateTest extends BaseTestCase
} }
/** /**
* Provides data for the random date. * Provides data for the random date
* *
* @return Generator * @return Generator
*/ */
@@ -753,4 +788,112 @@ class DateTest extends BaseTestCase
50, 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; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class GeneratorUtilityTest extends BaseTestCase class GeneratorUtilityTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(GeneratorUtility::class);
}
public function testGetGeneratorElements() public function testGetGeneratorElements()
{ {
/* /*

View File

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

View File

@@ -13,13 +13,18 @@ use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\MimeTypes; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class MimeTypesTest extends BaseTestCase class MimeTypesTest extends BaseTestCase
{ {
public function testConstructor()
{
static::assertHasNoConstructor(MimeTypes::class);
}
/** /**
* @param mixed $mimeType Empty value, e.g. "" * @param mixed $mimeType Empty value, e.g. ""
* @dataProvider provideEmptyValue * @dataProvider provideEmptyValue
@@ -186,7 +191,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides not existing mime type. * Provides not existing mime type
* *
* @return Generator * @return Generator
*/ */
@@ -198,7 +203,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides mime type of non-image. * Provides mime type of non-image
* *
* @return Generator * @return Generator
*/ */
@@ -211,7 +216,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides mime type of image. * Provides mime type of image
* *
* @return Generator * @return Generator
*/ */
@@ -226,7 +231,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides existing mime type used to get single, one extension. * Provides existing mime type used to get single, one extension
* *
* @return Generator * @return Generator
*/ */
@@ -249,7 +254,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides existing mime type used to get multiple, more than one extension. * Provides existing mime type used to get multiple, more than one extension
* *
* @return Generator * @return Generator
*/ */
@@ -316,7 +321,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides not existing mime types. * Provides not existing mime types
* *
* @return Generator * @return Generator
*/ */
@@ -344,7 +349,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides mime types used to get extensions. * Provides mime types used to get extensions
* *
* @return Generator * @return Generator
*/ */
@@ -357,7 +362,7 @@ class MimeTypesTest extends BaseTestCase
], ],
[ [
'application/x-7z-compressed' => '7z', 'application/x-7z-compressed' => '7z',
'application/json' => 'json', 'application/json' => 'json',
], ],
]; ];
@@ -374,12 +379,12 @@ class MimeTypesTest extends BaseTestCase
'nb', 'nb',
'mb', 'mb',
], ],
'application/xml' => [ 'application/xml' => [
'xml', 'xml',
'xsl', 'xsl',
], ],
'audio/mp4' => 'mp4a', 'audio/mp4' => 'mp4a',
'video/mp4' => [ 'video/mp4' => [
'mp4', 'mp4',
'mp4v', 'mp4v',
'mpg4', 'mpg4',
@@ -390,7 +395,7 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides mime types used to get extensions as upper case. * Provides mime types used to get extensions as upper case
* *
* @return Generator * @return Generator
*/ */
@@ -403,7 +408,7 @@ class MimeTypesTest extends BaseTestCase
], ],
[ [
'application/x-7z-compressed' => '7Z', 'application/x-7z-compressed' => '7Z',
'application/json' => 'JSON', 'application/json' => 'JSON',
], ],
]; ];
@@ -419,12 +424,12 @@ class MimeTypesTest extends BaseTestCase
'XML', 'XML',
'XSL', 'XSL',
], ],
'audio/mp4' => 'MP4A', 'audio/mp4' => 'MP4A',
'text/html' => [ 'text/html' => [
'HTML', 'HTML',
'HTM', 'HTM',
], ],
'video/mp4' => [ 'video/mp4' => [
'MP4', 'MP4',
'MP4V', 'MP4V',
'MPG4', 'MPG4',
@@ -435,37 +440,37 @@ class MimeTypesTest extends BaseTestCase
} }
/** /**
* Provides real file path to get mime type. * Provides real file path to get mime type
* *
* @return Generator * @return Generator
*/ */
public function provideFilePathToGetMimeTypeOfRealFile() public function provideFilePathToGetMimeTypeOfRealFile()
{ {
yield[ yield[
$this->getFilePathToTests('minion.jpg'), $this->getFilePathForTesting('minion.jpg'),
'image/jpeg', 'image/jpeg',
]; ];
yield[ yield[
$this->getFilePathToTests('lorem-ipsum.txt'), $this->getFilePathForTesting('lorem-ipsum.txt'),
'text/plain', 'text/plain',
]; ];
} }
/** /**
* Provides real file path to get information if the file is an image. * Provides real file path to get information if the file is an image
* *
* @return Generator * @return Generator
*/ */
public function provideExistingFilePathToCheckIsImagePath() public function provideExistingFilePathToCheckIsImagePath()
{ {
yield[ yield[
$this->getFilePathToTests('minion.jpg'), $this->getFilePathForTesting('minion.jpg'),
true, true,
]; ];
yield[ yield[
$this->getFilePathToTests('lorem-ipsum.txt'), $this->getFilePathForTesting('lorem-ipsum.txt'),
false, false,
]; ];
} }

View File

@@ -14,23 +14,33 @@ use Meritoo\Common\Exception\Regex\InvalidColorHexValueException;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Utilities\Locale; use Meritoo\Common\Utilities\Locale;
use Meritoo\Common\Utilities\Miscellaneous; use Meritoo\Common\Utilities\Miscellaneous;
use ReflectionException;
use stdClass; 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> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo.pl * @copyright Meritoo <http://www.meritoo.pl>
*/ */
class MiscellaneousTest extends BaseTestCase class MiscellaneousTest extends BaseTestCase
{ {
private $stringSmall; private $stringSmall;
private $stringCommaSeparated; private $stringCommaSeparated;
private $stringDotSeparated; private $stringDotSeparated;
private $stringWithoutSpaces;
/**
* @throws ReflectionException
*/
public function testConstructor()
{
static::assertHasNoConstructor(Miscellaneous::class);
}
public function testGetDirectoryContent() public function testGetDirectoryContent()
{ {
$directoryPath = __DIR__.'/../'; $directoryPath = __DIR__ . '/../';
$filePath = __FILE__; $filePath = __FILE__;
self::assertNull(Miscellaneous::getDirectoryContent(null)); self::assertNull(Miscellaneous::getDirectoryContent(null));
@@ -123,8 +133,8 @@ class MiscellaneousTest extends BaseTestCase
*/ */
$uniqueFileName2 = Miscellaneous::getUniqueFileName($originalFileName); $uniqueFileName2 = Miscellaneous::getUniqueFileName($originalFileName);
$isCorrect1 = (bool) preg_match($pattern, $uniqueFileName1); $isCorrect1 = (bool)preg_match($pattern, $uniqueFileName1);
$isCorrect2 = (bool) preg_match($pattern, $uniqueFileName2); $isCorrect2 = (bool)preg_match($pattern, $uniqueFileName2);
self::assertTrue($isCorrect1); self::assertTrue($isCorrect1);
self::assertTrue($isCorrect2); self::assertTrue($isCorrect2);
@@ -154,8 +164,8 @@ class MiscellaneousTest extends BaseTestCase
$expected = "int(123)\n"; $expected = "int(123)\n";
if ($xdebugLoaded) { if ($xdebugLoaded) {
$libraryPath = realpath(sprintf('%s%s', dirname(__FILE__), '/../../../../..')); $libraryPath = realpath(sprintf('%s%s', dirname(__FILE__), '/../..'));
$filePath = sprintf('%s%s', $libraryPath, '/src/Meritoo/Common/Utilities/Miscellaneous.php:'); $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 * Attention. I have to use "\d+" at the end of $filePath, because number of line may be different if new
@@ -345,8 +355,8 @@ class MiscellaneousTest extends BaseTestCase
{ {
$suffix = '...'; $suffix = '...';
self::assertEquals('Lorem ipsum'.$suffix, Miscellaneous::substringToWord($this->stringCommaSeparated, 20)); self::assertEquals('Lorem ipsum' . $suffix, Miscellaneous::substringToWord($this->stringCommaSeparated, 20));
self::assertEquals('Lorem ipsum dolor sit'.$suffix, Miscellaneous::substringToWord($this->stringCommaSeparated, 25)); self::assertEquals('Lorem ipsum dolor sit' . $suffix, Miscellaneous::substringToWord($this->stringCommaSeparated, 25));
self::assertEquals('Lorem ipsum dolor', Miscellaneous::substringToWord($this->stringCommaSeparated, 20, '')); self::assertEquals('Lorem ipsum dolor', Miscellaneous::substringToWord($this->stringCommaSeparated, 20, ''));
self::assertEquals('Lorem ipsum dolor sit amet, consectetur', Miscellaneous::substringToWord($this->stringCommaSeparated, 40, '')); self::assertEquals('Lorem ipsum dolor sit amet, consectetur', Miscellaneous::substringToWord($this->stringCommaSeparated, 40, ''));
@@ -356,38 +366,37 @@ class MiscellaneousTest extends BaseTestCase
{ {
self::assertEquals('Lorem ipsum dolor sit<br>amet, consectetur<br>adipiscing<br>elit', Miscellaneous::breakLongText($this->stringCommaSeparated, 20)); self::assertEquals('Lorem ipsum dolor sit<br>amet, consectetur<br>adipiscing<br>elit', Miscellaneous::breakLongText($this->stringCommaSeparated, 20));
self::assertEquals('Lorem ipsum dolor sit---amet, consectetur---adipiscing---elit', Miscellaneous::breakLongText($this->stringCommaSeparated, 20, '---')); self::assertEquals('Lorem ipsum dolor sit---amet, consectetur---adipiscing---elit', Miscellaneous::breakLongText($this->stringCommaSeparated, 20, '---'));
self::assertEquals('LoremIpsum<br>DolorSitAm<br>etConsecte<br>turAdipisc<br>ingElit', Miscellaneous::breakLongText($this->stringWithoutSpaces, 10));
} }
public function testRemoveDirectory() public function testRemoveDirectoryUsingNotExistingDirectory()
{ {
/* self::assertNull(Miscellaneous::removeDirectory('/abc/def/ghi'));
* Removing not existing directory }
*/
self::assertTrue(Miscellaneous::removeDirectory('/abc/def/ghi'));
/* public function testRemoveDirectoryUsingNoDirectory()
* Removing not directory {
*/ $directoryPath = sys_get_temp_dir() . '/ipsum.txt';
$directoryPath = sys_get_temp_dir().'/ipsum.txt';
touch($directoryPath); touch($directoryPath);
self::assertTrue(Miscellaneous::removeDirectory($directoryPath)); self::assertTrue(Miscellaneous::removeDirectory($directoryPath));
}
/* public function testRemoveDirectoryUsingSimpleDirectory()
* Removing simple directory {
*/ $directoryPath = sys_get_temp_dir() . '/lorem/ipsum';
$directoryPath = sys_get_temp_dir().'/lorem/ipsum';
mkdir($directoryPath, 0777, true); mkdir($directoryPath, 0777, true);
self::assertTrue(Miscellaneous::removeDirectory($directoryPath)); self::assertTrue(Miscellaneous::removeDirectory($directoryPath));
}
/* public function testRemoveDirectoryUsingComplexDirectory()
* Removing more complex directory {
*/ $directory1Path = sys_get_temp_dir() . '/lorem/ipsum';
$directory1Path = sys_get_temp_dir().'/lorem/ipsum'; $directory2Path = sys_get_temp_dir() . '/lorem/dolor/sit';
$directory2Path = sys_get_temp_dir().'/lorem/dolor/sit';
mkdir($directory1Path, 0777, true); mkdir($directory1Path, 0777, true);
mkdir($directory2Path, 0777, true); mkdir($directory2Path, 0777, true);
self::assertTrue(Miscellaneous::removeDirectory(sys_get_temp_dir().'/lorem', false));
self::assertTrue(Miscellaneous::removeDirectory(sys_get_temp_dir() . '/lorem', false));
} }
/** /**
@@ -503,16 +512,35 @@ class MiscellaneousTest extends BaseTestCase
self::assertEquals('lorem ipsum', Miscellaneous::trimSmart(' lorem ipsum ')); self::assertEquals('lorem ipsum', Miscellaneous::trimSmart(' lorem ipsum '));
} }
public function testConcatenatePaths() /**
* @param mixed $emptyPaths Empty paths co concatenate
* @dataProvider provideEmptyValue
*/
public function testConcatenatePathsWithEmptyPaths($emptyPaths)
{
self::assertEquals('', Miscellaneous::concatenatePaths($emptyPaths));
}
public function testConcatenatePathsWithOneEmptyPath()
{
$paths = [
'first/directory',
'second/one',
'',
'and/the/third',
];
$concatenated = Miscellaneous::concatenatePaths($paths);
unset($paths[2]);
$imploded = implode('/', $paths);
self::assertEquals('/' . $imploded, $concatenated);
}
public function testConcatenatePathsInNixOs()
{ {
/* /*
* Common cases * For *nix operating system
*/
self::assertEquals('', Miscellaneous::concatenatePaths(null));
self::assertEquals('', Miscellaneous::concatenatePaths([]));
/*
* *nix operating system
*/ */
$paths1 = [ $paths1 = [
'first/directory', 'first/directory',
@@ -520,9 +548,12 @@ class MiscellaneousTest extends BaseTestCase
'and/the/third', 'and/the/third',
]; ];
self::assertEquals('/'.implode('/', $paths1), Miscellaneous::concatenatePaths($paths1)); self::assertEquals('/' . implode('/', $paths1), Miscellaneous::concatenatePaths($paths1));
self::assertEquals('/'.implode('/', $paths1), Miscellaneous::concatenatePaths($paths1[0], $paths1[1], $paths1[2])); self::assertEquals('/' . implode('/', $paths1), Miscellaneous::concatenatePaths($paths1[0], $paths1[1], $paths1[2]));
}
public function testConcatenatePathsInWindowsOs()
{
/* /*
* For Windows operating system * For Windows operating system
*/ */
@@ -634,9 +665,14 @@ class MiscellaneousTest extends BaseTestCase
self::assertEquals(255, Miscellaneous::getValidColorComponent(255, false)); self::assertEquals(255, Miscellaneous::getValidColorComponent(255, false));
} }
/**
* @throws IncorrectColorHexLengthException
* @throws InvalidColorHexValueException
*/
public function testGetInvertedColorWithIncorrectLength() public function testGetInvertedColorWithIncorrectLength()
{ {
$this->expectException(IncorrectColorHexLengthException::class); $this->setExpectedException(IncorrectColorHexLengthException::class);
Miscellaneous::getInvertedColor(null); Miscellaneous::getInvertedColor(null);
Miscellaneous::getInvertedColor(''); Miscellaneous::getInvertedColor('');
Miscellaneous::getInvertedColor(1); Miscellaneous::getInvertedColor(1);
@@ -647,9 +683,14 @@ class MiscellaneousTest extends BaseTestCase
Miscellaneous::getInvertedColor('1234567'); Miscellaneous::getInvertedColor('1234567');
} }
/**
* @throws IncorrectColorHexLengthException
* @throws InvalidColorHexValueException
*/
public function testGetInvertedColorWithInvalidValue() public function testGetInvertedColorWithInvalidValue()
{ {
$this->expectException(InvalidColorHexValueException::class); $this->setExpectedException(InvalidColorHexValueException::class);
Miscellaneous::getInvertedColor('0011zz'); Miscellaneous::getInvertedColor('0011zz');
Miscellaneous::getInvertedColor('001#zz'); Miscellaneous::getInvertedColor('001#zz');
Miscellaneous::getInvertedColor('001!zz'); Miscellaneous::getInvertedColor('001!zz');
@@ -657,6 +698,10 @@ class MiscellaneousTest extends BaseTestCase
Miscellaneous::getInvertedColor('00ppqq'); Miscellaneous::getInvertedColor('00ppqq');
} }
/**
* @throws IncorrectColorHexLengthException
* @throws InvalidColorHexValueException
*/
public function testGetInvertedColor() public function testGetInvertedColor()
{ {
/* /*
@@ -720,8 +765,13 @@ class MiscellaneousTest extends BaseTestCase
self::assertSame($expected, Miscellaneous::fillMissingZeros($number, $length, $before)); self::assertSame($expected, Miscellaneous::fillMissingZeros($number, $length, $before));
} }
public function testGetProjectRootPath()
{
self::assertNotEmpty(Miscellaneous::getProjectRootPath());
}
/** /**
* Provides string to convert characters to latin characters and not lower cased and not human-readable. * Provides string to convert characters to latin characters and not lower cased and not human-readable
* *
* @return Generator * @return Generator
*/ */
@@ -816,7 +866,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides string to convert characters to latin characters and lower cased and human-readable. * Provides string to convert characters to latin characters and lower cased and human-readable
* *
* @return Generator * @return Generator
*/ */
@@ -911,7 +961,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides names of files. * Provides names of files
* *
* @return Generator * @return Generator
*/ */
@@ -939,7 +989,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides string to convert to camel case. * Provides string to convert to camel case
* *
* @return Generator * @return Generator
*/ */
@@ -965,7 +1015,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides path used to remove the starting / beginning directory's separator. * Provides path used to remove the starting / beginning directory's separator
* *
* @return Generator * @return Generator
*/ */
@@ -1009,7 +1059,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides path used to remove the ending directory's separator. * Provides path used to remove the ending directory's separator
* *
* @return Generator * @return Generator
*/ */
@@ -1053,7 +1103,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides empty value used to fill missing zeros. * Provides empty value used to fill missing zeros
* *
* @return Generator * @return Generator
*/ */
@@ -1067,7 +1117,7 @@ class MiscellaneousTest extends BaseTestCase
} }
/** /**
* Provides number used to fill missing zeros. * Provides number used to fill missing zeros
* *
* @return Generator * @return Generator
*/ */
@@ -1140,6 +1190,7 @@ class MiscellaneousTest extends BaseTestCase
$this->stringSmall = 'Lorem ipsum dolor sit amet.'; $this->stringSmall = 'Lorem ipsum dolor sit amet.';
$this->stringCommaSeparated = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'; $this->stringCommaSeparated = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
$this->stringDotSeparated = 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.'; $this->stringDotSeparated = 'Etiam ullamcorper. Suspendisse a pellentesque dui, non felis.';
$this->stringWithoutSpaces = 'LoremIpsumDolorSitAmetConsecteturAdipiscingElit';
} }
/** /**
@@ -1152,5 +1203,6 @@ class MiscellaneousTest extends BaseTestCase
unset($this->stringSmall); unset($this->stringSmall);
unset($this->stringCommaSeparated); unset($this->stringCommaSeparated);
unset($this->stringDotSeparated); unset($this->stringDotSeparated);
unset($this->stringWithoutSpaces);
} }
} }

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 Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.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),
]),
];
}
}

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