4 Commits
0.1.4 ... 0.1.3

Author SHA1 Message Date
Krzysztof Nizioł
e31af27c01 Merge branch 'master' of github.com:meritoo/common-library
# Conflicts:
#	README.md
2018-09-06 22:01:00 +02:00
Krzysztof Niziol
3bcda8e906 composer.json - update name of this package (name of vendor, actually) 2017-11-08 14:52:19 +01:00
Krzysztof Niziol
1641c50d1d composer.json - update name of this package 2017-11-07 16:34:49 +01:00
Krzysztof Niziol
afbbdfe437 composer.json - update name of this package 2017-11-07 15:24:51 +01:00
26 changed files with 424 additions and 834 deletions

View File

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

View File

@@ -2,13 +2,6 @@
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
1. Tests > refactoring & minor improvements

View File

@@ -2,14 +2,26 @@
Common and useful classes, methods, exceptions etc.
[![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)
[![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
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:
```bash
composer require meritoo/common-library
composer require wiosna-dev/common-library
```
> [How to install Composer?](https://getcomposer.org/download)

View File

@@ -1 +1 @@
0.1.4
0.1.3

View File

@@ -1,30 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<available file="phing/properties" property="custom.properties.available"/>
<then>
<property file="${project.basedir}/phing/properties"/>
<property file="phing/properties"/>
</then>
<else>
<property file="${project.basedir}/phing/properties.dist"/>
<property file="phing/properties.dist"/>
</else>
</if>
<!-- Default / main target -->
<target name="build:main"
depends="build:app,
build:tests"
/>
depends="build:app, build:tests"
description="Builds everything and runs all tests" />
<!-- Build app -->
<target name="build:app">
<phing phingfile="${project.basedir}/phing/app.xml" haltonfailure="true"/>
<target name="build:app" description="Prepares app to build and tests">
<phing phingfile="phing/app.xml" haltonfailure="true"/>
</target>
<!-- Build tests -->
<target name="build:tests">
<phing phingfile="${project.basedir}/phing/tests.xml" haltonfailure="true"/>
<target name="build:tests" description="Runs all tests, checks and creates docs">
<phing phingfile="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>
</project>

View File

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

View File

@@ -1,9 +1,6 @@
version: '3'
services:
#
# Required to run project
#
php:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-php
@@ -12,22 +9,12 @@ services:
build:
context: ./docker/config
args:
- TIMEZONE=${TIMEZONE}
- TIMEZONE=${TIMEZONE}
volumes:
- .:/project:cached
- .:/project:cached
composer:
image: ${DOCKER_CONTAINER_OWNER}/${DOCKER_CONTAINER_PROJECT}-php
container_name: ${DOCKER_CONTAINER_OWNER}-${DOCKER_CONTAINER_PROJECT}-composer
entrypoint: php -d memory_limit=-1 /usr/local/bin/composer
entrypoint: 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:
- .:/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');" \
&& php -r "if (hash_file('SHA384', 'composer-setup.php') === \
'93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo \
'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');" \

View File

@@ -15,11 +15,11 @@ Development-related information
docker-compose up -d
```
2. Rebuild project by running command (installs packages, prepares required directories and runs tests):
2. Install packages by running command:
```bash
docker-compose exec php phing
```
```bash
docker-compose run composer install
```
> [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:
```bash
docker-compose run --rm composer [command]
docker-compose run composer <command>
```
Examples below.
@@ -36,25 +36,25 @@ Examples below.
##### Install packages
```bash
docker-compose run --rm composer install
docker-compose run composer install
```
##### Update packages
```bash
docker-compose run --rm composer update
docker-compose run composer update
```
##### Add package
```bash
docker-compose run --rm composer require [vendor]/[package]
docker-compose run composer require <vendor>/<package>
```
##### Remove package
```bash
docker-compose run --rm composer remove [vendor]/[package]
docker-compose run composer remove <vendor>/<package>
```
# Coding Standards Fixer
@@ -65,12 +65,6 @@ Fix coding standard by running command:
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:
```bash
@@ -83,35 +77,37 @@ docker-compose exec php rm .php_cs.cache && docker-compose exec php php-cs-fixer
### Prerequisites
Install required packages by running command: `docker-compose run --rm composer install`.
Install required packages by running command: `docker-compose run composer install`.
### Running [PHPUnit](https://phpunit.de) tests
### Running tests
##### Easy (with code coverage)
#### Simply & quick, without code coverage
Tests are running using Docker and `php` service defined in `docker-compose.yml`. Example:
```bash
docker-compose run --rm phpunit --verbose
docker-compose exec php phpunit --no-coverage
```
or
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 phing -f phing/tests.xml test:phpunit
docker-compose exec php 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
Rebuild project and run tests by running command:

View File

@@ -1,184 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.14.0">
<!-- Properties -->
<if>
<available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<available file="phing/properties" property="custom.properties.available"/>
<then>
<property file="${project.basedir}/phing/properties"/>
<property file="phing/properties"/>
</then>
<else>
<property file="${project.basedir}/phing/properties.dist"/>
<property file="phing/properties.dist"/>
</else>
</if>
<!-- Filesets -->
<import file="${project.basedir}/phing/filesets.xml"/>
<!-- Default / main target -->
<target name="build:main"
depends="build:app"
/>
description="Builds the application" />
<!-- App target -->
<target name="build:app"
depends="app:clean,
app:composer:self-update,
app:composer:install,
app:composer:validate,
app:checkout"
/>
depends="app:composer, app:vendors, app:checkout"
description="Prepares app to build." />
<!-- Updates Composer and validates composer.* files -->
<target name="app:composer" description="Updates Composer and validates composer.* files">
<echo msg="Updating Composer and validating composer.* files..." />
<!-- Updates Composer -->
<target name="app:composer:self-update">
<if>
<not>
<available file="${composer.path}" property="composer.local.unavailable"/>
</not>
<available file="composer.phar" />
<then>
<echo msg="[Skipped] Downloading of Composer skipped, because exist in the project..." />
</then>
<else>
<if>
<os family="windows"/>
<os family="windows" />
<then>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer."/>
<fail message="Composer not found! Go to http://getcomposer.org/download and download the Composer." />
</then>
<else>
<exec command="${composer.download_command}" checkreturn="true" passthru="true"/>
<exec command="${composer.download_command}" checkreturn="true" />
</else>
</if>
</then>
</else>
</if>
<!-- Update Composer -->
<composer php="${composer.php}" composer="${composer.path}" command="selfupdate">
<arg value="--ansi"/>
<composer command="selfupdate" />
<!-- Validate Composer -->
<composer command="validate">
<arg line="--no-check-all --strict" />
</composer>
</target>
<!-- Validates composer.* files -->
<target name="app:composer:validate" depends="app:composer:install">
<composer php="${composer.php}" composer="${composer.path}" command="validate">
<arg value="--no-check-all"/>
<arg value="--strict"/>
<arg value="--ansi"/>
</composer>
</target>
<!-- Project Install/update vendors -->
<target name="app:vendors" description="Installs / updates vendors">
<echo msg="Installing / updating vendors..." />
<!-- Project clean -->
<target name="app:clean">
<if>
<equals arg1="${env}" arg2="prod"/>
<istrue value="${composer.self-update}"/>
<then>
<echo message="[Skipped] Cleaning project (and directories cleanup) -> 'prod' environment"/>
<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>
</then>
<else>
<foreach list="${directoriesToEmpty}" param="directory" target="app:clean:empty"/>
<composer php="${composer.php}" composer="${composer.path}" command="install" />
</else>
</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>
<!-- Checkout and finalization -->
<target name="app:checkout">
<tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M"/>
<format property="date_end" pattern="%Y-%m-%d %H:%M" />
</tstamp>
<echo msg="------------------------------------"/>
<echo msg="Build finished at: ${date_end}"/>
<echo msg="------------------------------------"/>
<echo msg="------------------------------------" />
<echo msg="Build finished at: ${date_end}" />
<echo msg="------------------------------------" />
</target>
</project>

View File

@@ -1,20 +0,0 @@
#!/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

View File

@@ -1,36 +0,0 @@
<?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,3 +1,19 @@
# --------------------------------------------------------------------------------
# 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
# --------------------------------------------------------------------------------
@@ -6,6 +22,10 @@
#
env = dev
# Install assets using symlinks
#
assets.installWithSymlink = true
# 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.
@@ -20,63 +40,67 @@ cache.clearWithWarmup = false
# Composer
# --------------------------------------------------------------------------------
# Command used to download Composer
#
composer.download_command = bash ${project.basedir}/phing/composer-install.sh
composer.download_command = php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"
# Path to composer executable or downloaded composer.phar file
# Path to composer executable or composer.phar file
#
composer.path = ${project.basedir}/composer.phar
composer.path = composer.phar
#composer.path = /usr/local/bin/composer
# Path to php executable used by composer
#
composer.php = php
# Self update of the composer
#
composer.self-update = false
# Validate the composer.json file
#
composer.validate = false
# --------------------------------------------------------------------------------
# Directories
# --------------------------------------------------------------------------------
# System directories
#
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.src = ${project.basedir}/src
dir.tests = ${project.basedir}/tests
# --------------------------------------------------------------------------------
# Build directories
#
# --------------------------------------------------------------------------------
dir.build = ${project.basedir}/build
dir.reports = ${dir.build}/reports
dir.reports = ${dir.build}/logs
dir.reports.pdepend = ${dir.reports}/pdepend
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
#
dir.data.tests = ${dir.data}/tests
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
dir.data.temporary = ${dir.data}/tmp
# --------------------------------------------------------------------------------
# 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)
#
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
phpCsFixer.path = ./vendor/bin/php-cs-fixer

View File

@@ -1,133 +1,230 @@
<?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.
<project name="Meritoo Package" basedir="." default="build:main" phingVersion="2.16.0">
<autoloader/>
Meritoo <github@meritoo.pl>
2017-02-23
-->
<autoloader />
<!-- Properties -->
<if>
<available file="${project.basedir}/phing/properties" property="custom.properties.available"/>
<available file="phing/properties" property="custom.properties.available"/>
<then>
<property file="${project.basedir}/phing/properties"/>
<property file="phing/properties"/>
</then>
<else>
<property file="${project.basedir}/phing/properties.dist"/>
<property file="phing/properties.dist"/>
</else>
</if>
<!-- Filesets -->
<fileset id="sourcecode" dir="${dir.src}">
<include name="**/*.php"/>
<exclude name="*Test.php"/>
<exclude name="**/*Test.php"/>
<exclude name="**/Resources/**"/>
<exclude name="**/DataFixtures/**"/>
<exclude name="**/Tests/**"/>
<include name="**/*.php" />
<exclude name="*Test.php" />
<exclude name="**/*Test.php" />
<exclude name="**/Resources/**" />
<exclude name="**/DataFixtures/**" />
<exclude name="**/Tests/**" />
</fileset>
<fileset id="tests" dir="${dir.tests}">
<include name="**/*Test*.php"/>
<include name="**/*Test*.php" />
</fileset>
<!-- Default / main target -->
<target name="build:main"
depends="build:fix-coding-standards,
build:check,
build:test,
app:checkout"
/>
depends="build:fix-coding-standards, build:clean, build:prepare, build:check, build:test, app:checkout"
description="Runs all tests and builds everything" />
<!--
Before:
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) -->
<target name="build:fix-coding-standards">
<exec command="${tests.cs_fixer.command}" passthru="true"/>
<target name="build:fix-coding-standards" description="Fixes coding standards using the PHP Coding Standards Fixer">
<echo msg="Fixing coding standards using the PHP Coding Standards Fixer (http://cs.sensiolabs.org)..." />
<!--
Attention.
Rules for formatting are defined in /.php_cs.dist file.
-->
<exec
passthru="true"
command="${phpCsFixer.path} fix --verbose"
/>
</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 -->
<target name="build:check"
depends="check:cs,
check:md,
check:cpd,
check:depend,
check:loc"
/>
depends="check:cs, check:md, check:cpd, check:depend, check:loc"
description="Analyzes code" />
<!-- Test target -->
<target name="build:test"
depends="test:phpunit"
/>
depends="test:unit"
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 -->
<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">
<fileset refid="sourcecode"/>
<formatter type="checkstyle" outfile="${dir.reports}/checkstyle.xml"/>
<formatter type="csv" outfile="${dir.reports}/checkstyle.csv"/>
<formatter type="summary" outfile="${dir.reports}/checkstyle_summary.txt"/>
<fileset refid="sourcecode" />
<formatter type="checkstyle" outfile="${dir.reports}/checkstyle.xml" />
<formatter type="csv" outfile="${dir.reports}/checkstyle.csv" />
<formatter type="summary" outfile="${dir.reports}/checkstyle_summary.txt" />
</phpcodesniffer>
</target>
<!-- copy/paste detector -->
<target name="check:cpd" depends="build:prepare">
<target name="check:cpd" description="Checks similar code blocks.">
<echo msg="Checking similar code blocks..." />
<phpcpd>
<fileset refid="sourcecode"/>
<formatter type="pmd" outfile="${dir.reports}/pmd-cpd.xml"/>
<fileset refid="sourcecode" />
<formatter type="pmd" outfile="${dir.reports}/pmd-cpd.xml" />
</phpcpd>
<!--
Previous / old version
Meritoo <github@meritoo.pl>
2017-02-22
<exec command="phpcpd \-\-log-pmd=${dir.reports}/pmd-cpd.xml ${dir.src}" />
-->
</target>
<!-- Mess detector -->
<target name="check:md" depends="build:prepare">
<target name="check:md" description="Generate code metrics">
<echo msg="Generating code metrics..." />
<phpmd rulesets="codesize,controversial,design,naming,unusedcode">
<fileset refid="sourcecode"/>
<formatter type="html" outfile="${dir.reports}/phpmd.html"/>
<formatter type="text" outfile="${dir.reports}/phpmd.txt"/>
<fileset refid="sourcecode" />
<formatter type="html" outfile="${dir.reports}/phpmd.html" />
<formatter type="text" outfile="${dir.reports}/phpmd.txt" />
</phpmd>
</target>
<!-- Code dependency -->
<target name="check:depend" depends="build:prepare">
<target name="check:depend" description="Checks coupling and dependency">
<echo msg="Checking coupling and dependency..." />
<phpdepend>
<fileset refid="sourcecode"/>
<logger type="jdepend-xml" outfile="${dir.reports.pdepend}/jdepend.xml"/>
<logger type="jdepend-chart" outfile="${dir.reports.pdepend}/dependencies.svg"/>
<logger type="overview-pyramid" outfile="${dir.reports.pdepend}/overview-pyramid.svg"/>
<fileset refid="sourcecode" />
<logger type="jdepend-xml" outfile="${dir.reports.pdepend}/jdepend.xml" />
<logger type="jdepend-chart" outfile="${dir.reports.pdepend}/dependencies.svg" />
<logger type="overview-pyramid" outfile="${dir.reports.pdepend}/overview-pyramid.svg" />
</phpdepend>
</target>
<!-- Measure the size and analyzing the structure of a project -->
<target name="check:loc" depends="build:prepare">
<target name="check:loc" description="Measures the size and analyzes the structure of a project">
<echo msg="Measuring the size and analyzing the structure of a project..." />
<phploc reportType="txt" reportName="phploc" reportDirectory="${dir.reports}">
<fileset refid="sourcecode"/>
<fileset refid="sourcecode" />
</phploc>
<!--
Previous / old version
Meritoo <github@meritoo.pl>
2017-02-22
<exec command="phploc \-\-log-csv=${dir.reports}/phploc.csv ${dir.src}" />
-->
</target>
<!-- PHPUnit tests -->
<target name="test:phpunit" depends="build:prepare">
<exec command="${tests.phpunit.command}" 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}"/>
<!-- Unit tests -->
<target name="test:unit" description="Executes unit tests">
<echo msg="Running unit tests..." />
<exec command="${tests.framework.path}" passthru="true"/>
</target>
<!-- Checkout and finalization -->
<target name="app:checkout">
<tstamp>
<format property="date_end" pattern="%Y-%m-%d %H:%M"/>
<format property="date_end" pattern="%Y-%m-%d %H:%M" />
</tstamp>
<echo msg="--------------------------------------------"/>
<echo msg="Build tests finished at: ${date_end}"/>
<echo msg="--------------------------------------------"/>
<echo msg="--------------------------------------------" />
<echo msg="Build tests finished at: ${date_end}" />
<echo msg="--------------------------------------------" />
</target>
</project>

View File

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

View File

@@ -23,9 +23,9 @@ abstract class UnknownTypeException extends Exception
/**
* Creates exception
*
* @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 string $typeName Name of the something
* @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 string $typeName Name of the something
* @return UnknownTypeException
*/
public static function create($unknownType, BaseType $typeInstance, $typeName)
@@ -35,7 +35,7 @@ abstract class UnknownTypeException extends Exception
$allTypes = $typeInstance->getAll();
$types = Arrays::values2string($allTypes, '', ', ');
$message = sprintf($template, $unknownType, $typeName, $types);
$message = sprintf(sprintf($template, $unknownType, $typeName, $types));
return new static($message);
}

View File

@@ -14,11 +14,13 @@ use Meritoo\Common\Exception\Type\UnknownOopVisibilityTypeException;
use Meritoo\Common\Type\OopVisibilityType;
use Meritoo\Common\Utilities\Miscellaneous;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use stdClass;
/**
* Trait for the base test case
* BaseTestCaseTrait
* Created on 2017-11-02
*
* @author Meritoo <github@meritoo.pl>
* @copyright Meritoo <http://www.meritoo.pl>
@@ -171,6 +173,7 @@ trait BaseTestCaseTrait
* @param int $requiredArgumentsCount (optional) Expected count/amount of required arguments
* of the verified method
* @throws UnknownOopVisibilityTypeException
* @throws ReflectionException
*
* Attention. 2nd argument, the $method, may be:
* - string - name of the method
@@ -227,6 +230,8 @@ trait BaseTestCaseTrait
* @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
* method
* @throws ReflectionException
* @throws UnknownOopVisibilityTypeException
*/
protected static function assertConstructorVisibilityAndArguments(
$classNamespace,
@@ -240,19 +245,14 @@ trait BaseTestCaseTrait
$reflection = new ReflectionClass($classNamespace);
$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
*
* @param string $classNamespace Namespace of class that contains constructor to verify
* @throws ReflectionException
*/
protected static function assertHasNoConstructor($classNamespace)
{

View File

@@ -43,7 +43,7 @@ abstract class BaseType
/**
* Returns information if given type is correct
*
* @param mixed $type The type to check
* @param string $type The type to check
* @return bool
*/
public function isCorrectType($type)

View File

@@ -64,7 +64,8 @@ class Date
const DATE_DIFFERENCE_UNIT_YEARS = 'years';
/**
* Returns date's period (that contains start and end date) for given period
* Returns 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.
* @throws Exception
@@ -530,15 +531,11 @@ class Date
/**
* Returns random date based on given start date
*
* @param DateTime $startDate (optional) Beginning of the random date. If not provided, current date will
* be used (default behaviour).
* @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 DateTime $startDate The start date. Start of the random date.
* @param int $start (optional) Start 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
* with next, iterated value. If not provided, "P%sD" will be used (default
* behaviour).
* with next, iterated value.
* @throws Exception
* @return DateTime
*/
@@ -572,11 +569,10 @@ class 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
* instance of DateTime class are allowed (e.g. "now", "last day of next
* month", "yyyy"). Otherwise - not and every incorrect value is refused
* (default behaviour).
* month", "yyyy"). Otherwise - not and every incorrect value is refused.
* @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
* "2015-01-01 10:00" value. Default: "Y-m-d".
* "2015-01-01 10:00" value.
* @return DateTime|bool
*/
public static function getDateTime($value, $allowCompoundFormats = false, $dateFormat = 'Y-m-d')

View File

@@ -662,7 +662,7 @@ class Reflection
}
/**
* Sets value of given property in given object
* Sets value of given property
*
* @param mixed $object Object that should contains given property
* @param string $property Name of the property
@@ -692,25 +692,4 @@ class Reflection
$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,13 +177,10 @@ class Repository
$direction = 'ASC'
) {
$alias = 'qb';
$queryBuilder = $repository->createQueryBuilder($alias);
if (empty($property)) {
return $queryBuilder;
}
return $queryBuilder->orderBy(sprintf('%s.%s', $alias, $property), $direction);
return $repository
->createQueryBuilder($alias)
->orderBy(sprintf('%s.%s', $alias, $property), $direction);
}
/**

View File

View File

@@ -82,15 +82,8 @@ class ReflectionTest extends BaseTestCase
* 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)
);
self::assertEquals('Symfony\Bundle\SecurityBundle\SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle'));
self::assertEquals('SecurityBundle', Reflection::getClassName('Symfony\Bundle\SecurityBundle\SecurityBundle', true));
}
}
@@ -122,10 +115,7 @@ class ReflectionTest extends BaseTestCase
* 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')
);
self::assertEquals('Symfony\Bundle\SecurityBundle', Reflection::getClassNamespace('Symfony\Bundle\SecurityBundle\SecurityBundle'));
}
}
@@ -193,11 +183,11 @@ class ReflectionTest extends BaseTestCase
public function testGetMethods()
{
self::assertCount(1, Reflection::getMethods(B::class, true));
self::assertCount(3, Reflection::getMethods(B::class));
self::assertCount(2, Reflection::getMethods(A::class));
self::assertCount(2, Reflection::getMethods(C::class, true));
self::assertCount(5, Reflection::getMethods(C::class));
self::assertEquals(1, count(Reflection::getMethods(B::class, true)));
self::assertEquals(3, count(Reflection::getMethods(B::class)));
self::assertEquals(2, count(Reflection::getMethods(A::class)));
self::assertEquals(2, count(Reflection::getMethods(C::class, true)));
self::assertEquals(5, count(Reflection::getMethods(C::class)));
}
/**
@@ -245,20 +235,9 @@ class ReflectionTest extends BaseTestCase
public function testGetPropertiesUsingFilter()
{
self::assertCount(
1,
Reflection::getProperties(B::class, ReflectionProperty::IS_PROTECTED)
);
self::assertCount(
0,
Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE)
);
self::assertCount(
1,
Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE, true)
);
self::assertCount(1, Reflection::getProperties(B::class, ReflectionProperty::IS_PROTECTED));
self::assertCount(0, Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE));
self::assertCount(1, Reflection::getProperties(B::class, ReflectionProperty::IS_PRIVATE, true));
}
public function testGetPropertiesWithParents()
@@ -505,7 +484,9 @@ class ReflectionTest extends BaseTestCase
public function testSetPropertyValueUsingNotExistingProperty($object, $property)
{
$this->setExpectedException(NotExistingPropertyException::class);
Reflection::setPropertyValue($object, $property, 'test test test');
$object = new \stdClass();
Reflection::setPropertyValue($object, 'test', 'test test test');
}
/**
@@ -525,43 +506,6 @@ class ReflectionTest extends BaseTestCase
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
*
@@ -644,104 +588,4 @@ class ReflectionTest extends BaseTestCase
'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,10 +8,6 @@
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 Meritoo\Common\Test\Base\BaseTestCase;
use Meritoo\Common\Test\Utilities\Repository\Sortable;
@@ -164,7 +160,7 @@ class RepositoryTest extends BaseTestCase
/**
* @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 bool $max (optional) If is set to true, maximum value is returned. Otherwise - minimum.
* @param int $expected Extreme position (max or min) of given items
*
* @dataProvider provideArraysWithoutExtremePositionToGetExtremePosition
@@ -174,122 +170,12 @@ class RepositoryTest extends BaseTestCase
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 provideArraysWithExtremePositionToGetExtremePosition
*/
public function testGetExtremePositionUsingArraysWithExtremePosition(array $items, $max, $expected)
public function testGetExtremePositionUsingObjects()
{
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 provideObjectsWithoutExtremePositionToGetExtremePosition
*/
public function testGetExtremePositionUsingObjectsWithoutExtremePosition(array $items, $max, $expected)
public function testGetEntityOrderedQueryBuilder()
{
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());
}
}
/**
@@ -695,7 +581,7 @@ class RepositoryTest extends BaseTestCase
[],
],
true,
2,
1,
];
yield[
@@ -710,125 +596,7 @@ class RepositoryTest extends BaseTestCase
[],
],
false,
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',
2,
];
}
}