* initial commit
This commit is contained in:
commit
1143075e17
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
.idea
|
||||
composer.phar
|
||||
|
||||
clover.xml
|
||||
coveralls-upload.json
|
||||
phpunit.xml
|
||||
vendor/
|
||||
48
bin/clear-config-cache.php
Normal file
48
bin/clear-config-cache.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
/**
|
||||
* Script for clearing the configuration cache.
|
||||
*
|
||||
* Can also be invoked as `composer clear-config-cache`.
|
||||
*
|
||||
* @see https://github.com/zendframework/zend-expressive-skeleton for the canonical source repository
|
||||
* @copyright Copyright (c) 2017 Zend Technologies USA Inc. (http://www.zend.com)
|
||||
* @license https://github.com/zendframework/zend-expressive-skeleton/blob/master/LICENSE.md New BSD License
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
chdir(__DIR__ . '/../');
|
||||
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
$config = include 'config/config.php';
|
||||
|
||||
if (! isset($config['config_cache_path'])) {
|
||||
echo "No configuration cache path found" . PHP_EOL;
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (! file_exists($config['config_cache_path'])) {
|
||||
printf(
|
||||
"Configured config cache file '%s' not found%s",
|
||||
$config['config_cache_path'],
|
||||
PHP_EOL
|
||||
);
|
||||
exit(0);
|
||||
}
|
||||
|
||||
if (false === unlink($config['config_cache_path'])) {
|
||||
printf(
|
||||
"Error removing config cache file '%s'%s",
|
||||
$config['config_cache_path'],
|
||||
PHP_EOL
|
||||
);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
printf(
|
||||
"Removed configured config cache file '%s'%s",
|
||||
$config['config_cache_path'],
|
||||
PHP_EOL
|
||||
);
|
||||
exit(0);
|
||||
17
bin/cli
Executable file
17
bin/cli
Executable file
@ -0,0 +1,17 @@
|
||||
#!/usr/bin/php
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
use Symfony\Component\Console\Application;
|
||||
|
||||
/** @var \Interop\Container\ContainerInterface $container */
|
||||
$container = require __DIR__ . '/../config/container.php';
|
||||
$application = new Application('Application console');
|
||||
|
||||
$commands = $container->get('config')['console']['commands'];
|
||||
foreach ($commands as $command) {
|
||||
$application->add($container->get($command));
|
||||
}
|
||||
|
||||
$application->run();
|
||||
9
cli-config.php
Normal file
9
cli-config.php
Normal file
@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
$container = require 'config/container.php';
|
||||
|
||||
return new \Symfony\Component\Console\Helper\HelperSet([
|
||||
'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper(
|
||||
$container->get('doctrine.entity_manager.orm_default')
|
||||
),
|
||||
]);
|
||||
99
composer.json
Normal file
99
composer.json
Normal file
@ -0,0 +1,99 @@
|
||||
{
|
||||
"name": "zendframework/zend-expressive-skeleton",
|
||||
"description": "Zend expressive skeleton. Begin developing PSR-15 middleware applications in seconds!",
|
||||
"type": "project",
|
||||
"homepage": "https://github.com/zendframework/zend-expressive-skeleton",
|
||||
"license": "BSD-3-Clause",
|
||||
"keywords": [
|
||||
"skeleton",
|
||||
"middleware",
|
||||
"psr",
|
||||
"psr-7",
|
||||
"psr-11",
|
||||
"psr-15",
|
||||
"zf",
|
||||
"zendframework",
|
||||
"zend-expressive"
|
||||
],
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"zf": {
|
||||
"component-whitelist": [
|
||||
"zendframework/zend-expressive",
|
||||
"zendframework/zend-expressive-helpers",
|
||||
"zendframework/zend-expressive-router",
|
||||
"zendframework/zend-httphandlerrunner",
|
||||
"zendframework/zend-expressive-fastroute"
|
||||
]
|
||||
}
|
||||
},
|
||||
"support": {
|
||||
"issues": "https://github.com/zendframework/zend-expressive-skeleton/issues",
|
||||
"source": "https://github.com/zendframework/zend-expressive-skeleton",
|
||||
"rss": "https://github.com/zendframework/zend-expressive-skeleton/releases.atom",
|
||||
"slack": "https://zendframework-slack.herokuapp.com",
|
||||
"forum": "https://discourse.zendframework.com/c/questions/expressive"
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.1",
|
||||
"dasprid/container-interop-doctrine": "^1.1",
|
||||
"doctrine/orm": "^2.6",
|
||||
"gedmo/doctrine-extensions": "^2.4",
|
||||
"roave/security-advisories": "dev-master",
|
||||
"symfony/console": "^4.0",
|
||||
"tuupola/cors-middleware": "^0.7.0",
|
||||
"zendframework/zend-component-installer": "^2.1.1",
|
||||
"zendframework/zend-config-aggregator": "^1.0",
|
||||
"zendframework/zend-diactoros": "^1.7.1",
|
||||
"zendframework/zend-expressive": "^3.0.1",
|
||||
"zendframework/zend-expressive-fastroute": "^3.0",
|
||||
"zendframework/zend-expressive-helpers": "^5.0",
|
||||
"zendframework/zend-filter": "^2.7",
|
||||
"zendframework/zend-form": "^2.11",
|
||||
"zendframework/zend-hydrator": "^2.3",
|
||||
"zendframework/zend-json": "^3.1",
|
||||
"zendframework/zend-servicemanager": "^3.3",
|
||||
"zendframework/zend-stdlib": "^3.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^7.0.1",
|
||||
"squizlabs/php_codesniffer": "^2.9.1",
|
||||
"zendframework/zend-expressive-tooling": "^1.0",
|
||||
"zfcampus/zf-development-mode": "^3.1",
|
||||
"filp/whoops": "^2.1.12"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"App\\": "src/App/",
|
||||
"DoctrineExpressiveModule\\": "src/DoctrineExpressiveModule/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"AppTest\\": "test/AppTest/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"post-create-project-cmd": [
|
||||
"@development-enable"
|
||||
],
|
||||
"development-disable": "zf-development-mode disable",
|
||||
"development-enable": "zf-development-mode enable",
|
||||
"development-status": "zf-development-mode status",
|
||||
"expressive": "expressive --ansi",
|
||||
"check": [
|
||||
"@cs-check",
|
||||
"@test",
|
||||
"@analyze"
|
||||
],
|
||||
"analyze": "phpstan analyze -l max -c ./phpstan.installer.neon ./src ./config",
|
||||
"clear-config-cache": "php bin/clear-config-cache.php",
|
||||
"cs-check": "phpcs",
|
||||
"cs-fix": "phpcbf",
|
||||
"serve": "php -S 0.0.0.0:8080 -t public/",
|
||||
"test": "phpunit --colors=always",
|
||||
"test-coverage": "phpunit --colors=always --coverage-clover clover.xml"
|
||||
}
|
||||
}
|
||||
4736
composer.lock
generated
Normal file
4736
composer.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
1
config/.gitignore
vendored
Normal file
1
config/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
||||
development.config.php
|
||||
2
config/autoload/.gitignore
vendored
Normal file
2
config/autoload/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
local.php
|
||||
*.local.php
|
||||
26
config/autoload/dependencies.global.php
Normal file
26
config/autoload/dependencies.global.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
// Provides application-wide services.
|
||||
// We recommend using fully-qualified class names whenever possible as
|
||||
// service names.
|
||||
'dependencies' => [
|
||||
// Use 'aliases' to alias a service name to another service. The
|
||||
// key is the alias name, the value is the service to which it points.
|
||||
'aliases' => [
|
||||
// Fully\Qualified\ClassOrInterfaceName::class => Fully\Qualified\ClassName::class,
|
||||
],
|
||||
// Use 'invokables' for constructor-less services, or services that do
|
||||
// not require arguments to the constructor. Map a service name to the
|
||||
// class name.
|
||||
'invokables' => [
|
||||
// Fully\Qualified\InterfaceName::class => Fully\Qualified\ClassName::class,
|
||||
],
|
||||
// Use 'factories' for services provided by callbacks/factory classes.
|
||||
'factories' => [
|
||||
// Fully\Qualified\ClassName::class => Fully\Qualified\FactoryName::class,
|
||||
],
|
||||
],
|
||||
];
|
||||
35
config/autoload/development.local.php.dist
Normal file
35
config/autoload/development.local.php.dist
Normal file
@ -0,0 +1,35 @@
|
||||
<?php
|
||||
/**
|
||||
* Development-only configuration.
|
||||
*
|
||||
* Put settings you want enabled when under development mode in this file, and
|
||||
* check it into your repository.
|
||||
*
|
||||
* Developers on your team will then automatically enable them by calling on
|
||||
* `composer development-enable`.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Zend\Expressive\Container;
|
||||
use Zend\Expressive\Middleware\ErrorResponseGenerator;
|
||||
|
||||
return [
|
||||
'dependencies' => [
|
||||
'invokables' => [
|
||||
],
|
||||
'factories' => [
|
||||
ErrorResponseGenerator::class => Container\WhoopsErrorResponseGeneratorFactory::class,
|
||||
'Zend\Expressive\Whoops' => Container\WhoopsFactory::class,
|
||||
'Zend\Expressive\WhoopsPageHandler' => Container\WhoopsPageHandlerFactory::class,
|
||||
],
|
||||
],
|
||||
|
||||
'whoops' => [
|
||||
'json_exceptions' => [
|
||||
'display' => true,
|
||||
'show_trace' => true,
|
||||
'ajax_only' => true,
|
||||
],
|
||||
],
|
||||
];
|
||||
76
config/autoload/doctrine.global.php
Normal file
76
config/autoload/doctrine.global.php
Normal file
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'dependencies' => [
|
||||
'aliases' => [
|
||||
Doctrine\ORM\EntityManager::class => 'doctrine.entity_manager.orm_default',
|
||||
],
|
||||
'factories' => [
|
||||
'doctrine.entity_manager.orm_default' => ContainerInteropDoctrine\EntityManagerFactory::class,
|
||||
],
|
||||
],
|
||||
'doctrine' => [
|
||||
'driver' => [
|
||||
'orm_default' => [
|
||||
'class' => Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain::class,
|
||||
'drivers' => [
|
||||
'App\Entity' => 'app_entity',
|
||||
],
|
||||
],
|
||||
'app_entity' => [
|
||||
'class' => Doctrine\ORM\Mapping\Driver\AnnotationDriver::class,
|
||||
'cache' => 'array',
|
||||
'paths' => __DIR__ . '/../../src/App/Entity',
|
||||
],
|
||||
],
|
||||
'configuration' => [
|
||||
'orm_default' => [
|
||||
// 'datetime_functions' => [
|
||||
// 'date' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'time' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'timestamp' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'convert_tz' => Oro\ORM\Query\AST\Functions\DateTime\ConvertTz::class,
|
||||
// ],
|
||||
'numeric_functions' => [
|
||||
// 'timestampdiff' => Oro\ORM\Query\AST\Functions\Numeric\TimestampDiff::class,
|
||||
// 'dayofyear' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'dayofmonth' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'dayofweek' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'week' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'day' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'hour' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'minute' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'month' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'quarter' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'second' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'year' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'sign' => Oro\ORM\Query\AST\Functions\Numeric\Sign::class,
|
||||
// 'pow' => Oro\ORM\Query\AST\Functions\Numeric\Pow::class,
|
||||
],
|
||||
// 'string_functions' => [
|
||||
// 'md5' => Oro\ORM\Query\AST\Functions\SimpleFunction::class,
|
||||
// 'group_concat' => Oro\ORM\Query\AST\Functions\String\GroupConcat::class,
|
||||
// 'cast' => Oro\ORM\Query\AST\Functions\Cast::class,
|
||||
// 'concat_ws' => Oro\ORM\Query\AST\Functions\String\ConcatWs::class
|
||||
// ]
|
||||
// 'filters' => [
|
||||
// 'soft-deleteable' => Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter::class,
|
||||
// ],
|
||||
],
|
||||
],
|
||||
'event_manager' => [
|
||||
'orm_default' => [
|
||||
'subscribers' => [
|
||||
Gedmo\Timestampable\TimestampableListener::class,
|
||||
// 'Gedmo\Tree\TreeListener',
|
||||
// 'Gedmo\SoftDeleteable\SoftDeleteableListener',
|
||||
// 'Gedmo\Translatable\TranslatableListener',
|
||||
// 'Gedmo\Blameable\BlameableListener',
|
||||
// 'Gedmo\Loggable\LoggableListener',
|
||||
// 'Gedmo\Sortable\SortableListener',
|
||||
// 'Gedmo\Sluggable\SluggableListener',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
14
config/autoload/doctrine.local.dist.php
Normal file
14
config/autoload/doctrine.local.dist.php
Normal file
@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'doctrine' => [
|
||||
'connection' => [
|
||||
'orm_default' => [
|
||||
'params' => [
|
||||
'url' => 'mysqli://user:passwd@host/database',
|
||||
'charset' => 'UTF8',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
12
config/autoload/local.php.dist
Normal file
12
config/autoload/local.php.dist
Normal file
@ -0,0 +1,12 @@
|
||||
<?php
|
||||
/**
|
||||
* Local configuration.
|
||||
*
|
||||
* Copy this file to `local.php` and change its settings as required.
|
||||
* `local.php` is ignored by git and safe to use for local and sensitive data like usernames and passwords.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
return [
|
||||
];
|
||||
25
config/autoload/zend-expressive.global.php
Normal file
25
config/autoload/zend-expressive.global.php
Normal file
@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Zend\ConfigAggregator\ConfigAggregator;
|
||||
|
||||
return [
|
||||
// Toggle the configuration cache. Set this to boolean false, or remove the
|
||||
// directive, to disable configuration caching. Toggling development mode
|
||||
// will also disable it by default; clear the configuration cache using
|
||||
// `composer clear-config-cache`.
|
||||
ConfigAggregator::ENABLE_CACHE => true,
|
||||
|
||||
// Enable debugging; typically used to provide debugging information within templates.
|
||||
'debug' => false,
|
||||
|
||||
'zend-expressive' => [
|
||||
// Provide templates for the error handling middleware to use when
|
||||
// generating responses.
|
||||
'error_handler' => [
|
||||
'template_404' => 'error::404',
|
||||
'template_error' => 'error::error',
|
||||
],
|
||||
],
|
||||
];
|
||||
46
config/config.php
Normal file
46
config/config.php
Normal file
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Zend\ConfigAggregator\ArrayProvider;
|
||||
use Zend\ConfigAggregator\ConfigAggregator;
|
||||
use Zend\ConfigAggregator\PhpFileProvider;
|
||||
|
||||
// To enable or disable caching, set the `ConfigAggregator::ENABLE_CACHE` boolean in
|
||||
// `config/autoload/local.php`.
|
||||
$cacheConfig = [
|
||||
'config_cache_path' => 'data/cache/config-cache.php',
|
||||
];
|
||||
|
||||
$aggregator = new ConfigAggregator([
|
||||
\Zend\Form\ConfigProvider::class,
|
||||
\Zend\InputFilter\ConfigProvider::class,
|
||||
\Zend\Validator\ConfigProvider::class,
|
||||
\Zend\Hydrator\ConfigProvider::class,
|
||||
\Zend\Filter\ConfigProvider::class,
|
||||
\Zend\Expressive\Router\FastRouteRouter\ConfigProvider::class,
|
||||
\Zend\HttpHandlerRunner\ConfigProvider::class,
|
||||
// Include cache configuration
|
||||
new ArrayProvider($cacheConfig),
|
||||
|
||||
\Zend\Expressive\Helper\ConfigProvider::class,
|
||||
\Zend\Expressive\ConfigProvider::class,
|
||||
\Zend\Expressive\Router\ConfigProvider::class,
|
||||
|
||||
// Default App module config
|
||||
App\ConfigProvider::class,
|
||||
DoctrineExpressiveModule\ConfigProvider::class,
|
||||
|
||||
// Load application config in a pre-defined order in such a way that local settings
|
||||
// overwrite global settings. (Loaded as first to last):
|
||||
// - `global.php`
|
||||
// - `*.global.php`
|
||||
// - `local.php`
|
||||
// - `*.local.php`
|
||||
new PhpFileProvider(realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php'),
|
||||
|
||||
// Load development config if it exists
|
||||
new PhpFileProvider(realpath(__DIR__) . '/development.config.php'),
|
||||
], $cacheConfig['config_cache_path']);
|
||||
|
||||
return $aggregator->getMergedConfig();
|
||||
14
config/container.php
Normal file
14
config/container.php
Normal file
@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Zend\ServiceManager\ServiceManager;
|
||||
|
||||
// Load configuration
|
||||
$config = require __DIR__ . '/config.php';
|
||||
|
||||
$dependencies = $config['dependencies'];
|
||||
$dependencies['services']['config'] = $config;
|
||||
|
||||
// Build container
|
||||
return new ServiceManager($dependencies);
|
||||
30
config/development.config.php.dist
Normal file
30
config/development.config.php.dist
Normal file
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
/**
|
||||
* File required to allow enablement of development mode.
|
||||
*
|
||||
* For use with the zf-development-mode tool.
|
||||
*
|
||||
* Usage:
|
||||
* $ composer development-disable
|
||||
* $ composer development-enable
|
||||
* $ composer development-status
|
||||
*
|
||||
* DO NOT MODIFY THIS FILE.
|
||||
*
|
||||
* Provide your own development-mode settings by editing the file
|
||||
* `config/autoload/development.local.php.dist`.
|
||||
*
|
||||
* Because this file is aggregated last, it simply ensures:
|
||||
*
|
||||
* - The `debug` flag is _enabled_.
|
||||
* - Configuration caching is _disabled_.
|
||||
*/
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Zend\ConfigAggregator\ConfigAggregator;
|
||||
|
||||
return [
|
||||
'debug' => true,
|
||||
ConfigAggregator::ENABLE_CACHE => false,
|
||||
];
|
||||
78
config/pipeline.php
Normal file
78
config/pipeline.php
Normal file
@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Tuupola\Middleware\CorsMiddleware;
|
||||
use Zend\Expressive\Application;
|
||||
use Zend\Expressive\Handler\NotFoundHandler;
|
||||
use Zend\Expressive\Helper\ServerUrlMiddleware;
|
||||
use Zend\Expressive\Helper\UrlHelperMiddleware;
|
||||
use Zend\Expressive\MiddlewareFactory;
|
||||
use Zend\Expressive\Router\Middleware\DispatchMiddleware;
|
||||
use Zend\Expressive\Router\Middleware\ImplicitHeadMiddleware;
|
||||
use Zend\Expressive\Router\Middleware\ImplicitOptionsMiddleware;
|
||||
use Zend\Expressive\Router\Middleware\MethodNotAllowedMiddleware;
|
||||
use Zend\Expressive\Router\Middleware\RouteMiddleware;
|
||||
use Zend\Stratigility\Middleware\ErrorHandler;
|
||||
|
||||
/**
|
||||
* Setup middleware pipeline:
|
||||
*/
|
||||
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
|
||||
// The error handler should be the first (most outer) middleware to catch
|
||||
// all Exceptions.
|
||||
$app->pipe(ErrorHandler::class);
|
||||
$app->pipe(ServerUrlMiddleware::class);
|
||||
|
||||
// Pipe more middleware here that you want to execute on every request:
|
||||
// - bootstrapping
|
||||
// - pre-conditions
|
||||
// - modifications to outgoing responses
|
||||
//
|
||||
// Piped Middleware may be either callables or service names. Middleware may
|
||||
// also be passed as an array; each item in the array must resolve to
|
||||
// middleware eventually (i.e., callable or service name).
|
||||
//
|
||||
// Middleware can be attached to specific paths, allowing you to mix and match
|
||||
// applications under a common domain. The handlers in each middleware
|
||||
// attached this way will see a URI with the matched path segment removed.
|
||||
//
|
||||
// i.e., path of "/api/member/profile" only passes "/member/profile" to $apiMiddleware
|
||||
// - $app->pipe('/api', $apiMiddleware);
|
||||
// - $app->pipe('/docs', $apiDocMiddleware);
|
||||
// - $app->pipe('/files', $filesMiddleware);
|
||||
|
||||
// Register the routing middleware in the middleware pipeline.
|
||||
// This middleware registers the Zend\Expressive\Router\RouteResult request attribute.
|
||||
$app->pipe(RouteMiddleware::class);
|
||||
|
||||
// The following handle routing failures for common conditions:
|
||||
// - HEAD request but no routes answer that method
|
||||
// - OPTIONS request but no routes answer that method
|
||||
// - method not allowed
|
||||
// Order here matters; the MethodNotAllowedMiddleware should be placed
|
||||
// after the Implicit*Middleware.
|
||||
$app->pipe(ImplicitHeadMiddleware::class);
|
||||
// $app->pipe(ImplicitOptionsMiddleware::class);
|
||||
$app->pipe(CorsMiddleware::class);
|
||||
$app->pipe(MethodNotAllowedMiddleware::class);
|
||||
|
||||
// Seed the UrlHelper with the routing results:
|
||||
$app->pipe(UrlHelperMiddleware::class);
|
||||
|
||||
// Add more middleware here that needs to introspect the routing results; this
|
||||
// might include:
|
||||
//
|
||||
// - route-based authentication
|
||||
// - route-based validation
|
||||
// - etc.
|
||||
|
||||
// Register the dispatch middleware in the middleware pipeline
|
||||
$app->pipe(DispatchMiddleware::class);
|
||||
|
||||
// At this point, if no Response is returned by any middleware, the
|
||||
// NotFoundHandler kicks in; alternately, you can provide other fallback
|
||||
// middleware to execute.
|
||||
$app->pipe(NotFoundHandler::class);
|
||||
};
|
||||
41
config/routes.php
Normal file
41
config/routes.php
Normal file
@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Zend\Expressive\Application;
|
||||
use Zend\Expressive\MiddlewareFactory;
|
||||
|
||||
/**
|
||||
* Setup routes with a single request method:
|
||||
*
|
||||
* $app->get('/', App\Handler\HomePageHandler::class, 'home');
|
||||
* $app->post('/album', App\Handler\AlbumCreateHandler::class, 'album.create');
|
||||
* $app->put('/album/:id', App\Handler\AlbumUpdateHandler::class, 'album.put');
|
||||
* $app->patch('/album/:id', App\Handler\AlbumUpdateHandler::class, 'album.patch');
|
||||
* $app->delete('/album/:id', App\Handler\AlbumDeleteHandler::class, 'album.delete');
|
||||
*
|
||||
* Or with multiple request methods:
|
||||
*
|
||||
* $app->route('/contact', App\Handler\ContactHandler::class, ['GET', 'POST', ...], 'contact');
|
||||
*
|
||||
* Or handling all request methods:
|
||||
*
|
||||
* $app->route('/contact', App\Handler\ContactHandler::class)->setName('contact');
|
||||
*
|
||||
* or:
|
||||
*
|
||||
* $app->route(
|
||||
* '/contact',
|
||||
* App\Handler\ContactHandler::class,
|
||||
* Zend\Expressive\Router\Route::HTTP_METHOD_ANY,
|
||||
* 'contact'
|
||||
* );
|
||||
*/
|
||||
return function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {
|
||||
$app->get('/', App\Handler\HomePageHandler::class, 'home');
|
||||
$app->get('/api/ping', App\Handler\PingHandler::class, 'api.ping');
|
||||
|
||||
$app->route('/api/team[/{id:\d+}]', App\Handler\TeamHandler::class)->setName('api.team');
|
||||
$app->route('/api/slide[/{id:\d+}]', App\Handler\SlideHandler::class)->setName('api.slide');
|
||||
};
|
||||
4
data/.gitignore
vendored
Normal file
4
data/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
*
|
||||
!cache
|
||||
!cache/.gitkeep
|
||||
!.gitignore
|
||||
0
data/cache/.gitkeep
vendored
Normal file
0
data/cache/.gitkeep
vendored
Normal file
20
phpcs.xml.dist
Normal file
20
phpcs.xml.dist
Normal file
@ -0,0 +1,20 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="Expressive Skeleton coding standard">
|
||||
<description>Expressive Skeleton coding standard</description>
|
||||
|
||||
<!-- display progress -->
|
||||
<arg value="p"/>
|
||||
<arg name="colors"/>
|
||||
|
||||
<!-- inherit rules from: -->
|
||||
<rule ref="PSR2"/>
|
||||
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/>
|
||||
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace">
|
||||
<properties>
|
||||
<property name="ignoreBlankLines" value="false"/>
|
||||
</properties>
|
||||
</rule>
|
||||
|
||||
<!-- Paths to check -->
|
||||
<file>src</file>
|
||||
</ruleset>
|
||||
17
phpunit.xml.dist
Normal file
17
phpunit.xml.dist
Normal file
@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true">
|
||||
<testsuites>
|
||||
<testsuite name="App\\Tests">
|
||||
<directory>./test</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
|
||||
<filter>
|
||||
<whitelist processUncoveredFilesFromWhitelist="true">
|
||||
<directory suffix=".php">./src</directory>
|
||||
</whitelist>
|
||||
</filter>
|
||||
</phpunit>
|
||||
19
public/.htaccess
Normal file
19
public/.htaccess
Normal file
@ -0,0 +1,19 @@
|
||||
RewriteEngine On
|
||||
# The following rule allows authentication to work with fast-cgi
|
||||
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
|
||||
# The following rule tells Apache that if the requested filename
|
||||
# exists, simply serve it.
|
||||
RewriteCond %{REQUEST_FILENAME} -s [OR]
|
||||
RewriteCond %{REQUEST_FILENAME} -l [OR]
|
||||
RewriteCond %{REQUEST_FILENAME} -d
|
||||
RewriteRule ^.*$ - [NC,L]
|
||||
|
||||
# The following rewrites all other queries to index.php. The
|
||||
# condition ensures that if you are using Apache aliases to do
|
||||
# mass virtual hosting, the base path will be prepended to
|
||||
# allow proper resolution of the index.php file; it will work
|
||||
# in non-aliased environments as well, providing a safe, one-size
|
||||
# fits all solution.
|
||||
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
|
||||
RewriteRule ^(.*) - [E=BASE:%1]
|
||||
RewriteRule ^(.*)$ %{ENV:BASE}index.php [NC,L]
|
||||
30
public/index.php
Normal file
30
public/index.php
Normal file
@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Delegate static file requests back to the PHP built-in webserver
|
||||
if (PHP_SAPI === 'cli-server' && $_SERVER['SCRIPT_FILENAME'] !== __FILE__) {
|
||||
return false;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
require 'vendor/autoload.php';
|
||||
|
||||
/**
|
||||
* Self-called anonymous function that creates its own scope and keep the global namespace clean.
|
||||
*/
|
||||
(function () {
|
||||
/** @var \Psr\Container\ContainerInterface $container */
|
||||
$container = require 'config/container.php';
|
||||
|
||||
/** @var \Zend\Expressive\Application $app */
|
||||
$app = $container->get(\Zend\Expressive\Application::class);
|
||||
$factory = $container->get(\Zend\Expressive\MiddlewareFactory::class);
|
||||
|
||||
// Execute programmatic/declarative middleware pipeline and routing
|
||||
// configuration statements
|
||||
(require 'config/pipeline.php')($app, $factory, $container);
|
||||
(require 'config/routes.php')($app, $factory, $container);
|
||||
|
||||
$app->run();
|
||||
})();
|
||||
61
src/App/ConfigProvider.php
Normal file
61
src/App/ConfigProvider.php
Normal file
@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
/**
|
||||
* The configuration provider for the App module
|
||||
*
|
||||
* @see https://docs.zendframework.com/zend-component-installer/
|
||||
*/
|
||||
class ConfigProvider
|
||||
{
|
||||
/**
|
||||
* Returns the configuration array
|
||||
*
|
||||
* To add a bit of a structure, each section is defined in a separate
|
||||
* method which returns an array with its configuration.
|
||||
*
|
||||
*/
|
||||
public function __invoke() : array
|
||||
{
|
||||
return [
|
||||
'dependencies' => $this->getDependencies(),
|
||||
'templates' => $this->getTemplates(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container dependencies
|
||||
*/
|
||||
public function getDependencies() : array
|
||||
{
|
||||
return [
|
||||
'invokables' => [
|
||||
Handler\PingHandler::class => Handler\PingHandler::class,
|
||||
],
|
||||
'factories' => [
|
||||
Handler\HomePageHandler::class => Handler\HomePageHandlerFactory::class,
|
||||
Handler\TeamHandler::class => Handler\TeamHandlerFactory::class,
|
||||
|
||||
Service\TeamService::class => Service\TeamServiceFactory::class,
|
||||
Service\SlideManager::class => Service\SlideManagerFactory::class,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the templates configuration
|
||||
*/
|
||||
public function getTemplates() : array
|
||||
{
|
||||
return [
|
||||
'paths' => [
|
||||
'app' => ['templates/app'],
|
||||
'error' => ['templates/error'],
|
||||
'layout' => ['templates/layout'],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
209
src/App/Entity/Slide.php
Normal file
209
src/App/Entity/Slide.php
Normal file
@ -0,0 +1,209 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Mapping\Annotation as Gedmo;
|
||||
use JsonSerializable;
|
||||
|
||||
/**
|
||||
* @ORM\Entity
|
||||
* @ORM\Table(name="slides")
|
||||
*/
|
||||
class Slide implements JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @ORM\Id
|
||||
* @ORM\GeneratedValue(strategy="IDENTITY")
|
||||
* @ORM\Column(name="id", type="integer")
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="title", type="string", length=200, unique=true)
|
||||
* @var string
|
||||
*/
|
||||
private $title;
|
||||
|
||||
/**
|
||||
* @ORM\ManyToOne(targetEntity="Team", inversedBy="slides")
|
||||
* @ORM\JoinColumn(name="team_id", referencedColumnName="id")
|
||||
* @var Team
|
||||
*/
|
||||
private $team;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="slide_data", type="text")
|
||||
* @var string
|
||||
*/
|
||||
private $slideData;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="is_visible", type="boolean")
|
||||
* @var bool
|
||||
*/
|
||||
private $isVisible;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="created_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="create")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $createdAt;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="updated_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="update")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $updatedAt;
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Slide
|
||||
*/
|
||||
public function setId(int $id): Slide
|
||||
{
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getTitle(): ?string
|
||||
{
|
||||
return $this->title;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $title
|
||||
* @return Slide
|
||||
*/
|
||||
public function setTitle(string $title)
|
||||
{
|
||||
$this->title = $title;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Team
|
||||
*/
|
||||
public function getTeam(): ?Team
|
||||
{
|
||||
return $this->team;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Team $team
|
||||
* @return Slide
|
||||
*/
|
||||
public function setTeam(Team $team): Slide
|
||||
{
|
||||
$this->team = $team;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getSlideData(): ?string
|
||||
{
|
||||
return $this->slideData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $slideData
|
||||
* @return Slide
|
||||
*/
|
||||
public function setSlideData(string $slideData): Slide
|
||||
{
|
||||
$this->slideData = $slideData;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isVisible(): ?bool
|
||||
{
|
||||
return $this->isVisible;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isVisible
|
||||
* @return Slide
|
||||
*/
|
||||
public function setIsVisible(bool $isVisible): Slide
|
||||
{
|
||||
$this->isVisible = $isVisible;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getCreatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $createdAt
|
||||
* @return Slide
|
||||
*/
|
||||
public function setCreatedAt(\DateTimeImmutable $createdAt): Slide
|
||||
{
|
||||
$this->createdAt = $createdAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getUpdatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->updatedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $updatedAt
|
||||
* @return Slide
|
||||
*/
|
||||
public function setUpdatedAt(\DateTimeImmutable $updatedAt): Slide
|
||||
{
|
||||
$this->updatedAt = $updatedAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function jsonSerialize()
|
||||
{
|
||||
return [
|
||||
'id' => $this->getId(),
|
||||
'title' => $this->getTitle(),
|
||||
'team' => $this->getTeam(),
|
||||
'slideData' => $this->getSlideData(),
|
||||
'isVisible' => $this->isVisible(),
|
||||
'createdAt' => $this->getCreatedAt()
|
||||
? $this->getCreatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
'updatedAt' => $this->getUpdatedAt()
|
||||
? $this->getUpdatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
];
|
||||
}
|
||||
}
|
||||
234
src/App/Entity/Team.php
Normal file
234
src/App/Entity/Team.php
Normal file
@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Mapping\Annotation as Gedmo;
|
||||
use JsonSerializable;
|
||||
|
||||
/**
|
||||
* @ORM\Entity
|
||||
* @ORM\Table(name="teams")
|
||||
*/
|
||||
class Team implements JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @ORM\Id
|
||||
* @ORM\GeneratedValue(strategy="IDENTITY")
|
||||
* @ORM\Column(name="id", type="integer")
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="name", type="string", length=200, unique=true)
|
||||
* @var string
|
||||
*/
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="members", type="json")
|
||||
* @var array
|
||||
*/
|
||||
private $members;
|
||||
|
||||
/**
|
||||
* @ORM\OneToMany(
|
||||
* targetEntity="Slide",
|
||||
* mappedBy="team",
|
||||
* cascade={"persist", "remove"},
|
||||
* orphanRemoval=true
|
||||
* )
|
||||
* @var Slide[]|Collection
|
||||
*/
|
||||
private $slides;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="is_active", type="boolean")
|
||||
* @var bool
|
||||
*/
|
||||
private $isActive;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="created_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="create")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $createdAt;
|
||||
|
||||
/**
|
||||
* @ORM\Column(name="updated_at", type="datetime_immutable", nullable=true)
|
||||
* @Gedmo\Timestampable(on="update")
|
||||
* @var \DateTimeImmutable
|
||||
*/
|
||||
private $updatedAt;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->slides = new ArrayCollection;
|
||||
$this->members = new \ArrayObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Team
|
||||
*/
|
||||
public function setId(int $id): Team
|
||||
{
|
||||
$this->id = $id;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getName(): ?string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $name
|
||||
* @return Team
|
||||
*/
|
||||
public function setName(string $name): Team
|
||||
{
|
||||
$this->name = $name;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getMembers()
|
||||
{
|
||||
return $this->members;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $members
|
||||
* @return Team
|
||||
*/
|
||||
public function setMembers(array $members): Team
|
||||
{
|
||||
$this->members = $members;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Slide $slide
|
||||
* @return Team
|
||||
*/
|
||||
public function addSlides(Slide $slide): Team
|
||||
{
|
||||
if (!$this->slides->contains($slide)) {
|
||||
$this->slides->removeElement($slide);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Slide[]|Collection
|
||||
*/
|
||||
public function getSlides(): ?Collection
|
||||
{
|
||||
return $this->slides;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Slide $slide
|
||||
* @return Team
|
||||
*/
|
||||
public function removeSlide(Slide $slide): Team
|
||||
{
|
||||
if ($this->slides->contains($slide)) {
|
||||
$this->slides->removeElement($slide);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function isActive(): ?bool
|
||||
{
|
||||
return $this->isActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param bool $isActive
|
||||
* @return Team
|
||||
*/
|
||||
public function setIsActive(bool $isActive): Team
|
||||
{
|
||||
$this->isActive = $isActive;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getCreatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $createdAt
|
||||
* @return Team
|
||||
*/
|
||||
public function setCreatedAt(\DateTimeImmutable $createdAt): Team
|
||||
{
|
||||
$this->createdAt = $createdAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \DateTimeImmutable
|
||||
*/
|
||||
public function getUpdatedAt(): ?\DateTimeImmutable
|
||||
{
|
||||
return $this->updatedAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \DateTimeImmutable $updatedAt
|
||||
* @return Team
|
||||
*/
|
||||
public function setUpdatedAt(\DateTimeImmutable $updatedAt): Team
|
||||
{
|
||||
$this->updatedAt = $updatedAt;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function jsonSerialize()
|
||||
{
|
||||
return [
|
||||
'id' => $this->getId(),
|
||||
'name' => $this->getName(),
|
||||
'members' => $this->getMembers(),
|
||||
'isActive' => $this->isActive(),
|
||||
'createdAt' => $this->getCreatedAt()
|
||||
? $this->getCreatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
'updatedAt' => $this->getUpdatedAt()
|
||||
? $this->getUpdatedAt()->format("Y-m-d H:i:s")
|
||||
: null,
|
||||
];
|
||||
}
|
||||
}
|
||||
73
src/App/Form/Slide.php
Normal file
73
src/App/Form/Slide.php
Normal file
@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use Zend\Form\Annotation;
|
||||
|
||||
/**
|
||||
* @Annotation\Name("slide")
|
||||
* @Annotation\Hydrator("doctrine.hydrator")
|
||||
*/
|
||||
class Slide
|
||||
{
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Hidden")
|
||||
* @Annotation\Required(false)
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\InputFilter("Zend\Filter\StringTrim")
|
||||
* @Annotation\Options({
|
||||
* "label": "Slide title"
|
||||
* })
|
||||
* @var string
|
||||
*/
|
||||
private $title;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\Options({
|
||||
* "label": "Team",
|
||||
* "target_class": "App\Entity\Team",
|
||||
* "display_empty_item": false,
|
||||
* "empty_item_label": "",
|
||||
* "is_method": true,
|
||||
* "find_method": {
|
||||
* "name": "findBy",
|
||||
* "params": {
|
||||
* "criteria": {"isActive": true},
|
||||
* "orderBy": {"name": "ASC"}
|
||||
* }
|
||||
* }
|
||||
* })
|
||||
* @var
|
||||
*/
|
||||
private $team;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\InputFilter("Zend\Filter\StringTrim")
|
||||
* @Annotation\Options({
|
||||
* "label": "Slide contents"
|
||||
* })
|
||||
* @var
|
||||
*/
|
||||
private $slideData;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Checkbox")
|
||||
* @Annotation\Options({
|
||||
* "label": "Visible"
|
||||
* })
|
||||
* @var bool
|
||||
*/
|
||||
private $isVisible;
|
||||
}
|
||||
52
src/App/Form/Team.php
Normal file
52
src/App/Form/Team.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use Zend\Form\Annotation;
|
||||
|
||||
/**
|
||||
* @Annotation\Name("team")
|
||||
* @Annotation\Hydrator("doctrine.hydrator")
|
||||
*/
|
||||
class Team
|
||||
{
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Hidden")
|
||||
* @Annotation\Required(false)
|
||||
* @var int
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\InputFilter("Zend\Filter\StringTrim")
|
||||
* @Annotation\Options({
|
||||
* "label": "Team name"
|
||||
* })
|
||||
* @var string
|
||||
*/
|
||||
private $name;
|
||||
|
||||
/**
|
||||
* This is a dummy field, not a text actually. Only used to filter the input
|
||||
* @Annotation\Type("Zend\Form\Element\Text")
|
||||
* @Annotation\Required(true)
|
||||
* @Annotation\Options({
|
||||
* "label": "Members"
|
||||
* })
|
||||
* @var array
|
||||
*/
|
||||
private $members;
|
||||
|
||||
/**
|
||||
* @Annotation\Type("Zend\Form\Element\Checkbox")
|
||||
* @Annotation\Options({
|
||||
* "label": "Active"
|
||||
* })
|
||||
* @var bool
|
||||
*/
|
||||
private $isActive;
|
||||
}
|
||||
161
src/App/Handler/AbstractCrudHandler.php
Normal file
161
src/App/Handler/AbstractCrudHandler.php
Normal file
@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Diactoros\Response\EmptyResponse;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
use Zend\Json\Json;
|
||||
|
||||
abstract class AbstractCrudHandler implements RequestHandlerInterface
|
||||
{
|
||||
const IDENTIFIER_NAME = 'id';
|
||||
|
||||
public function handle(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$requestMethod = strtoupper($request->getMethod());
|
||||
$id = $request->getAttribute(static::IDENTIFIER_NAME);
|
||||
|
||||
switch ($requestMethod) {
|
||||
case 'GET':
|
||||
return isset($id)
|
||||
? $this->get($request)
|
||||
: $this->getList($request);
|
||||
case 'POST':
|
||||
return $this->create($request);
|
||||
case 'PUT':
|
||||
return $this->update($request);
|
||||
case 'DELETE':
|
||||
return isset($id)
|
||||
? $this->delete($request)
|
||||
: $this->deleteList($request);
|
||||
case 'HEAD':
|
||||
return $this->head($request);
|
||||
case 'OPTIONS':
|
||||
return $this->options($request);
|
||||
case 'PATCH':
|
||||
return $this->patch($request);
|
||||
default:
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
}
|
||||
|
||||
public function get(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function getList(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function create(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function update(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function delete(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function deleteList(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function head(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
public function options(ServerRequestInterface $request)
|
||||
{
|
||||
return new EmptyResponse(200);
|
||||
}
|
||||
|
||||
public function patch(ServerRequestInterface $request)
|
||||
{
|
||||
return $this->createResponse(['content' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
final protected function createResponse($data, $status = 200)
|
||||
{
|
||||
return new JsonResponse($data, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param ServerRequestInterface $request
|
||||
* @return array|object
|
||||
*/
|
||||
public function getRequestData(ServerRequestInterface $request)
|
||||
{
|
||||
$body = $request->getParsedBody();
|
||||
|
||||
if (!empty($body)) {
|
||||
return $body;
|
||||
}
|
||||
|
||||
return $this->parseRequestData(
|
||||
$request->getBody()->getContents(),
|
||||
$request->getHeaderLine('content-type')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $input
|
||||
* @param string $contentType
|
||||
* @return mixed
|
||||
*/
|
||||
private function parseRequestData($input, $contentType)
|
||||
{
|
||||
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
|
||||
$parser = $this->returnParserContentType($contentTypeParts[0]);
|
||||
|
||||
return $parser($input);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param string $contentType
|
||||
* @return callable
|
||||
*/
|
||||
private function returnParserContentType(string $contentType): callable
|
||||
{
|
||||
if ($contentType === 'application/x-www-form-urlencoded') {
|
||||
return function ($input) {
|
||||
parse_str($input, $data);
|
||||
return $data;
|
||||
};
|
||||
} elseif ($contentType === 'application/json') {
|
||||
return function ($input) {
|
||||
$jsonDecoder = new Json();
|
||||
try {
|
||||
return $jsonDecoder->decode($input, Json::TYPE_ARRAY);
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
} elseif ($contentType === 'multipart/form-data') {
|
||||
return function ($input) {
|
||||
return $input;
|
||||
};
|
||||
}
|
||||
|
||||
return function ($input) {
|
||||
return $input;
|
||||
};
|
||||
}
|
||||
}
|
||||
94
src/App/Handler/HomePageHandler.php
Normal file
94
src/App/Handler/HomePageHandler.php
Normal file
@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Diactoros\Response\HtmlResponse;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
use Zend\Expressive\Plates\PlatesRenderer;
|
||||
use Zend\Expressive\Router;
|
||||
use Zend\Expressive\Template;
|
||||
use Zend\Expressive\Twig\TwigRenderer;
|
||||
use Zend\Expressive\ZendView\ZendViewRenderer;
|
||||
|
||||
class HomePageHandler implements RequestHandlerInterface
|
||||
{
|
||||
private $containerName;
|
||||
|
||||
private $router;
|
||||
|
||||
private $template;
|
||||
|
||||
public function __construct(
|
||||
Router\RouterInterface $router,
|
||||
Template\TemplateRendererInterface $template = null,
|
||||
string $containerName
|
||||
) {
|
||||
$this->router = $router;
|
||||
$this->template = $template;
|
||||
$this->containerName = $containerName;
|
||||
}
|
||||
|
||||
public function handle(ServerRequestInterface $request) : ResponseInterface
|
||||
{
|
||||
if (! $this->template) {
|
||||
return new JsonResponse([
|
||||
'welcome' => 'Congratulations! You have installed the zend-expressive skeleton application.',
|
||||
'docsUrl' => 'https://docs.zendframework.com/zend-expressive/',
|
||||
]);
|
||||
}
|
||||
|
||||
$data = [];
|
||||
|
||||
switch ($this->containerName) {
|
||||
case 'Aura\Di\Container':
|
||||
$data['containerName'] = 'Aura.Di';
|
||||
$data['containerDocs'] = 'http://auraphp.com/packages/2.x/Di.html';
|
||||
break;
|
||||
case 'Pimple\Container':
|
||||
$data['containerName'] = 'Pimple';
|
||||
$data['containerDocs'] = 'https://pimple.symfony.com/';
|
||||
break;
|
||||
case 'Zend\ServiceManager\ServiceManager':
|
||||
$data['containerName'] = 'Zend Servicemanager';
|
||||
$data['containerDocs'] = 'https://docs.zendframework.com/zend-servicemanager/';
|
||||
break;
|
||||
case 'Auryn\Injector':
|
||||
$data['containerName'] = 'Auryn';
|
||||
$data['containerDocs'] = 'https://github.com/rdlowrey/Auryn';
|
||||
break;
|
||||
case 'Symfony\Component\DependencyInjection\ContainerBuilder':
|
||||
$data['containerName'] = 'Symfony DI Container';
|
||||
$data['containerDocs'] = 'https://symfony.com/doc/current/service_container.html';
|
||||
break;
|
||||
}
|
||||
|
||||
if ($this->router instanceof Router\AuraRouter) {
|
||||
$data['routerName'] = 'Aura.Router';
|
||||
$data['routerDocs'] = 'http://auraphp.com/packages/2.x/Router.html';
|
||||
} elseif ($this->router instanceof Router\FastRouteRouter) {
|
||||
$data['routerName'] = 'FastRoute';
|
||||
$data['routerDocs'] = 'https://github.com/nikic/FastRoute';
|
||||
} elseif ($this->router instanceof Router\ZendRouter) {
|
||||
$data['routerName'] = 'Zend Router';
|
||||
$data['routerDocs'] = 'https://docs.zendframework.com/zend-router/';
|
||||
}
|
||||
|
||||
if ($this->template instanceof PlatesRenderer) {
|
||||
$data['templateName'] = 'Plates';
|
||||
$data['templateDocs'] = 'http://platesphp.com/';
|
||||
} elseif ($this->template instanceof TwigRenderer) {
|
||||
$data['templateName'] = 'Twig';
|
||||
$data['templateDocs'] = 'http://twig.sensiolabs.org/documentation';
|
||||
} elseif ($this->template instanceof ZendViewRenderer) {
|
||||
$data['templateName'] = 'Zend View';
|
||||
$data['templateDocs'] = 'https://docs.zendframework.com/zend-view/';
|
||||
}
|
||||
|
||||
return new HtmlResponse($this->template->render('app::home-page', $data));
|
||||
}
|
||||
}
|
||||
23
src/App/Handler/HomePageHandlerFactory.php
Normal file
23
src/App/Handler/HomePageHandlerFactory.php
Normal file
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Expressive\Router\RouterInterface;
|
||||
use Zend\Expressive\Template\TemplateRendererInterface;
|
||||
|
||||
class HomePageHandlerFactory
|
||||
{
|
||||
public function __invoke(ContainerInterface $container) : RequestHandlerInterface
|
||||
{
|
||||
$router = $container->get(RouterInterface::class);
|
||||
$template = $container->has(TemplateRendererInterface::class)
|
||||
? $container->get(TemplateRendererInterface::class)
|
||||
: null;
|
||||
|
||||
return new HomePageHandler($router, $template, get_class($container));
|
||||
}
|
||||
}
|
||||
18
src/App/Handler/PingHandler.php
Normal file
18
src/App/Handler/PingHandler.php
Normal file
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class PingHandler implements RequestHandlerInterface
|
||||
{
|
||||
public function handle(ServerRequestInterface $request) : ResponseInterface
|
||||
{
|
||||
return new JsonResponse(['ack' => time()]);
|
||||
}
|
||||
}
|
||||
73
src/App/Handler/SlideHandler.php
Normal file
73
src/App/Handler/SlideHandler.php
Normal file
@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\SlideManager;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class SlideHandler extends AbstractCrudHandler
|
||||
{
|
||||
/** @var SlideManager */
|
||||
private $slideManager;
|
||||
|
||||
public function __construct(SlideManager $teamService) {
|
||||
$this->slideManager = $teamService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function getList(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
return new JsonResponse($this->slideManager->listSlides());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function get(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->slideManager->getSlide((int)$id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function create(ServerRequestInterface $request)
|
||||
{
|
||||
$data = $this->getRequestData($request);
|
||||
try {
|
||||
return new JsonResponse($this->slideManager->addSlide($data));
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => 'The field `name` must be unique',
|
||||
], 500);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function delete(ServerRequestInterface $request)
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->slideManager->removeSlide($id));
|
||||
}
|
||||
}
|
||||
22
src/App/Handler/SlideHandlerFactory.php
Normal file
22
src/App/Handler/SlideHandlerFactory.php
Normal file
@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\SlideManager;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
class SlideHandlerFactory
|
||||
{
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @return RequestHandlerInterface
|
||||
*/
|
||||
public function __invoke(ContainerInterface $container) : RequestHandlerInterface
|
||||
{
|
||||
$slideManager = $container->get(SlideManager::class);
|
||||
return new SlideHandler($slideManager);
|
||||
}
|
||||
}
|
||||
73
src/App/Handler/TeamHandler.php
Normal file
73
src/App/Handler/TeamHandler.php
Normal file
@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\TeamService;
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class TeamHandler extends AbstractCrudHandler
|
||||
{
|
||||
/** @var TeamService */
|
||||
private $teamService;
|
||||
|
||||
public function __construct(TeamService $teamService) {
|
||||
$this->teamService = $teamService;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function getList(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
return new JsonResponse($this->teamService->listTeams());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return ResponseInterface
|
||||
*/
|
||||
public function get(ServerRequestInterface $request): ResponseInterface
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->teamService->getTeam((int)$id));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function create(ServerRequestInterface $request)
|
||||
{
|
||||
$data = $this->getRequestData($request);
|
||||
try {
|
||||
return new JsonResponse($this->teamService->addTeam($data));
|
||||
} catch (UniqueConstraintViolationException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => 'The field `name` must be unique',
|
||||
], 500);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
return new JsonResponse([
|
||||
'message' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ServerRequestInterface $request
|
||||
* @return JsonResponse
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function delete(ServerRequestInterface $request)
|
||||
{
|
||||
$id = $request->getAttribute('id');
|
||||
return new JsonResponse($this->teamService->removeTeam($id));
|
||||
}
|
||||
}
|
||||
22
src/App/Handler/TeamHandlerFactory.php
Normal file
22
src/App/Handler/TeamHandlerFactory.php
Normal file
@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Handler;
|
||||
|
||||
use App\Service\TeamService;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
class TeamHandlerFactory
|
||||
{
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @return RequestHandlerInterface
|
||||
*/
|
||||
public function __invoke(ContainerInterface $container) : RequestHandlerInterface
|
||||
{
|
||||
$teamService = $container->get(TeamService::class);
|
||||
return new TeamHandler($teamService);
|
||||
}
|
||||
}
|
||||
124
src/App/Service/SlideManager.php
Normal file
124
src/App/Service/SlideManager.php
Normal file
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Slide;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class SlideManager
|
||||
{
|
||||
const ENTITY_NAME = Slide::class;
|
||||
|
||||
/** @var EntityManager */
|
||||
private $em;
|
||||
|
||||
/** @var Form */
|
||||
private $form;
|
||||
|
||||
public function __construct(EntityManager $em, Form $form)
|
||||
{
|
||||
$this->em = $em;
|
||||
$this->form = $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function listSlides(): array
|
||||
{
|
||||
return $this->em->getRepository(self::ENTITY_NAME)->findBy([
|
||||
'isActive' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Slide
|
||||
*/
|
||||
public function getSlide(int $id): Slide
|
||||
{
|
||||
/** @var Slide $entity */
|
||||
$entity = $this->em->getRepository(self::ENTITY_NAME)->find($id);
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Slide
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
* @throws \Doctrine\DBAL\Exception\UniqueConstraintViolationException
|
||||
*/
|
||||
public function addSlide(array $data)
|
||||
{
|
||||
$entity = new Slide();
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->persist($entity);
|
||||
$this->em->flush();
|
||||
return $entity;
|
||||
} else {
|
||||
$messages = $this->form->getMessages();
|
||||
$fields = array_keys($messages);
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"The following fields are invalid: (%s)",
|
||||
implode(", ", $fields)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function changeSlide(int $id, array $data): bool
|
||||
{
|
||||
if (null === ($entity = $this->getSlide($id))) {
|
||||
return false;
|
||||
}
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->flush();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function removeSlide(int $id): bool
|
||||
{
|
||||
if (null !== ($entity = $this->getSlide($id))) {
|
||||
$this->em->remove($entity);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param bool $isVisible
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function setSlideVisible(int $id, bool $isVisible): bool
|
||||
{
|
||||
return $this->changeSlide($id, ['isVisible' => $isVisible]);
|
||||
}
|
||||
}
|
||||
23
src/App/Service/SlideManagerFactory.php
Normal file
23
src/App/Service/SlideManagerFactory.php
Normal file
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Form\Team;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Zend\Form\Annotation\AnnotationBuilder;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class SlideManagerFactory
|
||||
{
|
||||
public function __invoke(ContainerInterface $container) : SlideManager
|
||||
{
|
||||
$em = $container->get(EntityManager::class);
|
||||
$formBuilder = $container->get(AnnotationBuilder::class);
|
||||
/** @var Form $form */
|
||||
$form = $formBuilder->createForm(Team::class);
|
||||
return new SlideManager($em, $form);
|
||||
}
|
||||
}
|
||||
124
src/App/Service/TeamService.php
Normal file
124
src/App/Service/TeamService.php
Normal file
@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Team;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class TeamService
|
||||
{
|
||||
const ENTITY_NAME = Team::class;
|
||||
|
||||
/** @var EntityManager */
|
||||
private $em;
|
||||
|
||||
/** @var Form */
|
||||
private $form;
|
||||
|
||||
public function __construct(EntityManager $em, Form $form)
|
||||
{
|
||||
$this->em = $em;
|
||||
$this->form = $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function listTeams(): array
|
||||
{
|
||||
return $this->em->getRepository(self::ENTITY_NAME)->findBy([
|
||||
'isActive' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return Team
|
||||
*/
|
||||
public function getTeam(int $id): ?Team
|
||||
{
|
||||
/** @var Team $entity */
|
||||
$entity = $this->em->getRepository(self::ENTITY_NAME)->find($id);
|
||||
return $entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $data
|
||||
* @return Team
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
* @throws \Doctrine\DBAL\Exception\UniqueConstraintViolationException
|
||||
*/
|
||||
public function addTeam(array $data): Team
|
||||
{
|
||||
$entity = new Team();
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->persist($entity);
|
||||
$this->em->flush();
|
||||
return $entity;
|
||||
} else {
|
||||
$messages = $this->form->getMessages();
|
||||
$fields = array_keys($messages);
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
"The following fields are invalid: (%s)",
|
||||
implode(", ", $fields)
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param array $data
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function changeTeam(int $id, array $data): bool
|
||||
{
|
||||
if (null === ($entity = $this->getTeam($id))) {
|
||||
return false;
|
||||
}
|
||||
$this->form
|
||||
->bind($entity)
|
||||
->setData($data);
|
||||
|
||||
if ($this->form->isValid()) {
|
||||
$this->em->flush();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
*/
|
||||
public function removeTeam(int $id): bool
|
||||
{
|
||||
if (null !== ($entity = $this->getTeam($id))) {
|
||||
$this->em->remove($entity);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @param bool $isVisible
|
||||
* @return bool
|
||||
* @throws \Doctrine\ORM\ORMException
|
||||
* @throws \Doctrine\ORM\OptimisticLockException
|
||||
*/
|
||||
public function setTeamActive(int $id, bool $isVisible): bool
|
||||
{
|
||||
return $this->changeTeam($id, ['isVisible' => $isVisible]);
|
||||
}
|
||||
}
|
||||
23
src/App/Service/TeamServiceFactory.php
Normal file
23
src/App/Service/TeamServiceFactory.php
Normal file
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Form\Team;
|
||||
use Doctrine\ORM\EntityManager;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Zend\Form\Annotation\AnnotationBuilder;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class TeamServiceFactory
|
||||
{
|
||||
public function __invoke(ContainerInterface $container) : TeamService
|
||||
{
|
||||
$em = $container->get(EntityManager::class);
|
||||
$formBuilder = $container->get(AnnotationBuilder::class);
|
||||
/** @var Form $form */
|
||||
$form = $formBuilder->createForm(Team::class);
|
||||
return new TeamService($em, $form);
|
||||
}
|
||||
}
|
||||
48
src/DoctrineExpressiveModule/ConfigProvider.php
Normal file
48
src/DoctrineExpressiveModule/ConfigProvider.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineExpressiveModule;
|
||||
|
||||
use Zend\EventManager\EventManager;
|
||||
|
||||
/**
|
||||
* The configuration provider for the DoctrineExpressiveModule module
|
||||
*
|
||||
* @see https://docs.zendframework.com/zend-component-installer/
|
||||
*/
|
||||
class ConfigProvider
|
||||
{
|
||||
/**
|
||||
* Returns the configuration array
|
||||
*
|
||||
* To add a bit of a structure, each section is defined in a separate
|
||||
* method which returns an array with its configuration.
|
||||
*
|
||||
*/
|
||||
public function __invoke() : array
|
||||
{
|
||||
return [
|
||||
'dependencies' => $this->getDependencies(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the container dependencies
|
||||
*/
|
||||
public function getDependencies() : array
|
||||
{
|
||||
return [
|
||||
'aliases' => [
|
||||
'doctrine.hydrator' => Hydrator\DoctrineObject::class,
|
||||
'EventManager' => EventManager::class,
|
||||
],
|
||||
'invokables' => [
|
||||
EventManager::class => EventManager::class,
|
||||
],
|
||||
'factories' => [
|
||||
Hydrator\DoctrineObject::class => Hydrator\DoctrineObjectFactory::class,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element\Exception;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
class InvalidRepositoryResultException extends InvalidArgumentException
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\MultiCheckbox;
|
||||
use Zend\Form\Form;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
class ObjectMultiCheckbox extends MultiCheckbox
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
if ($value instanceof \Traversable) {
|
||||
$value = ArrayUtils::iteratorToArray($value);
|
||||
} elseif ($value == null) {
|
||||
return parent::setValue([]);
|
||||
} elseif (! is_array($value)) {
|
||||
$value = (array)$value;
|
||||
}
|
||||
|
||||
return parent::setValue(array_map([$this->getProxy(), 'getValue'], $value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
73
src/DoctrineExpressiveModule/Form/Element/ObjectRadio.php
Normal file
73
src/DoctrineExpressiveModule/Form/Element/ObjectRadio.php
Normal file
@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineExpressiveModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\Radio as RadioElement;
|
||||
use Zend\Form\Form;
|
||||
|
||||
class ObjectRadio extends RadioElement
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
return parent::setValue($this->getProxy()->getValue($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
88
src/DoctrineExpressiveModule/Form/Element/ObjectSelect.php
Normal file
88
src/DoctrineExpressiveModule/Form/Element/ObjectSelect.php
Normal file
@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use DoctrineExpressiveModule\Form\Element\Proxy;
|
||||
use Zend\Form\Element\Select as SelectElement;
|
||||
use Zend\Form\Form;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
class ObjectSelect extends SelectElement
|
||||
{
|
||||
/**
|
||||
* @var Proxy
|
||||
*/
|
||||
protected $proxy;
|
||||
|
||||
/**
|
||||
* @return Proxy
|
||||
*/
|
||||
public function getProxy()
|
||||
{
|
||||
if (null === $this->proxy) {
|
||||
$this->proxy = new Proxy();
|
||||
}
|
||||
return $this->proxy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|\Traversable $options
|
||||
* @return self
|
||||
*/
|
||||
public function setOptions($options)
|
||||
{
|
||||
$this->getProxy()->setOptions($options);
|
||||
return parent::setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param mixed $value
|
||||
* @return self
|
||||
*/
|
||||
public function setOption($key, $value)
|
||||
{
|
||||
$this->getProxy()->setOptions([$key => $value]);
|
||||
return parent::setOption($key, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function setValue($value)
|
||||
{
|
||||
$multiple = $this->getAttribute('multiple');
|
||||
|
||||
if (true === $multiple || 'multiple' === $multiple) {
|
||||
if ($value instanceof \Traversable) {
|
||||
$value = ArrayUtils::iteratorToArray($value);
|
||||
} elseif ($value == null) {
|
||||
return parent::setValue([]);
|
||||
} elseif (! is_array($value)) {
|
||||
$value = (array) $value;
|
||||
}
|
||||
|
||||
return parent::setValue(array_map([$this->getProxy(), 'getValue'], $value));
|
||||
}
|
||||
|
||||
return parent::setValue($this->getProxy()->getValue($value));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (! empty($this->valueOptions)) {
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
$proxyValueOptions = $this->getProxy()->getValueOptions();
|
||||
|
||||
if (! empty($proxyValueOptions)) {
|
||||
$this->setValueOptions($proxyValueOptions);
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
}
|
||||
653
src/DoctrineExpressiveModule/Form/Element/Proxy.php
Normal file
653
src/DoctrineExpressiveModule/Form/Element/Proxy.php
Normal file
@ -0,0 +1,653 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Form\Element;
|
||||
|
||||
use Traversable;
|
||||
use ReflectionMethod;
|
||||
use RuntimeException;
|
||||
use InvalidArgumentException;
|
||||
use Zend\Stdlib\Guard\ArrayOrTraversableGuardTrait;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Doctrine\Common\Util\Inflector;
|
||||
|
||||
class Proxy
|
||||
{
|
||||
use ArrayOrTraversableGuardTrait;
|
||||
|
||||
/**
|
||||
* @var array|Traversable
|
||||
*/
|
||||
protected $objects;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $targetClass;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $valueOptions = [];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $findMethod = [];
|
||||
|
||||
/**
|
||||
* @var
|
||||
*/
|
||||
protected $property;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $option_attributes = [];
|
||||
|
||||
/**
|
||||
* @var callable $labelGenerator A callable used to create a label based on an item in the collection an Entity
|
||||
*/
|
||||
protected $labelGenerator;
|
||||
|
||||
/**
|
||||
* @var bool|null
|
||||
*/
|
||||
protected $isMethod;
|
||||
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $displayEmptyItem = false;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $emptyItemLabel = '';
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $optgroupIdentifier;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
protected $optgroupDefault;
|
||||
|
||||
public function setOptions($options)
|
||||
{
|
||||
if (isset($options['object_manager'])) {
|
||||
$this->setObjectManager($options['object_manager']);
|
||||
}
|
||||
|
||||
if (isset($options['target_class'])) {
|
||||
$this->setTargetClass($options['target_class']);
|
||||
}
|
||||
|
||||
if (isset($options['property'])) {
|
||||
$this->setProperty($options['property']);
|
||||
}
|
||||
|
||||
if (isset($options['label_generator'])) {
|
||||
$this->setLabelGenerator($options['label_generator']);
|
||||
}
|
||||
|
||||
if (isset($options['find_method'])) {
|
||||
$this->setFindMethod($options['find_method']);
|
||||
}
|
||||
|
||||
if (isset($options['is_method'])) {
|
||||
$this->setIsMethod($options['is_method']);
|
||||
}
|
||||
|
||||
if (isset($options['display_empty_item'])) {
|
||||
$this->setDisplayEmptyItem($options['display_empty_item']);
|
||||
}
|
||||
|
||||
if (isset($options['empty_item_label'])) {
|
||||
$this->setEmptyItemLabel($options['empty_item_label']);
|
||||
}
|
||||
|
||||
if (isset($options['option_attributes'])) {
|
||||
$this->setOptionAttributes($options['option_attributes']);
|
||||
}
|
||||
|
||||
if (isset($options['optgroup_identifier'])) {
|
||||
$this->setOptgroupIdentifier($options['optgroup_identifier']);
|
||||
}
|
||||
|
||||
if (isset($options['optgroup_default'])) {
|
||||
$this->setOptgroupDefault($options['optgroup_default']);
|
||||
}
|
||||
}
|
||||
|
||||
public function getValueOptions()
|
||||
{
|
||||
if (empty($this->valueOptions)) {
|
||||
$this->loadValueOptions();
|
||||
}
|
||||
|
||||
return $this->valueOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|Traversable
|
||||
*/
|
||||
public function getObjects()
|
||||
{
|
||||
$this->loadObjects();
|
||||
|
||||
return $this->objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the label for the empty option
|
||||
*
|
||||
* @param string $emptyItemLabel
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setEmptyItemLabel($emptyItemLabel)
|
||||
{
|
||||
$this->emptyItemLabel = $emptyItemLabel;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getEmptyItemLabel()
|
||||
{
|
||||
return $this->emptyItemLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function getOptionAttributes()
|
||||
{
|
||||
return $this->option_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $option_attributes
|
||||
*/
|
||||
public function setOptionAttributes(array $option_attributes)
|
||||
{
|
||||
$this->option_attributes = $option_attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a flag, whether to include the empty option at the beginning or not
|
||||
*
|
||||
* @param boolean $displayEmptyItem
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setDisplayEmptyItem($displayEmptyItem)
|
||||
{
|
||||
$this->displayEmptyItem = $displayEmptyItem;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
*/
|
||||
public function getDisplayEmptyItem()
|
||||
{
|
||||
return $this->displayEmptyItem;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the object manager
|
||||
*
|
||||
* @param ObjectManager $objectManager
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setObjectManager(ObjectManager $objectManager)
|
||||
{
|
||||
$this->objectManager = $objectManager;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the object manager
|
||||
*
|
||||
* @return ObjectManager
|
||||
*/
|
||||
public function getObjectManager()
|
||||
{
|
||||
return $this->objectManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the FQCN of the target object
|
||||
*
|
||||
* @param string $targetClass
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setTargetClass($targetClass)
|
||||
{
|
||||
$this->targetClass = $targetClass;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the target class
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getTargetClass()
|
||||
{
|
||||
return $this->targetClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the property to use as the label in the options
|
||||
*
|
||||
* @param string $property
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setProperty($property)
|
||||
{
|
||||
$this->property = $property;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getProperty()
|
||||
{
|
||||
return $this->property;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the label generator callable that is responsible for generating labels for the items in the collection
|
||||
*
|
||||
* @param callable $callable A callable used to create a label based off of an Entity
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setLabelGenerator($callable)
|
||||
{
|
||||
if (! is_callable($callable)) {
|
||||
throw new InvalidArgumentException(
|
||||
'Property "label_generator" needs to be a callable function or a \Closure'
|
||||
);
|
||||
}
|
||||
|
||||
$this->labelGenerator = $callable;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return callable|null
|
||||
*/
|
||||
public function getLabelGenerator()
|
||||
{
|
||||
return $this->labelGenerator;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOptgroupIdentifier()
|
||||
{
|
||||
return $this->optgroupIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $optgroupIdentifier
|
||||
*/
|
||||
public function setOptgroupIdentifier($optgroupIdentifier)
|
||||
{
|
||||
$this->optgroupIdentifier = (string) $optgroupIdentifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|null
|
||||
*/
|
||||
public function getOptgroupDefault()
|
||||
{
|
||||
return $this->optgroupDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $optgroupDefault
|
||||
*/
|
||||
public function setOptgroupDefault($optgroupDefault)
|
||||
{
|
||||
$this->optgroupDefault = (string) $optgroupDefault;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set if the property is a method to use as the label in the options
|
||||
*
|
||||
* @param boolean $method
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setIsMethod($method)
|
||||
{
|
||||
$this->isMethod = (bool) $method;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getIsMethod()
|
||||
{
|
||||
return $this->isMethod;
|
||||
}
|
||||
|
||||
/** Set the findMethod property to specify the method to use on repository
|
||||
*
|
||||
* @param array $findMethod
|
||||
*
|
||||
* @return Proxy
|
||||
*/
|
||||
public function setFindMethod($findMethod)
|
||||
{
|
||||
$this->findMethod = $findMethod;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get findMethod definition
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getFindMethod()
|
||||
{
|
||||
return $this->findMethod;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $targetEntity
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
protected function generateLabel($targetEntity)
|
||||
{
|
||||
if (null === ($labelGenerator = $this->getLabelGenerator())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return call_user_func($labelGenerator, $targetEntity);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $value
|
||||
*
|
||||
* @return array|mixed|object
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function getValue($value)
|
||||
{
|
||||
if (! ($om = $this->getObjectManager())) {
|
||||
throw new RuntimeException('No object manager was set');
|
||||
}
|
||||
|
||||
if (! ($targetClass = $this->getTargetClass())) {
|
||||
throw new RuntimeException('No target class was set');
|
||||
}
|
||||
|
||||
$metadata = $om->getClassMetadata($targetClass);
|
||||
|
||||
if (is_object($value)) {
|
||||
if ($value instanceof Collection) {
|
||||
$data = [];
|
||||
|
||||
foreach ($value as $object) {
|
||||
$values = $metadata->getIdentifierValues($object);
|
||||
$data[] = array_shift($values);
|
||||
}
|
||||
|
||||
$value = $data;
|
||||
} else {
|
||||
$metadata = $om->getClassMetadata(get_class($value));
|
||||
$identifier = $metadata->getIdentifierFieldNames();
|
||||
|
||||
// TODO: handle composite (multiple) identifiers
|
||||
if (null !== $identifier && count($identifier) > 1) {
|
||||
//$value = $key;
|
||||
} else {
|
||||
$value = current($metadata->getIdentifierValues($value));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load objects
|
||||
*
|
||||
* @throws RuntimeException
|
||||
* @throws Exception\InvalidRepositoryResultException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadObjects()
|
||||
{
|
||||
if (! empty($this->objects)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$findMethod = (array) $this->getFindMethod();
|
||||
|
||||
if (! $findMethod) {
|
||||
$findMethodName = 'findAll';
|
||||
$repository = $this->objectManager->getRepository($this->targetClass);
|
||||
$objects = $repository->findAll();
|
||||
} else {
|
||||
if (! isset($findMethod['name'])) {
|
||||
throw new RuntimeException('No method name was set');
|
||||
}
|
||||
$findMethodName = $findMethod['name'];
|
||||
$findMethodParams = isset($findMethod['params']) ? array_change_key_case($findMethod['params']) : [];
|
||||
$repository = $this->objectManager->getRepository($this->targetClass);
|
||||
|
||||
if (! method_exists($repository, $findMethodName)) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Method "%s" could not be found in repository "%s"',
|
||||
$findMethodName,
|
||||
get_class($repository)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$r = new ReflectionMethod($repository, $findMethodName);
|
||||
$args = [];
|
||||
|
||||
foreach ($r->getParameters() as $param) {
|
||||
if (array_key_exists(strtolower($param->getName()), $findMethodParams)) {
|
||||
$args[] = $findMethodParams[strtolower($param->getName())];
|
||||
} elseif ($param->isDefaultValueAvailable()) {
|
||||
$args[] = $param->getDefaultValue();
|
||||
} elseif (! $param->isOptional()) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Required parameter "%s" with no default value for method "%s" in repository "%s"'
|
||||
. ' was not provided',
|
||||
$param->getName(),
|
||||
$findMethodName,
|
||||
get_class($repository)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
$objects = $r->invokeArgs($repository, $args);
|
||||
}
|
||||
|
||||
$this->guardForArrayOrTraversable(
|
||||
$objects,
|
||||
sprintf('%s::%s() return value', get_class($repository), $findMethodName),
|
||||
'DoctrineModule\Form\Element\Exception\InvalidRepositoryResultException'
|
||||
);
|
||||
|
||||
$this->objects = $objects;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load value options
|
||||
*
|
||||
* @throws RuntimeException
|
||||
* @return void
|
||||
*/
|
||||
protected function loadValueOptions()
|
||||
{
|
||||
if (! ($om = $this->objectManager)) {
|
||||
throw new RuntimeException('No object manager was set');
|
||||
}
|
||||
|
||||
if (! ($targetClass = $this->targetClass)) {
|
||||
throw new RuntimeException('No target class was set');
|
||||
}
|
||||
|
||||
$metadata = $om->getClassMetadata($targetClass);
|
||||
$identifier = $metadata->getIdentifierFieldNames();
|
||||
$objects = $this->getObjects();
|
||||
$options = [];
|
||||
$optionAttributes = [];
|
||||
|
||||
if ($this->displayEmptyItem) {
|
||||
$options[''] = $this->getEmptyItemLabel();
|
||||
}
|
||||
|
||||
foreach ($objects as $key => $object) {
|
||||
if (null !== ($generatedLabel = $this->generateLabel($object))) {
|
||||
$label = $generatedLabel;
|
||||
} elseif ($property = $this->property) {
|
||||
if ($this->isMethod == false && ! $metadata->hasField($property)) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Property "%s" could not be found in object "%s"',
|
||||
$property,
|
||||
$targetClass
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$getter = 'get' . Inflector::classify($property);
|
||||
|
||||
if (! is_callable([$object, $getter])) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Method "%s::%s" is not callable', $this->targetClass, $getter)
|
||||
);
|
||||
}
|
||||
|
||||
$label = $object->{$getter}();
|
||||
} else {
|
||||
if (! is_callable([$object, '__toString'])) {
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'%s must have a "__toString()" method defined if you have not set a property'
|
||||
. ' or method to use.',
|
||||
$targetClass
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$label = (string) $object;
|
||||
}
|
||||
|
||||
if (null !== $identifier && count($identifier) > 1) {
|
||||
$value = $key;
|
||||
} else {
|
||||
$value = current($metadata->getIdentifierValues($object));
|
||||
}
|
||||
|
||||
foreach ($this->getOptionAttributes() as $optionKey => $optionValue) {
|
||||
if (is_string($optionValue)) {
|
||||
$optionAttributes[$optionKey] = $optionValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_callable($optionValue)) {
|
||||
$callableValue = call_user_func($optionValue, $object);
|
||||
$optionAttributes[$optionKey] = (string) $callableValue;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new RuntimeException(
|
||||
sprintf(
|
||||
'Parameter "option_attributes" expects an array of key => value where value is of type'
|
||||
. '"string" or "callable". Value of type "%s" found.',
|
||||
gettype($optionValue)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// If no optgroup_identifier has been configured, apply default handling and continue
|
||||
if (is_null($this->getOptgroupIdentifier())) {
|
||||
$options[] = ['label' => $label, 'value' => $value, 'attributes' => $optionAttributes];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// optgroup_identifier found, handle grouping
|
||||
$optgroupGetter = 'get' . Inflector::classify($this->getOptgroupIdentifier());
|
||||
|
||||
if (! is_callable([$object, $optgroupGetter])) {
|
||||
throw new RuntimeException(
|
||||
sprintf('Method "%s::%s" is not callable', $this->targetClass, $optgroupGetter)
|
||||
);
|
||||
}
|
||||
|
||||
$optgroup = $object->{$optgroupGetter}();
|
||||
|
||||
// optgroup_identifier contains a valid group-name. Handle default grouping.
|
||||
if (false === is_null($optgroup) && trim($optgroup) !== '') {
|
||||
$options[$optgroup]['label'] = $optgroup;
|
||||
$options[$optgroup]['options'][] = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'attributes' => $optionAttributes,
|
||||
];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$optgroupDefault = $this->getOptgroupDefault();
|
||||
|
||||
// No optgroup_default has been provided. Line up without a group
|
||||
if (is_null($optgroupDefault)) {
|
||||
$options[] = ['label' => $label, 'value' => $value, 'attributes' => $optionAttributes];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Line up entry with optgroup_default
|
||||
$options[$optgroupDefault]['label'] = $optgroupDefault;
|
||||
$options[$optgroupDefault]['options'][] = [
|
||||
'label' => $label,
|
||||
'value' => $value,
|
||||
'attributes' => $optionAttributes,
|
||||
];
|
||||
}
|
||||
|
||||
$this->valueOptions = $options;
|
||||
}
|
||||
}
|
||||
594
src/DoctrineExpressiveModule/Hydrator/DoctrineObject.php
Normal file
594
src/DoctrineExpressiveModule/Hydrator/DoctrineObject.php
Normal file
@ -0,0 +1,594 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator;
|
||||
|
||||
use DateTime;
|
||||
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Doctrine\Common\Util\Inflector;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use Traversable;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
use Zend\Hydrator\AbstractHydrator;
|
||||
use Zend\Hydrator\Filter\FilterProviderInterface;
|
||||
|
||||
/**
|
||||
* This hydrator has been completely refactored for DoctrineModule 0.7.0. It provides an easy and powerful way
|
||||
* of extracting/hydrator objects in Doctrine, by handling most associations types.
|
||||
*
|
||||
* Starting from DoctrineModule 0.8.0, the hydrator can be used multiple times with different objects
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DoctrineObject extends AbstractHydrator
|
||||
{
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var ClassMetadata
|
||||
*/
|
||||
protected $metadata;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $byValue = true;
|
||||
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param ObjectManager $objectManager The ObjectManager to use
|
||||
* @param bool $byValue If set to true, hydrator will always use entity's public API
|
||||
*/
|
||||
public function __construct(ObjectManager $objectManager, $byValue = true)
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this->objectManager = $objectManager;
|
||||
$this->byValue = (bool) $byValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object
|
||||
*
|
||||
* @param object $object
|
||||
* @return array
|
||||
*/
|
||||
public function extract($object)
|
||||
{
|
||||
$this->prepare($object);
|
||||
|
||||
if ($this->byValue) {
|
||||
return $this->extractByValue($object);
|
||||
}
|
||||
|
||||
return $this->extractByReference($object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate $object with the provided $data.
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
public function hydrate(array $data, $object)
|
||||
{
|
||||
$this->prepare($object);
|
||||
|
||||
if ($this->byValue) {
|
||||
return $this->hydrateByValue($data, $object);
|
||||
}
|
||||
|
||||
return $this->hydrateByReference($data, $object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare the hydrator by adding strategies to every collection valued associations
|
||||
*
|
||||
* @param object $object
|
||||
* @return void
|
||||
*/
|
||||
protected function prepare($object)
|
||||
{
|
||||
$this->metadata = $this->objectManager->getClassMetadata(get_class($object));
|
||||
$this->prepareStrategies();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare strategies before the hydrator is used
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareStrategies()
|
||||
{
|
||||
$associations = $this->metadata->getAssociationNames();
|
||||
|
||||
foreach ($associations as $association) {
|
||||
if ($this->metadata->isCollectionValuedAssociation($association)) {
|
||||
// Add a strategy if the association has none set by user
|
||||
if (!$this->hasStrategy($association)) {
|
||||
if ($this->byValue) {
|
||||
$this->addStrategy($association, new Strategy\AllowRemoveByValue());
|
||||
} else {
|
||||
$this->addStrategy($association, new Strategy\AllowRemoveByReference());
|
||||
}
|
||||
}
|
||||
|
||||
$strategy = $this->getStrategy($association);
|
||||
|
||||
if (!$strategy instanceof Strategy\AbstractCollectionStrategy) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf(
|
||||
'Strategies used for collections valued associations must inherit from '
|
||||
. 'Strategy\AbstractCollectionStrategy, %s given',
|
||||
get_class($strategy)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$strategy->setCollectionName($association)
|
||||
->setClassMetadata($this->metadata);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object using a by-value logic (this means that it uses the entity
|
||||
* API, in this case, getters)
|
||||
*
|
||||
* @param object $object
|
||||
* @throws RuntimeException
|
||||
* @return array
|
||||
*/
|
||||
protected function extractByValue($object)
|
||||
{
|
||||
$fieldNames = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
|
||||
$methods = get_class_methods($object);
|
||||
$filter = $object instanceof FilterProviderInterface
|
||||
? $object->getFilter()
|
||||
: $this->filterComposite;
|
||||
|
||||
$data = [];
|
||||
foreach ($fieldNames as $fieldName) {
|
||||
if ($filter && !$filter->filter($fieldName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$getter = 'get' . Inflector::classify($fieldName);
|
||||
$isser = 'is' . Inflector::classify($fieldName);
|
||||
|
||||
$dataFieldName = $this->computeExtractFieldName($fieldName);
|
||||
if (in_array($getter, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$getter(), $object);
|
||||
} elseif (in_array($isser, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$isser(), $object);
|
||||
} elseif (substr($fieldName, 0, 2) === 'is'
|
||||
&& ctype_upper(substr($fieldName, 2, 1))
|
||||
&& in_array($fieldName, $methods)) {
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $object->$fieldName(), $object);
|
||||
}
|
||||
|
||||
// Unknown fields are ignored
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract values from an object using a by-reference logic (this means that values are
|
||||
* directly fetched without using the public API of the entity, in this case, getters)
|
||||
*
|
||||
* @param object $object
|
||||
* @return array
|
||||
*/
|
||||
protected function extractByReference($object)
|
||||
{
|
||||
$fieldNames = array_merge($this->metadata->getFieldNames(), $this->metadata->getAssociationNames());
|
||||
$refl = $this->metadata->getReflectionClass();
|
||||
$filter = $object instanceof FilterProviderInterface
|
||||
? $object->getFilter()
|
||||
: $this->filterComposite;
|
||||
|
||||
$data = [];
|
||||
foreach ($fieldNames as $fieldName) {
|
||||
if ($filter && !$filter->filter($fieldName)) {
|
||||
continue;
|
||||
}
|
||||
$reflProperty = $refl->getProperty($fieldName);
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
$dataFieldName = $this->computeExtractFieldName($fieldName);
|
||||
$data[$dataFieldName] = $this->extractValue($fieldName, $reflProperty->getValue($object), $object);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the object using a by-value logic (this means that it uses the entity API, in this
|
||||
* case, setters)
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @throws RuntimeException
|
||||
* @return object
|
||||
*/
|
||||
protected function hydrateByValue(array $data, $object)
|
||||
{
|
||||
$tryObject = $this->tryConvertArrayToObject($data, $object);
|
||||
$metadata = $this->metadata;
|
||||
|
||||
if (is_object($tryObject)) {
|
||||
$object = $tryObject;
|
||||
}
|
||||
|
||||
foreach ($data as $field => $value) {
|
||||
$field = $this->computeHydrateFieldName($field);
|
||||
$value = $this->handleTypeConversions($value, $metadata->getTypeOfField($field));
|
||||
$setter = 'set' . Inflector::classify($field);
|
||||
|
||||
if ($metadata->hasAssociation($field)) {
|
||||
$target = $metadata->getAssociationTargetClass($field);
|
||||
|
||||
if ($metadata->isSingleValuedAssociation($field)) {
|
||||
if (! method_exists($object, $setter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
|
||||
|
||||
if (null === $value
|
||||
&& !current($metadata->getReflectionClass()->getMethod($setter)->getParameters())->allowsNull()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$object->$setter($value);
|
||||
} elseif ($metadata->isCollectionValuedAssociation($field)) {
|
||||
$this->toMany($object, $field, $target, $value);
|
||||
}
|
||||
} else {
|
||||
if (! method_exists($object, $setter)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$object->$setter($this->hydrateValue($field, $value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrate the object using a by-reference logic (this means that values are modified directly without
|
||||
* using the public API, in this case setters, and hence override any logic that could be done in those
|
||||
* setters)
|
||||
*
|
||||
* @param array $data
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
protected function hydrateByReference(array $data, $object)
|
||||
{
|
||||
$tryObject = $this->tryConvertArrayToObject($data, $object);
|
||||
$metadata = $this->metadata;
|
||||
$refl = $metadata->getReflectionClass();
|
||||
|
||||
if (is_object($tryObject)) {
|
||||
$object = $tryObject;
|
||||
}
|
||||
|
||||
foreach ($data as $field => $value) {
|
||||
$field = $this->computeHydrateFieldName($field);
|
||||
|
||||
// Ignore unknown fields
|
||||
if (!$refl->hasProperty($field)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->handleTypeConversions($value, $metadata->getTypeOfField($field));
|
||||
$reflProperty = $refl->getProperty($field);
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
if ($metadata->hasAssociation($field)) {
|
||||
$target = $metadata->getAssociationTargetClass($field);
|
||||
|
||||
if ($metadata->isSingleValuedAssociation($field)) {
|
||||
$value = $this->toOne($target, $this->hydrateValue($field, $value, $data));
|
||||
$reflProperty->setValue($object, $value);
|
||||
} elseif ($metadata->isCollectionValuedAssociation($field)) {
|
||||
$this->toMany($object, $field, $target, $value);
|
||||
}
|
||||
} else {
|
||||
$reflProperty->setValue($object, $this->hydrateValue($field, $value, $data));
|
||||
}
|
||||
}
|
||||
|
||||
return $object;
|
||||
}
|
||||
|
||||
/**
|
||||
* This function tries, given an array of data, to convert it to an object if the given array contains
|
||||
* an identifier for the object. This is useful in a context of updating existing entities, without ugly
|
||||
* tricks like setting manually the existing id directly into the entity
|
||||
*
|
||||
* @param array $data The data that may contain identifiers keys
|
||||
* @param object $object
|
||||
* @return object
|
||||
*/
|
||||
protected function tryConvertArrayToObject($data, $object)
|
||||
{
|
||||
$metadata = $this->metadata;
|
||||
$identifierNames = $metadata->getIdentifierFieldNames($object);
|
||||
$identifierValues = [];
|
||||
|
||||
if (empty($identifierNames)) {
|
||||
return $object;
|
||||
}
|
||||
|
||||
foreach ($identifierNames as $identifierName) {
|
||||
if (!isset($data[$identifierName])) {
|
||||
return $object;
|
||||
}
|
||||
|
||||
$identifierValues[$identifierName] = $data[$identifierName];
|
||||
}
|
||||
|
||||
return $this->find($identifierValues, $metadata->getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ToOne associations
|
||||
*
|
||||
* When $value is an array but is not the $target's identifiers, $value is
|
||||
* most likely an array of fieldset data. The identifiers will be determined
|
||||
* and a target instance will be initialized and then hydrated. The hydrated
|
||||
* target will be returned.
|
||||
*
|
||||
* @param string $target
|
||||
* @param mixed $value
|
||||
* @return object
|
||||
*/
|
||||
protected function toOne($target, $value)
|
||||
{
|
||||
$metadata = $this->objectManager->getClassMetadata($target);
|
||||
|
||||
if (is_array($value) && array_keys($value) != $metadata->getIdentifier()) {
|
||||
// $value is most likely an array of fieldset data
|
||||
$identifiers = array_intersect_key(
|
||||
$value,
|
||||
array_flip($metadata->getIdentifier())
|
||||
);
|
||||
$object = $this->find($identifiers, $target) ?: new $target;
|
||||
return $this->hydrate($value, $object);
|
||||
}
|
||||
|
||||
return $this->find($value, $target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle ToMany associations. In proper Doctrine design, Collections should not be swapped, so
|
||||
* collections are always handled by reference. Internally, every collection is handled using specials
|
||||
* strategies that inherit from AbstractCollectionStrategy class, and that add or remove elements but without
|
||||
* changing the collection of the object
|
||||
*
|
||||
* @param object $object
|
||||
* @param mixed $collectionName
|
||||
* @param string $target
|
||||
* @param mixed $values
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function toMany($object, $collectionName, $target, $values)
|
||||
{
|
||||
$metadata = $this->objectManager->getClassMetadata(ltrim($target, '\\'));
|
||||
$identifier = $metadata->getIdentifier();
|
||||
|
||||
if (!is_array($values) && !$values instanceof Traversable) {
|
||||
$values = (array)$values;
|
||||
}
|
||||
|
||||
$collection = [];
|
||||
|
||||
// If the collection contains identifiers, fetch the objects from database
|
||||
foreach ($values as $value) {
|
||||
if ($value instanceof $target) {
|
||||
// assumes modifications have already taken place in object
|
||||
$collection[] = $value;
|
||||
continue;
|
||||
} elseif (empty($value)) {
|
||||
// assumes no id and retrieves new $target
|
||||
$collection[] = $this->find($value, $target);
|
||||
continue;
|
||||
}
|
||||
|
||||
$find = [];
|
||||
if (is_array($identifier)) {
|
||||
foreach ($identifier as $field) {
|
||||
switch (gettype($value)) {
|
||||
case 'object':
|
||||
$getter = 'get' . ucfirst($field);
|
||||
if (method_exists($value, $getter)) {
|
||||
$find[$field] = $value->$getter();
|
||||
} elseif (property_exists($value, $field)) {
|
||||
$find[$field] = $value->$field;
|
||||
}
|
||||
break;
|
||||
case 'array':
|
||||
if (array_key_exists($field, $value) && $value[$field] != null) {
|
||||
$find[$field] = $value[$field];
|
||||
unset($value[$field]); // removed identifier from persistable data
|
||||
}
|
||||
break;
|
||||
default:
|
||||
$find[$field] = $value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($find) && $found = $this->find($find, $target)) {
|
||||
$collection[] = (is_array($value)) ? $this->hydrate($value, $found) : $found;
|
||||
} else {
|
||||
$collection[] = (is_array($value)) ? $this->hydrate($value, new $target) : new $target;
|
||||
}
|
||||
}
|
||||
|
||||
$collection = array_filter(
|
||||
$collection,
|
||||
function ($item) {
|
||||
return null !== $item;
|
||||
}
|
||||
);
|
||||
|
||||
// Set the object so that the strategy can extract the Collection from it
|
||||
|
||||
/** @var \DoctrineModule\Stdlib\Hydrator\Strategy\AbstractCollectionStrategy $collectionStrategy */
|
||||
$collectionStrategy = $this->getStrategy($collectionName);
|
||||
$collectionStrategy->setObject($object);
|
||||
|
||||
// We could directly call hydrate method from the strategy, but if people want to override
|
||||
// hydrateValue function, they can do it and do their own stuff
|
||||
$this->hydrateValue($collectionName, $collection, $values);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle various type conversions that should be supported natively by Doctrine (like DateTime)
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param string $typeOfField
|
||||
* @return DateTime
|
||||
*/
|
||||
protected function handleTypeConversions($value, $typeOfField)
|
||||
{
|
||||
switch ($typeOfField) {
|
||||
case 'datetimetz':
|
||||
case 'datetime':
|
||||
case 'time':
|
||||
case 'date':
|
||||
if ('' === $value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (is_int($value)) {
|
||||
$dateTime = new DateTime();
|
||||
$dateTime->setTimestamp($value);
|
||||
$value = $dateTime;
|
||||
} elseif (is_string($value)) {
|
||||
$value = new DateTime($value);
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find an object by a given target class and identifier
|
||||
*
|
||||
* @param mixed $identifiers
|
||||
* @param string $targetClass
|
||||
*
|
||||
* @return object|null
|
||||
*/
|
||||
protected function find($identifiers, $targetClass)
|
||||
{
|
||||
if ($identifiers instanceof $targetClass) {
|
||||
return $identifiers;
|
||||
}
|
||||
|
||||
if ($this->isNullIdentifier($identifiers)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->objectManager->find($targetClass, $identifiers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies if a provided identifier is to be considered null
|
||||
*
|
||||
* @param mixed $identifier
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function isNullIdentifier($identifier)
|
||||
{
|
||||
if (null === $identifier) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($identifier instanceof Traversable || is_array($identifier)) {
|
||||
$nonNullIdentifiers = array_filter(
|
||||
ArrayUtils::iteratorToArray($identifier),
|
||||
function ($value) {
|
||||
return null !== $value;
|
||||
}
|
||||
);
|
||||
|
||||
return empty($nonNullIdentifiers);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the naming strategy if there is one set
|
||||
*
|
||||
* @param string $field
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function computeHydrateFieldName($field)
|
||||
{
|
||||
if ($this->hasNamingStrategy()) {
|
||||
$field = $this->getNamingStrategy()->hydrate($field);
|
||||
}
|
||||
return $field;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the naming strategy if there is one set
|
||||
*
|
||||
* @param string $field
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function computeExtractFieldName($field)
|
||||
{
|
||||
if ($this->hasNamingStrategy()) {
|
||||
$field = $this->getNamingStrategy()->extract($field);
|
||||
}
|
||||
return $field;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
|
||||
class DoctrineObjectFactory
|
||||
{
|
||||
|
||||
public function __invoke(ContainerInterface $container)
|
||||
{
|
||||
$em = $container->get('doctrine.entity_manager.orm_default');
|
||||
return new DoctrineObject($em);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,66 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Filter;
|
||||
|
||||
use Zend\Hydrator\Filter\FilterInterface;
|
||||
|
||||
/**
|
||||
* Provides a filter to restrict returned fields by whitelisting or
|
||||
* blacklisting property names.
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @author Liam O'Boyle <liam@ontheroad.net.nz>
|
||||
*/
|
||||
class PropertyName implements FilterInterface
|
||||
{
|
||||
/**
|
||||
* The propteries to exclude.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $properties = [];
|
||||
|
||||
/**
|
||||
* Either an exclude or an include.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $exclude = null;
|
||||
|
||||
/**
|
||||
* @param [ string | array ] $properties The properties to exclude or include.
|
||||
* @param bool $exclude If the method should be excluded
|
||||
*/
|
||||
public function __construct($properties, $exclude = true)
|
||||
{
|
||||
$this->exclude = $exclude;
|
||||
$this->properties = is_array($properties)
|
||||
? $properties
|
||||
: [$properties];
|
||||
}
|
||||
|
||||
public function filter($property)
|
||||
{
|
||||
return in_array($property, $this->properties)
|
||||
? !$this->exclude
|
||||
: $this->exclude;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,190 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
|
||||
use Zend\Hydrator\Strategy\StrategyInterface;
|
||||
|
||||
/**
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
abstract class AbstractCollectionStrategy implements StrategyInterface
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $collectionName;
|
||||
|
||||
/**
|
||||
* @var ClassMetadata
|
||||
*/
|
||||
protected $metadata;
|
||||
|
||||
/**
|
||||
* @var object
|
||||
*/
|
||||
protected $object;
|
||||
|
||||
|
||||
/**
|
||||
* Set the name of the collection
|
||||
*
|
||||
* @param string $collectionName
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setCollectionName($collectionName)
|
||||
{
|
||||
$this->collectionName = (string) $collectionName;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the name of the collection
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getCollectionName()
|
||||
{
|
||||
return $this->collectionName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the class metadata
|
||||
*
|
||||
* @param ClassMetadata $classMetadata
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setClassMetadata(ClassMetadata $classMetadata)
|
||||
{
|
||||
$this->metadata = $classMetadata;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the class metadata
|
||||
*
|
||||
* @return ClassMetadata
|
||||
*/
|
||||
public function getClassMetadata()
|
||||
{
|
||||
return $this->metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the object
|
||||
*
|
||||
* @param object $object
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return AbstractCollectionStrategy
|
||||
*/
|
||||
public function setObject($object)
|
||||
{
|
||||
if (!is_object($object)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf('The parameter given to setObject method of %s class is not an object', get_called_class())
|
||||
);
|
||||
}
|
||||
|
||||
$this->object = $object;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the object
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function getObject()
|
||||
{
|
||||
return $this->object;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function extract($value)
|
||||
{
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the collection by value (using the public API)
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getCollectionFromObjectByValue()
|
||||
{
|
||||
$object = $this->getObject();
|
||||
$getter = 'get' . ucfirst($this->getCollectionName());
|
||||
|
||||
if (!method_exists($object, $getter)) {
|
||||
throw new InvalidArgumentException(
|
||||
sprintf(
|
||||
'The getter %s to access collection %s in object %s does not exist',
|
||||
$getter,
|
||||
$this->getCollectionName(),
|
||||
get_class($object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $object->$getter();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the collection by reference (not using the public API)
|
||||
*
|
||||
* @return Collection
|
||||
*/
|
||||
protected function getCollectionFromObjectByReference()
|
||||
{
|
||||
$object = $this->getObject();
|
||||
$refl = $this->getClassMetadata()->getReflectionClass();
|
||||
$reflProperty = $refl->getProperty($this->getCollectionName());
|
||||
|
||||
$reflProperty->setAccessible(true);
|
||||
|
||||
return $reflProperty->getValue($object);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This method is used internally by array_udiff to check if two objects are equal, according to their
|
||||
* SPL hash. This is needed because the native array_diff only compare strings
|
||||
*
|
||||
* @param object $a
|
||||
* @param object $b
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function compareObjects($a, $b)
|
||||
{
|
||||
return strcmp(spl_object_hash($a), spl_object_hash($b));
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,58 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy remove elements from the original collection. For instance, if the
|
||||
* collection initially contains elements A and B, and that the new collection contains elements B and C, then the
|
||||
* final collection will contain elements B and C (while element A will be asked to be removed).
|
||||
*
|
||||
* This strategy is by reference, this means it won't use public API to add/remove elements to the collection
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class AllowRemoveByReference extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
$collection = $this->getCollectionFromObjectByReference();
|
||||
$collectionArray = $collection->toArray();
|
||||
|
||||
$toAdd = array_udiff($value, $collectionArray, [$this, 'compareObjects']);
|
||||
$toRemove = array_udiff($collectionArray, $value, [$this, 'compareObjects']);
|
||||
|
||||
foreach ($toAdd as $element) {
|
||||
$collection->add($element);
|
||||
}
|
||||
|
||||
foreach ($toRemove as $element) {
|
||||
$collection->removeElement($element);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use LogicException;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy remove elements from the original collection. For instance, if the
|
||||
* collection initially contains elements A and B, and that the new collection contains elements B and C, then the
|
||||
* final collection will contain elements B and C (while element A will be asked to be removed).
|
||||
*
|
||||
* This strategy is by value, this means it will use the public API (in this case, adder and remover)
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class AllowRemoveByValue extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
// AllowRemove strategy need "adder" and "remover"
|
||||
$adder = 'add' . ucfirst($this->collectionName);
|
||||
$remover = 'remove' . ucfirst($this->collectionName);
|
||||
|
||||
if (!method_exists($this->object, $adder) || !method_exists($this->object, $remover)) {
|
||||
throw new LogicException(
|
||||
sprintf(
|
||||
'AllowRemove strategy for DoctrineModule hydrator requires both %s and %s to be defined in %s
|
||||
entity domain code, but one or both seem to be missing',
|
||||
$adder,
|
||||
$remover,
|
||||
get_class($this->object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$collection = $this->getCollectionFromObjectByValue();
|
||||
|
||||
if ($collection instanceof Collection) {
|
||||
$collection = $collection->toArray();
|
||||
}
|
||||
|
||||
$toAdd = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
|
||||
$toRemove = new ArrayCollection(array_udiff($collection, $value, [$this, 'compareObjects']));
|
||||
|
||||
$this->object->$adder($toAdd);
|
||||
$this->object->$remover($toRemove);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,53 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy will not remove those elements. At most, it will add new elements. For
|
||||
* instance, if the collection initially contains elements A and B, and that the new collection contains elements B
|
||||
* and C, then the final collection will contain elements A, B and C.
|
||||
*
|
||||
* This strategy is by reference, this means it won't use the public API to remove elements
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DisallowRemoveByReference extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
$collection = $this->getCollectionFromObjectByReference();
|
||||
$collectionArray = $collection->toArray();
|
||||
|
||||
$toAdd = array_udiff($value, $collectionArray, [$this, 'compareObjects']);
|
||||
|
||||
foreach ($toAdd as $element) {
|
||||
$collection->add($element);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,72 @@
|
||||
<?php
|
||||
/*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the MIT license. For more information, see
|
||||
* <http://www.doctrine-project.org>.
|
||||
*/
|
||||
|
||||
namespace DoctrineExpressiveModule\Hydrator\Strategy;
|
||||
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use LogicException;
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
|
||||
/**
|
||||
* When this strategy is used for Collections, if the new collection does not contain elements that are present in
|
||||
* the original collection, then this strategy will not remove those elements. At most, it will add new elements. For
|
||||
* instance, if the collection initially contains elements A and B, and that the new collection contains elements B
|
||||
* and C, then the final collection will contain elements A, B and C.
|
||||
*
|
||||
* This strategy is by value, this means it will use the public API (in this case, remover)
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.7.0
|
||||
* @author Michael Gallego <mic.gallego@gmail.com>
|
||||
*/
|
||||
class DisallowRemoveByValue extends AbstractCollectionStrategy
|
||||
{
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function hydrate($value)
|
||||
{
|
||||
// AllowRemove strategy need "adder"
|
||||
$adder = 'add' . ucfirst($this->collectionName);
|
||||
|
||||
if (!method_exists($this->object, $adder)) {
|
||||
throw new LogicException(
|
||||
sprintf(
|
||||
'DisallowRemove strategy for DoctrineModule hydrator requires %s to
|
||||
be defined in %s entity domain code, but it seems to be missing',
|
||||
$adder,
|
||||
get_class($this->object)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$collection = $this->getCollectionFromObjectByValue();
|
||||
|
||||
if ($collection instanceof Collection) {
|
||||
$collection = $collection->toArray();
|
||||
}
|
||||
|
||||
$toAdd = new ArrayCollection(array_udiff($value, $collection, [$this, 'compareObjects']));
|
||||
|
||||
$this->object->$adder($toAdd);
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
43
src/DoctrineExpressiveModule/Validator/NoObjectExists.php
Normal file
43
src/DoctrineExpressiveModule/Validator/NoObjectExists.php
Normal file
@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
/**
|
||||
* Class that validates if objects does not exist in a given repository with a given list of matched fields
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.4.0
|
||||
* @author Marco Pivetta <ocramius@gmail.com>
|
||||
*/
|
||||
class NoObjectExists extends ObjectExists
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_OBJECT_FOUND = 'objectFound';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_OBJECT_FOUND => "An object matching '%value%' was found",
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (is_object($match)) {
|
||||
$this->error(self::ERROR_OBJECT_FOUND, $value);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
175
src/DoctrineExpressiveModule/Validator/ObjectExists.php
Normal file
175
src/DoctrineExpressiveModule/Validator/ObjectExists.php
Normal file
@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Doctrine\Common\Persistence\ObjectRepository;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
/**
|
||||
* Class that validates if objects exist in a given repository with a given list of matched fields
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 0.4.0
|
||||
* @author Marco Pivetta <ocramius@gmail.com>
|
||||
*/
|
||||
class ObjectExists extends AbstractValidator
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_NO_OBJECT_FOUND = 'noObjectFound';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_NO_OBJECT_FOUND => "No object matching '%value%' was found",
|
||||
];
|
||||
|
||||
/**
|
||||
* ObjectRepository from which to search for entities
|
||||
*
|
||||
* @var ObjectRepository
|
||||
*/
|
||||
protected $objectRepository;
|
||||
|
||||
/**
|
||||
* Fields to be checked
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $fields;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options required keys are `object_repository`, which must be an instance of
|
||||
* Doctrine\Common\Persistence\ObjectRepository, and `fields`, with either
|
||||
* a string or an array of strings representing the fields to be matched by the validator.
|
||||
* @throws \Zend\Validator\Exception\InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $options)
|
||||
{
|
||||
if (! isset($options['object_repository']) || ! $options['object_repository'] instanceof ObjectRepository) {
|
||||
if (! array_key_exists('object_repository', $options)) {
|
||||
$provided = 'nothing';
|
||||
} else {
|
||||
if (is_object($options['object_repository'])) {
|
||||
$provided = get_class($options['object_repository']);
|
||||
} else {
|
||||
$provided = getType($options['object_repository']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf(
|
||||
'Option "object_repository" is required and must be an instance of'
|
||||
. ' Doctrine\Common\Persistence\ObjectRepository, %s given',
|
||||
$provided
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$this->objectRepository = $options['object_repository'];
|
||||
|
||||
if (! isset($options['fields'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Key `fields` must be provided and be a field or a list of fields to be used when searching for'
|
||||
. ' existing instances'
|
||||
);
|
||||
}
|
||||
|
||||
$this->fields = $options['fields'];
|
||||
$this->validateFields();
|
||||
|
||||
parent::__construct($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters and validates the fields passed to the constructor
|
||||
*
|
||||
* @throws \Zend\Validator\Exception\InvalidArgumentException
|
||||
* @return array
|
||||
*/
|
||||
private function validateFields()
|
||||
{
|
||||
$fields = (array) $this->fields;
|
||||
|
||||
if (empty($fields)) {
|
||||
throw new Exception\InvalidArgumentException('Provided fields list was empty!');
|
||||
}
|
||||
|
||||
foreach ($fields as $key => $field) {
|
||||
if (! is_string($field)) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf('Provided fields must be strings, %s provided for key %s', gettype($field), $key)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->fields = array_values($fields);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|array $value a field value or an array of field values if more fields have been configured to be
|
||||
* matched
|
||||
* @return array
|
||||
* @throws \Zend\Validator\Exception\RuntimeException
|
||||
*/
|
||||
protected function cleanSearchValue($value)
|
||||
{
|
||||
$value = is_object($value) ? [$value] : (array) $value;
|
||||
|
||||
if (ArrayUtils::isHashTable($value)) {
|
||||
$matchedFieldsValues = [];
|
||||
|
||||
foreach ($this->fields as $field) {
|
||||
if (! array_key_exists($field, $value)) {
|
||||
throw new Exception\RuntimeException(
|
||||
sprintf(
|
||||
'Field "%s" was not provided, but was expected since the configured field lists needs'
|
||||
. ' it for validation',
|
||||
$field
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$matchedFieldsValues[$field] = $value[$field];
|
||||
}
|
||||
} else {
|
||||
$matchedFieldsValues = @array_combine($this->fields, $value);
|
||||
|
||||
if (false === $matchedFieldsValues) {
|
||||
throw new Exception\RuntimeException(
|
||||
sprintf(
|
||||
'Provided values count is %s, while expected number of fields to be matched is %s',
|
||||
count($value),
|
||||
count($this->fields)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return $matchedFieldsValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (is_object($match)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->error(self::ERROR_NO_OBJECT_FOUND, $value);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Zend\ServiceManager\FactoryInterface;
|
||||
use Interop\Container\ContainerInterface;
|
||||
use Zend\ServiceManager\ServiceLocatorInterface;
|
||||
use Zend\ServiceManager\ServiceLocatorAwareInterface;
|
||||
use DoctrineModule\Validator\Service\Exception\ServiceCreationException;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
|
||||
/**
|
||||
* Factory for creating NoObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
abstract class AbstractValidatorFactory implements FactoryInterface
|
||||
{
|
||||
const DEFAULT_OBJECTMANAGER_KEY = 'doctrine.entitymanager.orm_default';
|
||||
|
||||
protected $creationOptions = [];
|
||||
|
||||
protected $validatorClass;
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @param array $options
|
||||
* @return \Doctrine\Common\Persistence\ObjectRepository
|
||||
* @throws ServiceCreationException
|
||||
*/
|
||||
protected function getRepository(ContainerInterface $container, array $options)
|
||||
{
|
||||
if (empty($options['target_class'])) {
|
||||
throw new ServiceCreationException(sprintf(
|
||||
"Option 'target_class' is missing when creating validator %s",
|
||||
__CLASS__
|
||||
));
|
||||
}
|
||||
|
||||
$objectManager = $this->getObjectManager($container, $options);
|
||||
$targetClassName = $options['target_class'];
|
||||
$objectRepository = $objectManager->getRepository($targetClassName);
|
||||
|
||||
return $objectRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ContainerInterface $container
|
||||
* @param array $options
|
||||
* @return \Doctrine\Common\Persistence\ObjectManager
|
||||
*/
|
||||
protected function getObjectManager(ContainerInterface $container, array $options)
|
||||
{
|
||||
$objectManager = ($options['object_manager']) ?? self::DEFAULT_OBJECTMANAGER_KEY;
|
||||
|
||||
if (is_string($objectManager)) {
|
||||
$objectManager = $container->get($objectManager);
|
||||
}
|
||||
|
||||
return $objectManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $options
|
||||
* @return array
|
||||
*/
|
||||
protected function getFields(array $options)
|
||||
{
|
||||
if (isset($options['fields'])) {
|
||||
return (array) $options['fields'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to merge options array passed to `__invoke`
|
||||
* together with the options array created based on the above
|
||||
* helper methods.
|
||||
*
|
||||
* @param array $previousOptions
|
||||
* @param array $newOptions
|
||||
* @return array
|
||||
*/
|
||||
protected function merge($previousOptions, $newOptions)
|
||||
{
|
||||
return ArrayUtils::merge($previousOptions, $newOptions, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method for ZF2 compatiblity.
|
||||
*
|
||||
* In ZF2 the plugin manager instance if passed to `createService`
|
||||
* instead of the global service manager instance (as in ZF3).
|
||||
*
|
||||
* @param ContainerInterface $container
|
||||
* @return ContainerInterface
|
||||
*/
|
||||
protected function container(ContainerInterface $container)
|
||||
{
|
||||
if ($container instanceof ServiceLocatorAwareInterface) {
|
||||
$container = $container->getServiceLocator();
|
||||
}
|
||||
|
||||
return $container;
|
||||
}
|
||||
|
||||
public function createService(ServiceLocatorInterface $serviceLocator)
|
||||
{
|
||||
return $this($serviceLocator, $this->validatorClass, $this->creationOptions);
|
||||
}
|
||||
|
||||
public function setCreationOptions(array $options)
|
||||
{
|
||||
$this->creationOptions = $options;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service\Exception;
|
||||
|
||||
use RuntimeException as BaseRuntimeException;
|
||||
|
||||
/**
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class ServiceCreationException extends BaseRuntimeException
|
||||
{
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\NoObjectExists;
|
||||
|
||||
/**
|
||||
* Factory for creating NoObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class NoObjectExistsFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = NoObjectExists::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$repository = $this->getRepository($container, $options);
|
||||
|
||||
$validator = new NoObjectExists($this->merge($options, [
|
||||
'object_repository' => $repository,
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\ObjectExists;
|
||||
|
||||
/**
|
||||
* Factory for creating ObjectExists instances
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @since 1.3.0
|
||||
* @author Fabian Grutschus <f.grutschus@lubyte.de>
|
||||
*/
|
||||
class ObjectExistsFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = ObjectExists::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$repository = $this->getRepository($container, $options);
|
||||
|
||||
$validator = new ObjectExists($this->merge($options, [
|
||||
'object_repository' => $repository,
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace DoctrineModule\Validator\Service;
|
||||
|
||||
use Interop\Container\ContainerInterface;
|
||||
use DoctrineModule\Validator\UniqueObject;
|
||||
|
||||
class UniqueObjectFactory extends AbstractValidatorFactory
|
||||
{
|
||||
protected $validatorClass = UniqueObject::class;
|
||||
|
||||
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
|
||||
{
|
||||
$container = $this->container($container);
|
||||
|
||||
$useContext = isset($options['use_context']) ? (boolean) $options['use_context'] : false;
|
||||
|
||||
$validator = new UniqueObject($this->merge($options, [
|
||||
'object_manager' => $this->getObjectManager($container, $options),
|
||||
'use_context' => $useContext,
|
||||
'object_repository' => $this->getRepository($container, $options),
|
||||
'fields' => $this->getFields($options),
|
||||
]));
|
||||
|
||||
return $validator;
|
||||
}
|
||||
}
|
||||
166
src/DoctrineExpressiveModule/Validator/UniqueObject.php
Normal file
166
src/DoctrineExpressiveModule/Validator/UniqueObject.php
Normal file
@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace DoctrineModule\Validator;
|
||||
|
||||
use Doctrine\Common\Persistence\ObjectManager;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
/**
|
||||
* Class that validates if objects exist in a given repository with a given list of matched fields only once.
|
||||
*
|
||||
* @license MIT
|
||||
* @link http://www.doctrine-project.org/
|
||||
* @author Oskar Bley <oskar@programming-php.net>
|
||||
*/
|
||||
class UniqueObject extends ObjectExists
|
||||
{
|
||||
/**
|
||||
* Error constants
|
||||
*/
|
||||
const ERROR_OBJECT_NOT_UNIQUE = 'objectNotUnique';
|
||||
|
||||
/**
|
||||
* @var array Message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::ERROR_OBJECT_NOT_UNIQUE => "There is already another object matching '%value%'",
|
||||
];
|
||||
|
||||
/**
|
||||
* @var ObjectManager
|
||||
*/
|
||||
protected $objectManager;
|
||||
|
||||
/**
|
||||
* @var boolean
|
||||
*/
|
||||
protected $useContext;
|
||||
|
||||
/***
|
||||
* Constructor
|
||||
*
|
||||
* @param array $options required keys are `object_repository`, which must be an instance of
|
||||
* Doctrine\Common\Persistence\ObjectRepository, `object_manager`, which
|
||||
* must be an instance of Doctrine\Common\Persistence\ObjectManager,
|
||||
* and `fields`, with either a string or an array of strings representing
|
||||
* the fields to be matched by the validator.
|
||||
* @throws Exception\InvalidArgumentException
|
||||
*/
|
||||
public function __construct(array $options)
|
||||
{
|
||||
parent::__construct($options);
|
||||
|
||||
if (! isset($options['object_manager']) || ! $options['object_manager'] instanceof ObjectManager) {
|
||||
if (! array_key_exists('object_manager', $options)) {
|
||||
$provided = 'nothing';
|
||||
} else {
|
||||
if (is_object($options['object_manager'])) {
|
||||
$provided = get_class($options['object_manager']);
|
||||
} else {
|
||||
$provided = getType($options['object_manager']);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception\InvalidArgumentException(
|
||||
sprintf(
|
||||
'Option "object_manager" is required and must be an instance of'
|
||||
. ' Doctrine\Common\Persistence\ObjectManager, %s given',
|
||||
$provided
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$this->objectManager = $options['object_manager'];
|
||||
$this->useContext = isset($options['use_context']) ? (boolean) $options['use_context'] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns false if there is another object with the same field values but other identifiers.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @param array $context
|
||||
* @return boolean
|
||||
*/
|
||||
public function isValid($value, $context = null)
|
||||
{
|
||||
if (! $this->useContext) {
|
||||
$context = (array) $value;
|
||||
}
|
||||
|
||||
$cleanedValue = $this->cleanSearchValue($value);
|
||||
$match = $this->objectRepository->findOneBy($cleanedValue);
|
||||
|
||||
if (! is_object($match)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$expectedIdentifiers = $this->getExpectedIdentifiers($context);
|
||||
$foundIdentifiers = $this->getFoundIdentifiers($match);
|
||||
|
||||
if (count(array_diff_assoc($expectedIdentifiers, $foundIdentifiers)) == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->error(self::ERROR_OBJECT_NOT_UNIQUE, $value);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the identifiers from the matched object.
|
||||
*
|
||||
* @param object $match
|
||||
* @return array
|
||||
* @throws Exception\RuntimeException
|
||||
*/
|
||||
protected function getFoundIdentifiers($match)
|
||||
{
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierValues($match);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the identifiers from the context.
|
||||
*
|
||||
* @param array|object $context
|
||||
* @return array
|
||||
* @throws Exception\RuntimeException
|
||||
*/
|
||||
protected function getExpectedIdentifiers($context = null)
|
||||
{
|
||||
if ($context === null) {
|
||||
throw new Exception\RuntimeException(
|
||||
'Expected context to be an array but is null'
|
||||
);
|
||||
}
|
||||
|
||||
$className = $this->objectRepository->getClassName();
|
||||
|
||||
if ($context instanceof $className) {
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierValues($context);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($this->getIdentifiers() as $identifierField) {
|
||||
if (! array_key_exists($identifierField, $context)) {
|
||||
throw new Exception\RuntimeException(\sprintf('Expected context to contain %s', $identifierField));
|
||||
}
|
||||
|
||||
$result[$identifierField] = $context[$identifierField];
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return array the names of the identifiers
|
||||
*/
|
||||
protected function getIdentifiers()
|
||||
{
|
||||
return $this->objectManager
|
||||
->getClassMetadata($this->objectRepository->getClassName())
|
||||
->getIdentifierFieldNames();
|
||||
}
|
||||
}
|
||||
52
test/AppTest/Handler/HomePageHandlerFactoryTest.php
Normal file
52
test/AppTest/Handler/HomePageHandlerFactoryTest.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AppTest\Handler;
|
||||
|
||||
use App\Handler\HomePageHandler;
|
||||
use App\Handler\HomePageHandlerFactory;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Zend\Expressive\Router\RouterInterface;
|
||||
use Zend\Expressive\Template\TemplateRendererInterface;
|
||||
|
||||
class HomePageHandlerFactoryTest extends TestCase
|
||||
{
|
||||
/** @var ContainerInterface|ObjectProphecy */
|
||||
protected $container;
|
||||
|
||||
protected function setUp()
|
||||
{
|
||||
$this->container = $this->prophesize(ContainerInterface::class);
|
||||
$router = $this->prophesize(RouterInterface::class);
|
||||
|
||||
$this->container->get(RouterInterface::class)->willReturn($router);
|
||||
}
|
||||
|
||||
public function testFactoryWithoutTemplate()
|
||||
{
|
||||
$factory = new HomePageHandlerFactory();
|
||||
$this->container->has(TemplateRendererInterface::class)->willReturn(false);
|
||||
|
||||
$this->assertInstanceOf(HomePageHandlerFactory::class, $factory);
|
||||
|
||||
$homePage = $factory($this->container->reveal(), null, get_class($this->container->reveal()));
|
||||
|
||||
$this->assertInstanceOf(HomePageHandler::class, $homePage);
|
||||
}
|
||||
|
||||
public function testFactoryWithTemplate()
|
||||
{
|
||||
$this->container->has(TemplateRendererInterface::class)->willReturn(true);
|
||||
$this->container
|
||||
->get(TemplateRendererInterface::class)
|
||||
->willReturn($this->prophesize(TemplateRendererInterface::class));
|
||||
|
||||
$factory = new HomePageHandlerFactory();
|
||||
|
||||
$homePage = $factory($this->container->reveal(), null, get_class($this->container->reveal()));
|
||||
|
||||
$this->assertInstanceOf(HomePageHandler::class, $homePage);
|
||||
}
|
||||
}
|
||||
64
test/AppTest/Handler/HomePageHandlerTest.php
Normal file
64
test/AppTest/Handler/HomePageHandlerTest.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AppTest\Handler;
|
||||
|
||||
use App\Handler\HomePageHandler;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Prophecy\Argument;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Zend\Diactoros\Response\HtmlResponse;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
use Zend\Expressive\Router\RouterInterface;
|
||||
use Zend\Expressive\Template\TemplateRendererInterface;
|
||||
|
||||
class HomePageHandlerTest extends TestCase
|
||||
{
|
||||
/** @var ContainerInterface|ObjectProphecy */
|
||||
protected $container;
|
||||
|
||||
/** @var RouterInterface|ObjectProphecy */
|
||||
protected $router;
|
||||
|
||||
protected function setUp()
|
||||
{
|
||||
$this->container = $this->prophesize(ContainerInterface::class);
|
||||
$this->router = $this->prophesize(RouterInterface::class);
|
||||
}
|
||||
|
||||
public function testReturnsJsonResponseWhenNoTemplateRendererProvided()
|
||||
{
|
||||
$homePage = new HomePageHandler(
|
||||
$this->router->reveal(),
|
||||
null,
|
||||
get_class($this->container->reveal())
|
||||
);
|
||||
$response = $homePage->handle(
|
||||
$this->prophesize(ServerRequestInterface::class)->reveal()
|
||||
);
|
||||
|
||||
$this->assertInstanceOf(JsonResponse::class, $response);
|
||||
}
|
||||
|
||||
public function testReturnsHtmlResponseWhenTemplateRendererProvided()
|
||||
{
|
||||
$renderer = $this->prophesize(TemplateRendererInterface::class);
|
||||
$renderer
|
||||
->render('app::home-page', Argument::type('array'))
|
||||
->willReturn('');
|
||||
|
||||
$homePage = new HomePageHandler(
|
||||
$this->router->reveal(),
|
||||
$renderer->reveal(),
|
||||
get_class($this->container->reveal())
|
||||
);
|
||||
|
||||
$response = $homePage->handle(
|
||||
$this->prophesize(ServerRequestInterface::class)->reveal()
|
||||
);
|
||||
|
||||
$this->assertInstanceOf(HtmlResponse::class, $response);
|
||||
}
|
||||
}
|
||||
26
test/AppTest/Handler/PingHandlerTest.php
Normal file
26
test/AppTest/Handler/PingHandlerTest.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace AppTest\Handler;
|
||||
|
||||
use App\Handler\PingHandler;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class PingHandlerTest extends TestCase
|
||||
{
|
||||
public function testResponse()
|
||||
{
|
||||
$pingHandler = new PingHandler();
|
||||
$response = $pingHandler->handle(
|
||||
$this->prophesize(ServerRequestInterface::class)->reveal()
|
||||
);
|
||||
|
||||
$json = json_decode((string) $response->getBody());
|
||||
|
||||
$this->assertInstanceOf(JsonResponse::class, $response);
|
||||
$this->assertTrue(isset($json->ack));
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user