25 Commits
0.1.3 ... 0.1.4

Author SHA1 Message Date
Meritoo
39ede292d6 Merge branch 'develop' 2018-11-03 09:09:09 +01:00
Meritoo
8e9dcb3206 Reflection > setPropertiesValues() method > sets values of properties in given object 2018-11-03 08:53:01 +01:00
Meritoo
06fbf63e09 Tests > refactoring 2018-11-03 08:50:12 +01:00
Meritoo
4e600ec599 Utilities > Reflection > setPropertyValue() method > fix description and test 2018-11-03 08:16:49 +01:00
Meritoo
b4ccbbac11 Utilities > Date > update descriptions of methods 2018-11-03 08:10:03 +01:00
Meritoo
c82f53219e Phing > PHPUnit > run with code coverage (to get all reports) 2018-10-29 08:31:38 +01:00
Meritoo
c8fc0b14ff Exceptions > UnknownTypeException > remove duplicated and unnecessary sprintf() call > sprintf(sprintf()) 2018-10-28 00:12:18 +02:00
Meritoo
3c3d1b997e Docker > docker-compose.yml > add "phpunit" service > used to run PHPUnit's tests 2018-10-28 00:10:42 +02:00
Meritoo
61209e3f67 Documentation > Development > add commands based on Phing & update whole document 2018-10-28 00:09:29 +02:00
Meritoo
822dbf6830 Phing > tests > remove mutation tests (because Infection requires PHP 7.1+) 2018-10-28 00:06:52 +02:00
Meritoo
870bfe48a2 Docker > Dockerfile > fix installation of Composer 2018-10-28 00:03:35 +02:00
Meritoo
ff416fda69 Phing > update configuration 2018-10-25 11:05:32 +02:00
Meritoo
61676a445e Docker > update docker-compose.yml > composer > fix "allowed memory size of 1610612736 bytes exhausted" bug 2018-10-25 10:31:44 +02:00
Meritoo
1f5106bcf0 Docker > improve performance > fix indentations 2018-10-25 10:31:21 +02:00
Meritoo
971224b2e6 PHPUnit > update configuration 2018-10-25 10:28:00 +02:00
Meritoo
7e4b14a92f Phing > update configuration 2018-10-25 10:27:48 +02:00
Meritoo
38c68b0952 Readme > add badge with required PHP version 2018-10-19 22:54:26 +02:00
Meritoo
ca9c3bd8f1 Utilities > Date > update descriptions of methods 2018-10-19 22:54:11 +02:00
Meritoo
97c6112919 TravisCI > fix indentation 2018-09-20 20:41:48 +02:00
Meritoo
26b136d676 Tests > increase code coverage 2018-09-20 17:30:07 +02:00
Meritoo
4db631223f Phing > tests > PHPUnit > do not use dox format (for output results) 2018-09-08 08:21:50 +02:00
Meritoo
5d6b559108 Phing > tests > missing path of directory with code coverage report 2018-09-07 13:48:44 +02:00
Meritoo
575bb344cd BaseTestCaseTrait > minor refactoring 2018-08-27 22:04:35 +02:00
Meritoo
35b70f53e7 BaseType > minor refactoring 2018-08-26 16:39:45 +02:00
Meritoo
51ff110101 Phing > update configuration 2018-08-26 15:43:34 +02:00
26 changed files with 835 additions and 425 deletions

View File

@@ -11,7 +11,7 @@ before_install:
- composer global require hirak/prestissimo - composer global require hirak/prestissimo
install: install:
- travis_wait 30 composer install - travis_wait 30 composer install -v
script: script:
- php ./vendor/bin/phpunit - php ./vendor/bin/phpunit

View File

@@ -2,6 +2,13 @@
Common and useful classes, methods, exceptions etc. Common and useful classes, methods, exceptions etc.
# 0.1.4
1. Phing > update configuration
2. Utilities > Date > update descriptions of methods
3. Docker > docker-compose.yml > add "phpunit" service > used to run PHPUnit's tests
4. Reflection > setPropertiesValues() method > sets values of properties in given object
# 0.1.3 # 0.1.3
1. Tests > refactoring & minor improvements 1. Tests > refactoring & minor improvements

View File

@@ -2,26 +2,14 @@
Common and useful classes, methods, exceptions etc. Common and useful classes, methods, exceptions etc.
[![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) [![PHP Version](https://img.shields.io/badge/php-%3E%3D5.6-blue.svg)](https://img.shields.io/badge/php-%3E%3D5.6-blue.svg) [![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)
# Installation # Installation
In your `composer.json` add address of repository into `repositories` section:
```json
"repositories": [
(...)
{
"type": "vcs",
"url": "https://github.com/wiosna-dev/common-library"
}
]
```
Run [Composer](https://getcomposer.org) to install this package in your project: Run [Composer](https://getcomposer.org) to install this package in your project:
```bash ```bash
composer require wiosna-dev/common-library composer require meritoo/common-library
``` ```
> [How to install Composer?](https://getcomposer.org/download) > [How to install Composer?](https://getcomposer.org/download)

View File

@@ -1 +1 @@
0.1.3 0.1.4

View File

@@ -1,46 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0"> <project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties --> <!-- Properties -->
<if> <if>
<available file="phing/properties" property="custom.properties.available"/> <available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<then> <then>
<property file="phing/properties"/> <property file="${project.basedir}/phing/properties"/>
</then> </then>
<else> <else>
<property file="phing/properties.dist"/> <property file="${project.basedir}/phing/properties.dist"/>
</else> </else>
</if> </if>
<!-- Default / main target --> <!-- Default / main target -->
<target name="build:main" <target name="build:main"
depends="build:app, build:tests" depends="build:app,
description="Builds everything and runs all tests" /> build:tests"
/>
<!-- Build app --> <!-- Build app -->
<target name="build:app" description="Prepares app to build and tests"> <target name="build:app">
<phing phingfile="phing/app.xml" haltonfailure="true"/> <phing phingfile="${project.basedir}/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">
<phing phingfile="phing/tests.xml" haltonfailure="true"/> <phing phingfile="${project.basedir}/phing/tests.xml" haltonfailure="true"/>
<!--
Conditional running of tests.
Disabled, because not required.
Meritoo <github@meritoo.pl>
2017-02-22
<if>
<equals arg1="${env}" arg2="test" />
<then>
<phing phingfile="phing/tests.xml" haltonfailure="true" />
</then>
<else>
<echo message="[Skipped] Running tests, checks and creating docs, because it's a not 'test' environment..." />
</else>
</if>
-->
</target> </target>
</project> </project>

View File

@@ -1,5 +1,5 @@
{ {
"name": "wiosna-dev/common-library", "name": "meritoo/common-library",
"description": "Useful classes, methods, extensions etc.", "description": "Useful classes, methods, extensions etc.",
"license": "MIT", "license": "MIT",
"authors": [ "authors": [

View File

@@ -1,6 +1,9 @@
version: '3' version: '3'
services: services:
#
# Required to run project
#
php: php:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-php container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-php
@@ -15,6 +18,16 @@ services:
composer: composer:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-composer container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-composer
entrypoint: composer entrypoint: php -d memory_limit=-1 /usr/local/bin/composer
volumes:
- .:/project:cached
#
# Required to run PHPUnit's tests
#
phpunit:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-phpunit
entrypoint: ./vendor/bin/phpunit
command: --version
volumes: volumes:
- .:/project:cached - .:/project:cached

View File

@@ -98,7 +98,7 @@ ENV COMPOSER_ALLOW_SUPERUSER 1
# #
RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \ RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
&& php -r "if (hash_file('SHA384', 'composer-setup.php') === \ && php -r "if (hash_file('SHA384', 'composer-setup.php') === \
'544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo \ '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo \
'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" \ '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 composer-setup.php --install-dir=/usr/local/bin --filename=composer \
&& php -r "unlink('composer-setup.php');" \ && php -r "unlink('composer-setup.php');" \

View File

@@ -15,10 +15,10 @@ Development-related information
docker-compose up -d docker-compose up -d
``` ```
2. Install packages by running command: 2. Rebuild project by running command (installs packages, prepares required directories and runs tests):
```bash ```bash
docker-compose run composer install docker-compose exec php phing
``` ```
> [What is Docker?](https://www.docker.com/what-docker) > [What is Docker?](https://www.docker.com/what-docker)
@@ -28,7 +28,7 @@ Development-related information
Available as `composer` service. You can run any Composer's command using the `composer` service: Available as `composer` service. You can run any Composer's command using the `composer` service:
```bash ```bash
docker-compose run composer <command> docker-compose run --rm composer [command]
``` ```
Examples below. Examples below.
@@ -36,25 +36,25 @@ Examples below.
##### Install packages ##### Install packages
```bash ```bash
docker-compose run composer install docker-compose run --rm composer install
``` ```
##### Update packages ##### Update packages
```bash ```bash
docker-compose run composer update docker-compose run --rm composer update
``` ```
##### Add package ##### Add package
```bash ```bash
docker-compose run composer require <vendor>/<package> docker-compose run --rm composer require [vendor]/[package]
``` ```
##### Remove package ##### Remove package
```bash ```bash
docker-compose run composer remove <vendor>/<package> docker-compose run --rm composer remove [vendor]/[package]
``` ```
# Coding Standards Fixer # Coding Standards Fixer
@@ -65,6 +65,12 @@ Fix coding standard by running command:
docker-compose exec php php-cs-fixer fix docker-compose exec php php-cs-fixer fix
``` ```
or
```bash
docker-compose exec php phing -f phing/tests.xml build:fix-coding-standards
```
Omit cache and run the Fixer from scratch by running command: Omit cache and run the Fixer from scratch by running command:
```bash ```bash
@@ -77,37 +83,35 @@ docker-compose exec php rm .php_cs.cache && docker-compose exec php php-cs-fixer
### Prerequisites ### Prerequisites
Install required packages by running command: `docker-compose run composer install`. Install required packages by running command: `docker-compose run --rm composer install`.
### Running tests ### Running [PHPUnit](https://phpunit.de) tests
#### Simply & quick, without code coverage ##### Easy (with code coverage)
Tests are running using Docker and `php` service defined in `docker-compose.yml`. Example:
```bash ```bash
docker-compose exec php phpunit --no-coverage docker-compose run --rm phpunit --verbose
``` ```
You can also run them in container. In this case you have to run 2 commands: or
1. Enter container:
```bash
docker-compose exec php bash
```
2. Run tests:
```bash
phpunit --no-coverage
```
#### With code coverage
```bash ```bash
docker-compose exec php phpunit docker-compose exec php phing -f phing/tests.xml test:phpunit
``` ```
##### Quick (without code coverage)
```bash
docker-compose run --rm phpunit --verbose --no-coverage
```
# Versions of packages
### squizlabs/php_codesniffer
I have to use [squizlabs/php_codesniffer](https://packagist.org/packages/squizlabs/php_codesniffer) `^2.9` instead of
`^3.3`, because [Phing doesn't support 3.x PHP_CodeSniffer](https://github.com/phingofficial/phing/issues/716).
# Other # Other
Rebuild project and run tests by running command: Rebuild project and run tests by running command:

View File

@@ -1,98 +1,184 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
<!-- Properties --> <!-- Properties -->
<if> <if>
<available file="phing/properties" property="custom.properties.available"/> <available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<then> <then>
<property file="phing/properties"/> <property file="${project.basedir}/phing/properties"/>
</then> </then>
<else> <else>
<property file="phing/properties.dist"/> <property file="${project.basedir}/phing/properties.dist"/>
</else> </else>
</if> </if>
<!-- Filesets -->
<import file="${project.basedir}/phing/filesets.xml"/>
<!-- Default / main target --> <!-- Default / main target -->
<target name="build:main" <target name="build:main"
depends="build:app" depends="build:app"
description="Builds the application" /> />
<!-- App target --> <!-- App target -->
<target name="build:app" <target name="build:app"
depends="app:composer, app:vendors, app:checkout" depends="app:clean,
description="Prepares app to build." /> app:composer:self-update,
app:composer:install,
<!-- Updates Composer and validates composer.* files --> app:composer:validate,
<target name="app:composer" description="Updates Composer and validates composer.* files"> app:checkout"
<echo msg="Updating Composer and validating composer.* files..." /> />
<!-- Updates Composer -->
<target name="app:composer:self-update">
<if> <if>
<available file="composer.phar" /> <not>
<available file="${composer.path}" property="composer.local.unavailable"/>
</not>
<then> <then>
<echo msg="[Skipped] Downloading of Composer skipped, because exist in the project..." /> <if>
<os family="windows"/>
<then>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer."/>
</then> </then>
<else> <else>
<if> <exec command="${composer.download_command}" checkreturn="true" passthru="true"/>
<os family="windows" />
<then>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer." />
</then>
<else>
<exec command="${composer.download_command}" checkreturn="true" />
</else> </else>
</if> </if>
</else> </then>
</if> </if>
<!-- Update Composer --> <!-- Update Composer -->
<composer command="selfupdate" /> <composer php="${composer.php}" composer="${composer.path}" command="selfupdate">
<arg value="--ansi"/>
<!-- Validate Composer -->
<composer command="validate">
<arg line="--no-check-all --strict" />
</composer> </composer>
</target> </target>
<!-- Project Install/update vendors --> <!-- Validates composer.* files -->
<target name="app:vendors" description="Installs / updates vendors"> <target name="app:composer:validate" depends="app:composer:install">
<echo msg="Installing / updating vendors..." /> <composer php="${composer.php}" composer="${composer.path}" command="validate">
<arg value="--no-check-all"/>
<if> <arg value="--strict"/>
<istrue value="${composer.self-update}"/> <arg value="--ansi"/>
<then>
<composer php="${composer.php}" composer="${composer.path}" command="self-update"/>
</then>
</if>
<if>
<istrue value="${composer.validate}"/>
<then>
<composer php="${composer.php}" composer="${composer.path}" command="validate"/>
</then>
</if>
<if>
<equals arg1="${env}" arg2="prod" />
<then>
<composer php="${composer.php}" composer="${composer.path}" command="install">
<arg value="--optimize-autoloader" />
<arg value="--prefer-dist" />
<arg value="--classmap-authoritative" />
</composer> </composer>
</target>
<!-- Project clean -->
<target name="app:clean">
<if>
<equals arg1="${env}" arg2="prod"/>
<then>
<echo message="[Skipped] Cleaning project (and directories cleanup) -> 'prod' environment"/>
</then> </then>
<else> <else>
<composer php="${composer.php}" composer="${composer.path}" command="install" /> <foreach list="${directoriesToEmpty}" param="directory" target="app:clean:empty"/>
</else> </else>
</if> </if>
<foreach list="${directoriesToCheck}" param="directory" target="app:clean:check"/>
<touch file="${dir.cache}/.gitkeep"/>
<touch file="${dir.logs}/.gitkeep"/>
<touch file="${dir.sessions}/.gitkeep"/>
<foreach list="${directoriesToEmpty}" param="directory" target="app:permissions"/>
</target>
<!-- Cleaning directory (making empty) directory -->
<target name="app:clean:empty">
<if>
<available file="${directory}" type="dir" property="dir_is_available"/>
<then>
<delete includeemptydirs="true" dir="${directory}"/>
</then>
</if>
</target>
<!-- Checking if directory exists -->
<target name="app:clean:check">
<if>
<not>
<available file="${directory}" type="dir" property="dir_is_available"/>
</not>
<then>
<if>
<or>
<contains string="${directory}" substring="cache"/>
<contains string="${directory}" substring="logs"/>
<contains string="${directory}" substring="sessions"/>
</or>
<then>
<mkdir dir="${directory}" mode="0777"/>
</then>
<else>
<mkdir dir="${directory}" mode="0775"/>
</else>
</if>
</then>
</if>
</target>
<!-- Installs vendors -->
<target name="app:composer:install" depends="app:composer:self-update">
<composer php="${composer.php}" composer="${composer.path}" command="install">
<arg value="--optimize-autoloader"/>
<arg value="--ansi"/>
</composer>
</target>
<!-- Clearing cache -->
<target name="app:cache">
<if>
<istrue value="${cache.clearWithWarmup}"/>
<then>
<SymfonyConsole console="bin/console" command="cache:clear">
<arg name="env" value="${env}"/>
</SymfonyConsole>
</then>
<else>
<SymfonyConsole console="bin/console" command="cache:clear">
<arg name="env" value="${env}"/>
<arg name="no-warmup"/>
</SymfonyConsole>
</else>
</if>
</target>
<!-- Clearing cache (faster) -->
<target name="app:cache:faster">
<SymfonyConsole console="bin/console" command="cache:clear">
<arg name="env" value="${env}"/>
<arg name="no-optional-warmers"/>
</SymfonyConsole>
</target>
<!-- Warming up cache -->
<target name="app:cache:warmup">
<SymfonyConsole console="bin/console" command="cache:warmup">
<arg name="env" value="${env}"/>
</SymfonyConsole>
</target>
<!-- Setting permissions of given directory -->
<target name="app:permissions">
<if>
<not>
<os family="windows"/>
</not>
<then>
<exec command="chmod -R 777 ${directory}/*"/>
</then>
</if>
</target> </target>
<!-- Checkout and finalization --> <!-- Checkout and finalization -->
<target name="app:checkout"> <target name="app:checkout">
<tstamp> <tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M" /> <format property="date_end" pattern="%Y-%m-%d %H:%M"/>
</tstamp> </tstamp>
<echo msg="------------------------------------" /> <echo msg="------------------------------------"/>
<echo msg="Build finished at: ${date_end}" /> <echo msg="Build finished at: ${date_end}"/>
<echo msg="------------------------------------" /> <echo msg="------------------------------------"/>
</target> </target>
</project> </project>

20
phing/composer-install.sh Normal file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
EXPECTED_SIGNATURE="$(curl -L https://composer.github.io/installer.sig)"
# Original line (with wget):
# EXPECTED_SIGNATURE="$(wget -q -O - https://composer.github.io/installer.sig)"
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
ACTUAL_SIGNATURE="$(php -r "echo hash_file('SHA384', 'composer-setup.php');")"
if [ "$EXPECTED_SIGNATURE" != "$ACTUAL_SIGNATURE" ]
then
>&2 echo 'ERROR: Invalid installer signature'
rm composer-setup.php
exit 1
fi
php composer-setup.php --quiet
RESULT=$?
rm composer-setup.php
exit $RESULT

36
phing/filesets.xml Normal file
View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
<!-- Filesets -->
<fileset id="cache" dir="${dir.cache}">
<include name="**/*"/>
<exclude name=".gitkeep"/>
</fileset>
<fileset id="logs" dir="${dir.logs}">
<include name="**/*"/>
<exclude name=".gitkeep"/>
</fileset>
<fileset id="sessions" dir="${dir.sessions}">
<include name="**/*"/>
<exclude name=".gitkeep"/>
</fileset>
<!-- Directories to check -->
<property name="directoriesToCheck" value="
${dir.cache},
${dir.logs},
${dir.sessions},
${dir.data.tests},
${dir.data.temporary},
${dir.docker.data},
${dir.docker.logs}"
/>
<!-- Directories to empty -->
<property name="directoriesToEmpty" value="
${dir.cache},
${dir.logs},
${dir.sessions},
${dir.data.temporary}"
/>
</project>

View File

@@ -1,19 +1,3 @@
# --------------------------------------------------------------------------------
# Information
# --------------------------------------------------------------------------------
# Property files contain key/value pairs
# key = value
#
# Property keys may contain alphanumeric chars and colons, but
# not special chars. This way you can create pseudo-namespaces
#
# You can refer to values of other properties by enclosing their keys in "${}".
# Example: dir.js = ${dir.web}/js
#
# Everything behind the equal sign is the value, you do
# not have to enclose strings: text=This is some text, Your OS is ${php.os}
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Common, e.g. default environment # Common, e.g. default environment
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
@@ -22,10 +6,6 @@
# #
env = dev env = dev
# Install assets using symlinks
#
assets.installWithSymlink = true
# Clear cache with the "warmup" option # Clear cache with the "warmup" option
# #
# The cache:clear command should always be called with the --no-warmup option. Warmup should be done via the cache:warmup command. # The cache:clear command should always be called with the --no-warmup option. Warmup should be done via the cache:warmup command.
@@ -40,67 +20,63 @@ cache.clearWithWarmup = false
# Composer # Composer
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
composer.download_command = php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));" # Command used to download Composer
# Path to composer executable or composer.phar file
# #
composer.path = composer.phar composer.download_command = bash ${project.basedir}/phing/composer-install.sh
#composer.path = /usr/local/bin/composer
# Path to composer executable or downloaded composer.phar file
#
composer.path = ${project.basedir}/composer.phar
# Path to php executable used by composer # Path to php executable used by composer
# #
composer.php = php composer.php = php
# Self update of the composer
#
composer.self-update = false
# Validate the composer.json file
#
composer.validate = false
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Directories # Directories
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# System directories # System directories
# #
dir.data = ${project.basedir}/data
dir.src = ${project.basedir}/src dir.src = ${project.basedir}/src
dir.var = ${project.basedir}/tests/Resources/var
dir.cache = ${dir.var}/cache
dir.logs = ${dir.var}/log
dir.sessions = ${dir.var}/sessions
dir.data = ${project.basedir}/data
dir.tests = ${project.basedir}/tests dir.tests = ${project.basedir}/tests
# --------------------------------------------------------------------------------
# Build directories # Build directories
# -------------------------------------------------------------------------------- #
dir.build = ${project.basedir}/build dir.build = ${project.basedir}/build
dir.reports = ${dir.build}/logs dir.reports = ${dir.build}/reports
dir.reports.pdepend = ${dir.reports}/pdepend dir.reports.pdepend = ${dir.reports}/pdepend
dir.reports.coverage = ${dir.reports}/phpunit_coverage dir.reports.coverage = ${dir.reports}/phpunit_coverage
#
# Disabled, because unnecessary right now
# phpdocumentor/phpdocumentor cannot be installed via Composer
#
# Meritoo <github@meritoo.pl>
# 2017-02-22
#
#dir.docs = ${dir.build}/docs
#dir.docs.phpdoc2 = ${dir.docs}/phpdoc2
# --------------------------------------------------------------------------------
# Data directories # Data directories
# -------------------------------------------------------------------------------- #
dir.data.tests = ${dir.data}/tests
dir.data.temporary = ${dir.data}/tmp dir.data.temporary = ${dir.data}/tmp
# Docker directories
#
dir.docker = ${project.basedir}/docker
dir.docker.data = ${dir.docker}/data/db
dir.docker.logs = ${dir.docker}/logs/nginx
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Testing # Testing
# -------------------------------------------------------------------------------- # --------------------------------------------------------------------------------
# Path of the framework used to run unit tests
#
tests.framework.path = ./vendor/bin/phpunit --verbose --no-coverage --testdox
# Path of the PHP Coding Standards Fixer (http://cs.sensiolabs.org) # Path of the PHP Coding Standards Fixer (http://cs.sensiolabs.org)
# #
phpCsFixer.path = ./vendor/bin/php-cs-fixer tests.cs_fixer.command = ./vendor/bin/php-cs-fixer fix --verbose
# Test database path
#
tests.database = ${dir.data.temporary}/database.sqlite
# Paths of frameworks used to run tests:
# - PHPUnit (unit tests)
#
tests.phpunit.command = ./vendor/bin/phpunit --verbose

View File

@@ -1,230 +1,133 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!--
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.
Meritoo <github@meritoo.pl> <project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
2017-02-23 <autoloader/>
-->
<autoloader />
<!-- Properties --> <!-- Properties -->
<if> <if>
<available file="phing/properties" property="custom.properties.available"/> <available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<then> <then>
<property file="phing/properties"/> <property file="${project.basedir}/phing/properties"/>
</then> </then>
<else> <else>
<property file="phing/properties.dist"/> <property file="${project.basedir}/phing/properties.dist"/>
</else> </else>
</if> </if>
<!-- Filesets --> <!-- Filesets -->
<fileset id="sourcecode" dir="${dir.src}"> <fileset id="sourcecode" dir="${dir.src}">
<include name="**/*.php" /> <include name="**/*.php"/>
<exclude name="*Test.php" /> <exclude name="*Test.php"/>
<exclude name="**/*Test.php" /> <exclude name="**/*Test.php"/>
<exclude name="**/Resources/**" /> <exclude name="**/Resources/**"/>
<exclude name="**/DataFixtures/**" /> <exclude name="**/DataFixtures/**"/>
<exclude name="**/Tests/**" /> <exclude name="**/Tests/**"/>
</fileset> </fileset>
<fileset id="tests" dir="${dir.tests}"> <fileset id="tests" dir="${dir.tests}">
<include name="**/*Test*.php" /> <include name="**/*Test*.php"/>
</fileset> </fileset>
<!-- Default / main target --> <!-- Default / main target -->
<target name="build:main" <target name="build:main"
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, app:checkout" depends="build:fix-coding-standards,
description="Runs all tests and builds everything" /> build:check,
<!-- build:test,
Before: app:checkout"
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, build:doc, app:checkout" />
After:
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, app:checkout"
The "build:doc" task is disabled, because it cannot be installed via Composer:
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Meritoo <github@meritoo.pl>
2017-02-22
-->
<!-- Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org) --> <!-- Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org) -->
<target name="build:fix-coding-standards" description="Fixes coding standards using the PHP Coding Standards Fixer"> <target name="build:fix-coding-standards">
<echo msg="Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org)..." /> <exec command="${tests.cs_fixer.command}" passthru="true"/>
<!--
Attention.
Rules for formatting are defined in /.php_cs.dist file.
-->
<exec
passthru="true"
command="${phpCsFixer.path} fix --verbose"
/>
</target> </target>
<!-- Doc target -->
<!--
Disabled, because it cannot be installed via Composer:
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Meritoo <github@meritoo.pl>
2017-02-22
-->
<!--<target name="build:doc"-->
<!--depends="build:prepare, doc:phpdoc2"-->
<!--description="Generates API documentation" />-->
<!-- Check target --> <!-- Check target -->
<target name="build:check" <target name="build:check"
depends="check:cs, check:md, check:cpd, check:depend, check:loc" depends="check:cs,
description="Analyzes code" /> check:md,
check:cpd,
check:depend,
check:loc"
/>
<!-- Test target --> <!-- Test target -->
<target name="build:test" <target name="build:test"
depends="test:unit" depends="test:phpunit"
description="Executes all tests" /> />
<!-- Project build clean -->
<target name="build:clean" description="Cleans up build directories">
<echo msg="Cleaning docs and reports directories..." />
<!--<delete dir="${dir.docs}" />-->
<delete dir="${dir.reports}" />
</target>
<!-- Project build prepare -->
<target name="build:prepare" description="Create build directories">
<echo msg="Creating build directories..." />
<!--<mkdir dir="${dir.docs}" />-->
<!--<mkdir dir="${dir.docs.phpdoc2}" />-->
<mkdir dir="${dir.reports}" />
<mkdir dir="${dir.reports.pdepend}" />
<mkdir dir="${dir.reports.coverage}"/>
</target>
<!-- PHPDocumentor2 API documentation target -->
<!--
Disabled, because it cannot be installed via Composer:
a) phpdocumentor/phpdocumentor v2.9.0 requires symfony/validator ~2.2
b) symfony/validator ~2.2 causes to remove symfony/symfony 3.*
Meritoo <github@meritoo.pl>
2017-02-22
<target name="doc:phpdoc2" description="Generates API documentations">
<echo msg="Generating API Documentation with phpDocumentor 2..." />
<phpdoc2 title="${phing.project.name}"
destdir="${dir.docs.phpdoc2}"
template="responsive">
<fileset refid="sourcecode" />
</phpdoc2>
</target>
-->
<!-- Symfony2 code sniffer --> <!-- Symfony2 code sniffer -->
<!-- <target name="check:cs" depends="build:prepare">
Attention 1.
To use Symfony2 standards to check coding you have to:
copy, symlink or check out repo to a folder called Symfony2 inside the phpcs Standards directory.
Example:
$ pear config-show | grep php_dir
$ cd /path/to/pear/PHP/CodeSniffer/Standards
$ git clone git://github.com/opensky/Symfony2-coding-standard.git Symfony2
Attention 2.
PSR2 standard is used instead of Symfony2 standard, because after installation squizlabs/php_codesniffer package
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.
Meritoo <github@meritoo.pl>
2017-02-22
-->
<target name="check:cs" description="Checks coding standard">
<echo msg="Checking coding standard..." />
<phpcodesniffer standard="PSR2" showWarnings="true"> <phpcodesniffer standard="PSR2" showWarnings="true">
<fileset refid="sourcecode" /> <fileset refid="sourcecode"/>
<formatter type="checkstyle" outfile="${dir.reports}/checkstyle.xml" /> <formatter type="checkstyle" outfile="${dir.reports}/checkstyle.xml"/>
<formatter type="csv" outfile="${dir.reports}/checkstyle.csv" /> <formatter type="csv" outfile="${dir.reports}/checkstyle.csv"/>
<formatter type="summary" outfile="${dir.reports}/checkstyle_summary.txt" /> <formatter type="summary" outfile="${dir.reports}/checkstyle_summary.txt"/>
</phpcodesniffer> </phpcodesniffer>
</target> </target>
<!-- copy/paste detector --> <!-- copy/paste detector -->
<target name="check:cpd" description="Checks similar code blocks."> <target name="check:cpd" depends="build:prepare">
<echo msg="Checking similar code blocks..." />
<phpcpd> <phpcpd>
<fileset refid="sourcecode" /> <fileset refid="sourcecode"/>
<formatter type="pmd" outfile="${dir.reports}/pmd-cpd.xml" /> <formatter type="pmd" outfile="${dir.reports}/pmd-cpd.xml"/>
</phpcpd> </phpcpd>
<!--
Previous / old version
Meritoo <github@meritoo.pl>
2017-02-22
<exec command="phpcpd \-\-log-pmd=${dir.reports}/pmd-cpd.xml ${dir.src}" />
-->
</target> </target>
<!-- Mess detector --> <!-- Mess detector -->
<target name="check:md" description="Generate code metrics"> <target name="check:md" depends="build:prepare">
<echo msg="Generating code metrics..." />
<phpmd rulesets="codesize,controversial,design,naming,unusedcode"> <phpmd rulesets="codesize,controversial,design,naming,unusedcode">
<fileset refid="sourcecode" /> <fileset refid="sourcecode"/>
<formatter type="html" outfile="${dir.reports}/phpmd.html" /> <formatter type="html" outfile="${dir.reports}/phpmd.html"/>
<formatter type="text" outfile="${dir.reports}/phpmd.txt" /> <formatter type="text" outfile="${dir.reports}/phpmd.txt"/>
</phpmd> </phpmd>
</target> </target>
<!-- Code dependency --> <!-- Code dependency -->
<target name="check:depend" description="Checks coupling and dependency"> <target name="check:depend" depends="build:prepare">
<echo msg="Checking coupling and dependency..." />
<phpdepend> <phpdepend>
<fileset refid="sourcecode" /> <fileset refid="sourcecode"/>
<logger type="jdepend-xml" outfile="${dir.reports.pdepend}/jdepend.xml" /> <logger type="jdepend-xml" outfile="${dir.reports.pdepend}/jdepend.xml"/>
<logger type="jdepend-chart" outfile="${dir.reports.pdepend}/dependencies.svg" /> <logger type="jdepend-chart" outfile="${dir.reports.pdepend}/dependencies.svg"/>
<logger type="overview-pyramid" outfile="${dir.reports.pdepend}/overview-pyramid.svg" /> <logger type="overview-pyramid" outfile="${dir.reports.pdepend}/overview-pyramid.svg"/>
</phpdepend> </phpdepend>
</target> </target>
<!-- Measure the size and analyzing the structure of a project --> <!-- Measure the size and analyzing the structure of a project -->
<target name="check:loc" description="Measures the size and analyzes the structure of a project"> <target name="check:loc" depends="build:prepare">
<echo msg="Measuring the size and analyzing the structure of a project..." />
<phploc reportType="txt" reportName="phploc" reportDirectory="${dir.reports}"> <phploc reportType="txt" reportName="phploc" reportDirectory="${dir.reports}">
<fileset refid="sourcecode" /> <fileset refid="sourcecode"/>
</phploc> </phploc>
<!--
Previous / old version
Meritoo <github@meritoo.pl>
2017-02-22
<exec command="phploc \-\-log-csv=${dir.reports}/phploc.csv ${dir.src}" />
-->
</target> </target>
<!-- Unit tests --> <!-- PHPUnit tests -->
<target name="test:unit" description="Executes unit tests"> <target name="test:phpunit" depends="build:prepare">
<echo msg="Running unit tests..." /> <exec command="${tests.phpunit.command}" passthru="true"/>
<exec command="${tests.framework.path}" passthru="true"/> </target>
<!-- Project build clean -->
<target name="build:clean">
<if>
<available file="${dir.reports}" type="dir" property="dir_is_available"/>
<then>
<delete dir="${dir.reports}"/>
</then>
</if>
</target>
<!-- Project build prepare -->
<target name="build:prepare" depends="build:clean">
<mkdir dir="${dir.reports}"/>
<mkdir dir="${dir.reports.pdepend}"/>
<mkdir dir="${dir.reports.coverage}"/>
</target> </target>
<!-- Checkout and finalization --> <!-- Checkout and finalization -->
<target name="app:checkout"> <target name="app:checkout">
<tstamp> <tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M" /> <format property="date_end" pattern="%Y-%m-%d %H:%M"/>
</tstamp> </tstamp>
<echo msg="--------------------------------------------" /> <echo msg="--------------------------------------------"/>
<echo msg="Build tests finished at: ${date_end}" /> <echo msg="Build tests finished at: ${date_end}"/>
<echo msg="--------------------------------------------" /> <echo msg="--------------------------------------------"/>
</target> </target>
</project> </project>

View File

@@ -1,28 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.de/manual/4.8/en/appendixes.configuration.html -->
<phpunit <phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/4.8/phpunit.xsd" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/4.8/phpunit.xsd"
backupGlobals="true" bootstrap="vendor/autoload.php"
backupStaticAttributes="false"
bootstrap="./vendor/autoload.php"
cacheTokens="false"
colors="true" colors="true"
convertErrorsToExceptions="true"
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" verbose="true"
> >
<php> <php>
@@ -31,23 +14,17 @@
<testsuites> <testsuites>
<testsuite name="Meritoo Package - Main Test Suite"> <testsuite name="Meritoo Package - Main Test Suite">
<directory>./tests/</directory> <directory>tests/</directory>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter> <filter>
<whitelist> <whitelist>
<directory>./src/</directory> <directory>src/</directory>
</whitelist> </whitelist>
</filter> </filter>
<groups>
<exclude>
<group>performance</group>
</exclude>
</groups>
<logging> <logging>
<log type="coverage-html" target="./build/logs/phpunit_coverage/html"/> <log type="coverage-html" target="build/reports/phpunit_coverage/html"/>
</logging> </logging>
</phpunit> </phpunit>

View File

@@ -23,7 +23,7 @@ abstract class UnknownTypeException extends Exception
/** /**
* Creates exception * Creates exception
* *
* @param string|int $unknownType The unknown type of something (value of constant) * @param mixed $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 * @return UnknownTypeException
@@ -35,7 +35,7 @@ abstract class UnknownTypeException extends Exception
$allTypes = $typeInstance->getAll(); $allTypes = $typeInstance->getAll();
$types = Arrays::values2string($allTypes, '', ', '); $types = Arrays::values2string($allTypes, '', ', ');
$message = sprintf(sprintf($template, $unknownType, $typeName, $types)); $message = sprintf($template, $unknownType, $typeName, $types);
return new static($message); return new static($message);
} }

View File

@@ -14,13 +14,11 @@ use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException;
use Meritoo\Common\Type\OopVisibilityType; use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\Miscellaneous; use Meritoo\Common\Utilities\Miscellaneous;
use ReflectionClass; use ReflectionClass;
use ReflectionException;
use ReflectionMethod; use ReflectionMethod;
use stdClass; use stdClass;
/** /**
* BaseTestCaseTrait * Trait for the base test case
* Created on 2017-11-02
* *
* @author Meritoo <github@meritoo.pl> * @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl> * @copyright Meritoo <http://www.meritoo.pl>
@@ -173,7 +171,6 @@ trait BaseTestCaseTrait
* @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
@@ -230,8 +227,6 @@ trait BaseTestCaseTrait
* @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
*/ */
protected static function assertConstructorVisibilityAndArguments( protected static function assertConstructorVisibilityAndArguments(
$classNamespace, $classNamespace,
@@ -245,14 +240,19 @@ trait BaseTestCaseTrait
$reflection = new ReflectionClass($classNamespace); $reflection = new ReflectionClass($classNamespace);
$method = $reflection->getConstructor(); $method = $reflection->getConstructor();
static::assertMethodVisibilityAndArguments($classNamespace, $method, $visibilityType, $argumentsCount, $requiredArgumentsCount); static::assertMethodVisibilityAndArguments(
$classNamespace,
$method,
$visibilityType,
$argumentsCount,
$requiredArgumentsCount
);
} }
/** /**
* Asserts that class with given namespace has no constructor * Asserts that class with given namespace has no constructor
* *
* @param string $classNamespace Namespace of class that contains constructor to verify * @param string $classNamespace Namespace of class that contains constructor to verify
* @throws ReflectionException
*/ */
protected static function assertHasNoConstructor($classNamespace) protected static function assertHasNoConstructor($classNamespace)
{ {

View File

@@ -43,7 +43,7 @@ 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 mixed $type The type to check
* @return bool * @return bool
*/ */
public function isCorrectType($type) public function isCorrectType($type)

View File

@@ -64,8 +64,7 @@ class Date
const DATE_DIFFERENCE_UNIT_YEARS = 'years'; const DATE_DIFFERENCE_UNIT_YEARS = 'years';
/** /**
* Returns start and end date for given period. * Returns date's period (that contains start and end date) for given period
* 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 * @throws Exception
@@ -531,11 +530,15 @@ 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 (optional) Beginning of the random date. If not provided, current date will
* @param int $start (optional) Start of random partition * be used (default behaviour).
* @param int $end (optional) End of random partition * @param int $start (optional) Start of random partition. If not provided, 1 will be used
* (default behaviour).
* @param int $end (optional) End of random partition. If not provided, 100 will be used
* (default behaviour).
* @param string $intervalTemplate (optional) Template used to build date interval. The placeholder is replaced * @param string $intervalTemplate (optional) Template used to build date interval. The placeholder is replaced
* with next, iterated value. * with next, iterated value. If not provided, "P%sD" will be used (default
* behaviour).
* @throws Exception * @throws Exception
* @return DateTime * @return DateTime
*/ */
@@ -569,10 +572,11 @@ class 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
* (default behaviour).
* @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. Default: "Y-m-d".
* @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')

View File

@@ -662,7 +662,7 @@ class Reflection
} }
/** /**
* Sets value of given property * Sets value of given property in given object
* *
* @param mixed $object Object that should contains given property * @param mixed $object Object that should contains given property
* @param string $property Name of the property * @param string $property Name of the property
@@ -692,4 +692,25 @@ class Reflection
$reflectionProperty->setAccessible(false); $reflectionProperty->setAccessible(false);
} }
} }
/**
* Sets values of properties in given object
*
* @param mixed $object Object that should contains given property
* @param array $propertiesValues Key-value pairs, where key - name of the property, value - value of the property
*/
public static function setPropertiesValues($object, array $propertiesValues)
{
/*
* No properties?
* Nothing to do
*/
if (empty($propertiesValues)) {
return;
}
foreach ($propertiesValues as $property => $value) {
static::setPropertyValue($object, $property, $value);
}
}
} }

View File

@@ -177,10 +177,13 @@ class Repository
$direction = 'ASC' $direction = 'ASC'
) { ) {
$alias = 'qb'; $alias = 'qb';
$queryBuilder = $repository->createQueryBuilder($alias);
return $repository if (empty($property)) {
->createQueryBuilder($alias) return $queryBuilder;
->orderBy(sprintf('%s.%s', $alias, $property), $direction); }
return $queryBuilder->orderBy(sprintf('%s.%s', $alias, $property), $direction);
} }
/** /**

0
tests/Resources/var/cache/.gitkeep vendored Normal file
View File

View File

View File

View File

@@ -82,8 +82,15 @@ class ReflectionTest extends BaseTestCase
* Class with namespace containing name of class (duplicated string) * Class with namespace containing name of class (duplicated string)
*/ */
if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) { if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) {
self::assertEquals('Symfony\Bundle\SecurityBundle\SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle')); self::assertEquals(
self::assertEquals('SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle', true)); 'Symfony\Bundle\SecurityBundle\SecurityBundle',
Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle')
);
self::assertEquals(
'SecurityBundle',
Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle', true)
);
} }
} }
@@ -115,7 +122,10 @@ class ReflectionTest extends BaseTestCase
* Class with namespace containing name of class (duplicated string) * Class with namespace containing name of class (duplicated string)
*/ */
if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) { if (class_exists('Symfony\Bundle\SecurityBundle\SecurityBundle')) {
self::assertEquals('Symfony\Bundle\SecurityBundle', Reflection::getClassNamespace('Symfony\Bundle\SecurityBundle\SecurityBundle')); self::assertEquals(
'Symfony\Bundle\SecurityBundle',
Reflection::getClassNamespace('Symfony\Bundle\SecurityBundle\SecurityBundle')
);
} }
} }
@@ -183,11 +193,11 @@ class ReflectionTest extends BaseTestCase
public function testGetMethods() public function testGetMethods()
{ {
self::assertEquals(1, count(Reflection::getMethods(B::class, true))); self::assertCount(1, Reflection::getMethods(B::class, true));
self::assertEquals(3, count(Reflection::getMethods(B::class))); self::assertCount(3, Reflection::getMethods(B::class));
self::assertEquals(2, count(Reflection::getMethods(A::class))); self::assertCount(2, Reflection::getMethods(A::class));
self::assertEquals(2, count(Reflection::getMethods(C::class, true))); self::assertCount(2, Reflection::getMethods(C::class, true));
self::assertEquals(5, count(Reflection::getMethods(C::class))); self::assertCount(5, Reflection::getMethods(C::class));
} }
/** /**
@@ -235,9 +245,20 @@ class ReflectionTest extends BaseTestCase
public function testGetPropertiesUsingFilter() public function testGetPropertiesUsingFilter()
{ {
self::assertCount(1, Reflection::getProperties(B::class, ReflectionProperty::IS_PROTECTED)); self::assertCount(
self::assertCount(0, Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE)); 1,
self::assertCount(1, Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE, true)); Reflection::getProperties(B::class, ReflectionProperty::IS_PROTECTED)
);
self::assertCount(
0,
Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE)
);
self::assertCount(
1,
Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE, true)
);
} }
public function testGetPropertiesWithParents() public function testGetPropertiesWithParents()
@@ -484,9 +505,7 @@ class ReflectionTest extends BaseTestCase
public function testSetPropertyValueUsingNotExistingProperty($object, $property) public function testSetPropertyValueUsingNotExistingProperty($object, $property)
{ {
$this->setExpectedException(NotExistingPropertyException::class); $this->setExpectedException(NotExistingPropertyException::class);
Reflection::setPropertyValue($object, $property, 'test test test');
$object = new \stdClass();
Reflection::setPropertyValue($object, 'test', 'test test test');
} }
/** /**
@@ -506,6 +525,43 @@ class ReflectionTest extends BaseTestCase
static::assertSame($newValue, $value); static::assertSame($newValue, $value);
} }
public function testSetPropertiesValuesWithoutProperties()
{
$object = new G();
Reflection::setPropertiesValues($object, []);
static::assertSame($object->getFirstName(), 'John');
static::assertSame($object->getLastName(), 'Scott');
}
/**
* @param mixed $object Object that should contains given property
* @param array $propertiesValues Key-value pairs, where key - name of the property, value - value of the property
*
* @dataProvider provideObjectAndNotExistingProperties
*/
public function testSetPropertiesValuesUsingNotExistingProperties($object, array $propertiesValues)
{
$this->setExpectedException(NotExistingPropertyException::class);
Reflection::setPropertiesValues($object, $propertiesValues);
}
/**
* @param mixed $object Object that should contains given property
* @param array $propertiesValues Key-value pairs, where key - name of the property, value - value of the property
*
* @dataProvider provideObjectAndPropertiesValues
*/
public function testSetPropertiesValues($object, array $propertiesValues)
{
Reflection::setPropertiesValues($object, $propertiesValues);
foreach ($propertiesValues as $property => $value) {
$realValue = Reflection::getPropertyValue($object, $property);
static::assertSame($value, $realValue);
}
}
/** /**
* Provides invalid class and trait * Provides invalid class and trait
* *
@@ -588,4 +644,104 @@ class ReflectionTest extends BaseTestCase
'Smith', 'Smith',
]; ];
} }
/**
* Provides object and not existing properties
*
* @return Generator
*/
public function provideObjectAndNotExistingProperties()
{
yield[
new \stdClass(),
[
'test' => 1,
],
];
yield[
new A(),
[
'test' => 2,
],
];
yield[
new B(),
[
'firstName' => '',
],
];
}
/**
* Provides object and its new values of properties
*
* @return Generator
*/
public function provideObjectAndPropertiesValues()
{
yield[
new A(),
[
'count' => 123,
],
];
yield[
new B(),
[
'name' => 'test test',
],
];
yield[
new G(),
[
'firstName' => 'Jane',
],
];
yield[
new G(),
[
'lastName' => 'Smith',
],
];
yield[
new G(),
[
'firstName' => 'Jane',
'lastName' => 'Brown',
],
];
yield[
new F(
123,
'New York',
'USA',
'UnKnown'
),
[
'gInstance' => new G(),
],
];
yield[
new F(
123,
'New York',
'USA',
'UnKnown',
'Mary',
'Brown'
),
[
'country' => 'Canada',
'accountBalance' => 456,
],
];
}
} }

View File

@@ -8,6 +8,10 @@
namespace Meritoo\Common\Test\Utilities; namespace Meritoo\Common\Test\Utilities;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\OrderBy;
use Doctrine\ORM\QueryBuilder;
use Generator; use Generator;
use Meritoo\Common\Test\Base\BaseTestCase; use Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Test\Utilities\Repository\Sortable; use Meritoo\Common\Test\Utilities\Repository\Sortable;
@@ -160,7 +164,7 @@ class RepositoryTest extends BaseTestCase
/** /**
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays * @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. * @param bool $max If is set to true, maximum value is returned. Otherwise - minimum.
* @param int $expected Extreme position (max or min) of given items * @param int $expected Extreme position (max or min) of given items
* *
* @dataProvider provideArraysWithoutExtremePositionToGetExtremePosition * @dataProvider provideArraysWithoutExtremePositionToGetExtremePosition
@@ -170,12 +174,122 @@ class RepositoryTest extends BaseTestCase
static::assertEquals($expected, Repository::getExtremePosition($items, $max)); static::assertEquals($expected, Repository::getExtremePosition($items, $max));
} }
public function testGetExtremePositionUsingObjects() /**
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $max If is set to true, maximum value is returned. Otherwise - minimum.
* @param int $expected Extreme position (max or min) of given items
*
* @dataProvider provideArraysWithExtremePositionToGetExtremePosition
*/
public function testGetExtremePositionUsingArraysWithExtremePosition(array $items, $max, $expected)
{ {
static::assertEquals($expected, Repository::getExtremePosition($items, $max));
} }
public function testGetEntityOrderedQueryBuilder() /**
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $max If is set to true, maximum value is returned. Otherwise - minimum.
* @param int $expected Extreme position (max or min) of given items
*
* @dataProvider provideObjectsWithoutExtremePositionToGetExtremePosition
*/
public function testGetExtremePositionUsingObjectsWithoutExtremePosition(array $items, $max, $expected)
{ {
static::assertEquals($expected, Repository::getExtremePosition($items, $max));
}
/**
* @param array $items Objects who have "getPosition()" and "setPosition()" methods or arrays
* @param bool $max If is set to true, maximum value is returned. Otherwise - minimum.
* @param int $expected Extreme position (max or min) of given items
*
* @dataProvider provideObjectsWithExtremePositionToGetExtremePosition
*/
public function testGetExtremePositionUsingObjectsWithExtremePosition(array $items, $max, $expected)
{
static::assertEquals($expected, Repository::getExtremePosition($items, $max));
}
public function testGetEntityOrderedQueryBuilderUsingDefaults()
{
$entityManager = $this->getMock(EntityManagerInterface::class);
$entityRepository = $this
->getMockBuilder(EntityRepository::class)
->disableOriginalConstructor()
->setMethods([
'createQueryBuilder',
])
->getMock();
$expectedQueryBuilder = new QueryBuilder($entityManager);
$expectedQueryBuilder->from('any_table_name', 'qb');
$entityRepository
->expects(static::once())
->method('createQueryBuilder')
->willReturn($expectedQueryBuilder);
$queryBuilder = Repository::getEntityOrderedQueryBuilder($entityRepository);
$selectDQLPart = $queryBuilder->getDQLPart('select');
$whereDQLPart = $queryBuilder->getDQLPart('where');
$orderDQLPart = $queryBuilder->getDQLPart('orderBy');
/* @var OrderBy $orderBy */
$orderBy = $orderDQLPart[0];
static::assertInstanceOf(QueryBuilder::class, $queryBuilder);
static::assertArraySubset(['qb'], $queryBuilder->getRootAliases());
static::assertSame([], $selectDQLPart);
static::assertNull($whereDQLPart);
static::assertSame(['qb.name ASC'], $orderBy->getParts());
}
/**
* @param string $property Name of property used by the ORDER BY clause
* @param string $direction Direction used by the ORDER BY clause ("ASC" or "DESC")
* @param string $expectedOrderBy Expected ORDER BY clause
*
* @dataProvider providePropertyAndDirectionToGetEntityOrderedQueryBuilder
*/
public function testGetEntityOrderedQueryBuilder($property, $direction, $expectedOrderBy)
{
$entityManager = $this->getMock(EntityManagerInterface::class);
$entityRepository = $this
->getMockBuilder(EntityRepository::class)
->disableOriginalConstructor()
->setMethods([
'createQueryBuilder',
])
->getMock();
$expectedQueryBuilder = new QueryBuilder($entityManager);
$expectedQueryBuilder->from('any_table_name', 'qb');
$entityRepository
->expects(static::once())
->method('createQueryBuilder')
->willReturn($expectedQueryBuilder);
$queryBuilder = Repository::getEntityOrderedQueryBuilder($entityRepository, $property, $direction);
$selectDQLPart = $queryBuilder->getDQLPart('select');
$whereDQLPart = $queryBuilder->getDQLPart('where');
$orderDQLPart = $queryBuilder->getDQLPart('orderBy');
static::assertInstanceOf(QueryBuilder::class, $queryBuilder);
static::assertArraySubset(['qb'], $queryBuilder->getRootAliases());
static::assertSame([], $selectDQLPart);
static::assertNull($whereDQLPart);
if (empty($property)) {
static::assertSame([], $orderDQLPart);
} else {
/* @var OrderBy $orderBy */
$orderBy = $orderDQLPart[0];
static::assertSame([$expectedOrderBy], $orderBy->getParts());
}
} }
/** /**
@@ -581,7 +695,7 @@ class RepositoryTest extends BaseTestCase
[], [],
], ],
true, true,
1, 2,
]; ];
yield[ yield[
@@ -596,7 +710,125 @@ class RepositoryTest extends BaseTestCase
[], [],
], ],
false, false,
2, 1,
];
}
/**
* Provides objects without extreme position used to get extreme position
*
* @return Generator
*/
public function provideObjectsWithoutExtremePositionToGetExtremePosition()
{
yield[
[],
false,
null,
];
yield[
[],
true,
null,
];
yield[
[
new Sortable(),
new Sortable(),
new Sortable(),
],
true,
null,
];
yield[
[
new Sortable(),
new Sortable(),
new Sortable(),
],
false,
null,
];
}
/**
* Provides objects with extreme position used to get extreme position
*
* @return Generator
*/
public function provideObjectsWithExtremePositionToGetExtremePosition()
{
yield[
[
new Sortable(1),
new Sortable(2),
new Sortable(3),
],
true,
3,
];
yield[
[
new Sortable(1),
new Sortable(2),
new Sortable(3),
],
false,
1,
];
}
/**
* Provide name of property, direction and expected ORDER BY clause used to get query builder
*
* @return Generator
*/
public function providePropertyAndDirectionToGetEntityOrderedQueryBuilder()
{
yield[
null,
null,
'',
];
yield[
'',
'',
'',
];
yield[
'first_name',
'',
'qb.first_name ASC',
];
yield[
'first_name',
'asc',
'qb.first_name asc',
];
yield[
'first_name',
'ASC',
'qb.first_name ASC',
];
yield[
'first_name',
'desc',
'qb.first_name desc',
];
yield[
'first_name',
'DESC',
'qb.first_name DESC',
]; ];
} }
} }