feat : init project Coltura (CRM/ERP)

Symfony 8 + API Platform 4 + Nuxt 4 monorepo.
Backend: User entity, JWT auth, fixtures.
Frontend: login, dashboard, auth middleware, i18n, @malio/layer-ui.
Docker: dev (ports 8083/3003/5436) + prod multi-stage.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matthieu
2026-04-07 10:56:57 +02:00
commit 4c9040c923
70 changed files with 2464 additions and 0 deletions

21
.env Normal file
View File

@@ -0,0 +1,21 @@
APP_ENV=dev
APP_SECRET="change_me_in_env_local"
APP_DEBUG=1
DEFAULT_URI=http://localhost/
###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN='^https?://(localhost|127.0.0.1)(:[0-9]+)?$'
###< nelmio/cors-bundle ###
###> lexik/jwt-authentication-bundle ###
JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pem
JWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pem
JWT_PASSPHRASE=change_me_in_env_local
JWT_COOKIE_SECURE=0
JWT_TOKEN_TTL=86400
JWT_COOKIE_TTL=86400
###< lexik/jwt-authentication-bundle ###
DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:${POSTGRES_PORT}/${POSTGRES_DB}?serverVersion=16&charset=utf8"

38
.gitignore vendored Normal file
View File

@@ -0,0 +1,38 @@
###> symfony/framework-bundle ###
/.env.local
/.env.local.php
/.env.*.local
/config/secrets/dev/dev.decrypt.private.php
/public/bundles/
/var/
/vendor/
###< symfony/framework-bundle ###
###> phpunit/phpunit ###
/phpunit.xml
.phpunit.result.cache
.phpunit.cache
###< phpunit/phpunit ###
###> php-cs-fixer ###
.php-cs-fixer.cache
###< php-cs-fixer ###
###> lexik/jwt-authentication-bundle ###
/config/jwt/*.pem
###< lexik/jwt-authentication-bundle ###
###> frontend ###
frontend/node_modules/
frontend/.nuxt/
frontend/.output/
frontend/dist/
###< frontend ###
###> docker ###
infra/dev/.env.docker.local
###< docker ###
###> logs ###
LOG/
###< logs ###

56
.php-cs-fixer.dist.php Normal file
View File

@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
$finder = Finder::create()
->in('src')
->notName('Kernel.php')
;
$rules = [
'@Symfony' => true,
'@PSR12' => true,
'@PHP84Migration' => true,
'@PER-CS' => true,
'@PhpCsFixer' => true,
'strict_param' => true,
'strict_comparison' => true,
'no_useless_else' => true,
'no_useless_return' => true,
'binary_operator_spaces' => [
'operators' => [
'=' => 'align_single_space_minimal',
'||' => 'align_single_space_minimal',
'=>' => 'align_single_space_minimal',
],
],
'global_namespace_import' => [
'import_classes' => true,
'import_constants' => true,
'import_functions' => true,
],
'modernize_strpos' => true,
'no_superfluous_phpdoc_tags' => true,
'echo_tag_syntax' => true,
'semicolon_after_instruction' => true,
'combine_consecutive_unsets' => true,
'ternary_to_null_coalescing' => true,
'declare_strict_types' => true,
'operator_linebreak' => [
'position' => 'beginning',
],
'no_unused_imports' => true,
'single_line_throw' => false,
'php_unit_test_class_requires_covers' => false,
];
$config = new Config();
return $config
->setRiskyAllowed(true)
->setRules($rules)
->setFinder($finder)
;

114
CLAUDE.md Normal file
View File

@@ -0,0 +1,114 @@
# Coltura
CRM/ERP. Monorepo Symfony 8 (API Platform 4) + Nuxt 4.
## Stack
- **Backend** : PHP 8.4, Symfony 8.0, API Platform 4, Doctrine ORM, PostgreSQL 16
- **Frontend** : Nuxt 4 (SSR off / SPA), Vue 3, Pinia, Tailwind CSS, @malio/layer-ui, nuxt-toast, @nuxtjs/i18n, @nuxt/icon
- **Auth** : JWT HTTP-only cookie (lexik/jwt-authentication-bundle), login a `/login_check`, cookie `BEARER`
- **Docker** : PHP-FPM + Node 24, Nginx (port 8083), PostgreSQL (port 5436)
## Structure
```
src/Entity/ # Entites Doctrine (User)
src/ApiResource/ # Ressources API Platform decouples (AppVersion)
src/State/ # Providers et Processors API Platform (MeProvider, AppVersionProvider, UserPasswordHasherProcessor)
src/Service/ # Services metier
src/Repository/ # Repositories Doctrine
src/DataFixtures/ # Fixtures
config/ # Config Symfony (security, api_platform, lexik_jwt, nelmio_cors, doctrine)
config/jwt/ # Cles JWT (private.pem, public.pem)
migrations/ # Migrations Doctrine
infra/dev/ # Config Docker dev (Dockerfile, nginx, php.ini, xdebug)
infra/prod/ # Config Docker prod (Dockerfile multi-stage, nginx, php-prod.ini)
frontend/ # App Nuxt 4
frontend/pages/ # Pages (index, login)
frontend/layouts/ # Layouts (default)
frontend/components/ # Composants Vue
frontend/composables/# Composables (useApi, useAppVersion)
frontend/stores/ # Stores Pinia (auth, ui)
frontend/services/ # Services API (auth)
frontend/services/dto/ # Types TypeScript
frontend/i18n/locales/ # Fichiers de traduction
```
## Commandes
```bash
make start # Demarrer les containers
make stop # Arreter les containers
make restart # Redemarrer les containers
make install # Install complet (composer, migrations, fixtures, build Nuxt)
make reset # Tout supprimer et reinstaller (supprime la BDD)
make dev-nuxt # Dev server Nuxt (hot reload, port 3003)
make shell # Shell dans le container PHP
make shell-root # Shell root dans le container PHP
make cache-clear # Vider le cache Symfony
make migration-migrate # Lancer les migrations
make fixtures # Charger les fixtures
make db-reset # Reset BDD + migrations + fixtures
make test # PHPUnit
make php-cs-fixer-allow-risky # Fix code style PHP
make logs-dev # Tail logs Symfony
```
## Conventions
### Commits
Format : `<type>(<scope optionnel>) : <message>` (espace avant et apres `:`)
Types autorises (minuscules) : `build`, `chore`, `ci`, `docs`, `feat`, `fix`, `perf`, `refactor`, `revert`, `style`, `test`
Exemples : `feat : add login page`, `fix(auth) : prevent null token crash`
### Tags & Versioning
- La version de l'app est dans `config/version.yaml` (parametre `app.version`)
- A chaque creation de tag, **toujours** mettre a jour `config/version.yaml` avec la meme version
- Faire un commit separe de bump : `chore : bump version to v<X.Y.Z>`
- Puis creer le tag et pusher : `git tag v<X.Y.Z> && git push origin develop --tags`
### Backend
- Toujours `declare(strict_types=1)` en haut des fichiers PHP
- API Platform : utiliser ApiResource, Providers (`src/State/`), Processors — pas de controllers
- Routes API prefixees `/api` (via `config/routes/api_platform.yaml`)
- Le login (`/login_check`) est hors prefix `/api`, nginx reecrit `REQUEST_URI` vers `/login_check`
- PHP CS Fixer : regles Symfony + PSR-12 + strict types
- Roles : `ROLE_ADMIN`, `ROLE_USER` — hierarchie dans `security.yaml`
- PostgreSQL : noms de colonnes toujours en **minuscules** dans le SQL brut
- Controllers custom sous `/api/` : ajouter `priority: 1` sur `#[Route]` pour eviter le conflit avec API Platform `{id}`
- Serialization : pour embarquer une relation (pas IRI), ajouter le groupe du parent aux proprietes de l'entite cible
- Upload fichiers : utiliser `$file->getMimeType()` (pas `getClientMimeType()`) pour valider cote serveur
### Frontend
- TypeScript strict
- Composable `useApi()` pour tous les appels API (gere cookies, erreurs, toasts, i18n)
- Stores Pinia : `useAuthStore` (auth), `useUiStore` (ui)
- Middleware global `auth.global.ts` protege les routes
- Traductions dans `frontend/i18n/locales/`
- 4 espaces d'indentation
### Nginx
- `/api/*` -> Symfony (via try_files + index.php)
- `/api/login_check` -> location exact match, fastcgi direct avec REQUEST_URI reecrit en `/login_check`
- `/` -> SPA frontend (`frontend/dist/`)
## Docker
- Container PHP : `php-coltura-fpm`
- Container Nginx : `nginx-coltura`
- Container DB : PostgreSQL sur port **5436** (interne et externe)
- Config Docker dev : `infra/dev/.env.docker` (override local : `infra/dev/.env.docker.local`)
- Config Docker prod : `infra/prod/` (Dockerfile multi-stage, docker-compose.prod.yml)
- Apres modif nginx : `docker restart nginx-coltura`
## Fixtures
- User admin : `admin` / `admin` (ROLE_ADMIN)
- Users internes : `alice` / `alice`, `bob` / `bob` (ROLE_USER)

26
README.md Normal file
View File

@@ -0,0 +1,26 @@
# Coltura
CRM/ERP - Symfony 8 + API Platform 4 + Nuxt 4
## Quick Start
```bash
make start # Start Docker containers
make install # Install dependencies, run migrations, build frontend
```
Dev frontend: `make dev-nuxt` (hot reload on port 3003)
## Ports
| Service | Port |
|----------|------|
| API | 8083 |
| Frontend | 3003 |
| PostgreSQL | 5436 |
## Credentials (dev)
- admin / admin (ROLE_ADMIN)
- alice / alice (ROLE_USER)
- bob / bob (ROLE_USER)

21
bin/console Executable file
View File

@@ -0,0 +1,21 @@
#!/usr/bin/env php
<?php
use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;
if (!is_dir(dirname(__DIR__).'/vendor')) {
throw new LogicException('Dependencies are missing. Try running "composer install".');
}
if (!is_file(dirname(__DIR__).'/vendor/autoload_runtime.php')) {
throw new LogicException('Symfony Runtime is missing. Try running "composer require symfony/runtime".');
}
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
$kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
return new Application($kernel);
};

31
commit-msg Executable file
View File

@@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
MSG_FILE="${1}"
FIRST_LINE="$(head -n 1 "$MSG_FILE" | tr -d '\r')"
# Autoriser commits auto-générés par git
if [[ "$FIRST_LINE" =~ ^Merge\ ]]; then
exit 0
fi
# Types autorisés (MINUSCULES uniquement)
# Optionnel: scope => feat(auth) : ...
REGEX='^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([a-z0-9._-]+\))?\ :\ .+'
if [[ ! "$FIRST_LINE" =~ $REGEX ]]; then
echo "❌ Message de commit invalide."
echo ""
echo "➡️ Format attendu : <type>(<scope optionnel>) : <message>"
echo "➡️ Types autorisés (minuscules uniquement) :"
echo " build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test"
echo ""
echo "✅ Exemples :"
echo " feat : add login page"
echo " fix(auth) : prevent null token crash"
echo " docs : update README"
echo ""
echo "❌ Exemple refusé :"
echo " Feat : add login page"
exit 1
fi

95
composer.json Normal file
View File

@@ -0,0 +1,95 @@
{
"type": "project",
"license": "proprietary",
"minimum-stability": "stable",
"prefer-stable": true,
"require": {
"php": ">=8.4",
"ext-ctype": "*",
"ext-iconv": "*",
"api-platform/doctrine-orm": "^4.2",
"api-platform/symfony": "^4.2",
"doctrine/doctrine-bundle": "^3.2",
"doctrine/doctrine-migrations-bundle": "^4.0",
"doctrine/orm": "^3.6",
"lexik/jwt-authentication-bundle": "^3.2",
"nelmio/cors-bundle": "^2.6",
"nyholm/psr7": "^1.8",
"phpdocumentor/reflection-docblock": "^5.6|^6.0",
"phpstan/phpdoc-parser": "^2.3",
"symfony/asset": "8.0.*",
"symfony/console": "8.0.*",
"symfony/dotenv": "8.0.*",
"symfony/expression-language": "8.0.*",
"symfony/flex": "^2",
"symfony/framework-bundle": "8.0.*",
"symfony/http-client": "8.0.*",
"symfony/mime": "8.0.*",
"symfony/monolog-bundle": "^4.0",
"symfony/property-access": "8.0.*",
"symfony/property-info": "8.0.*",
"symfony/rate-limiter": "8.0.*",
"symfony/runtime": "8.0.*",
"symfony/security-bundle": "8.0.*",
"symfony/serializer": "8.0.*",
"symfony/validator": "8.0.*",
"symfony/yaml": "8.0.*"
},
"config": {
"allow-plugins": {
"php-http/discovery": true,
"symfony/flex": true,
"symfony/runtime": true
},
"bump-after-update": true,
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"replace": {
"symfony/polyfill-ctype": "*",
"symfony/polyfill-iconv": "*",
"symfony/polyfill-php72": "*",
"symfony/polyfill-php73": "*",
"symfony/polyfill-php74": "*",
"symfony/polyfill-php80": "*",
"symfony/polyfill-php81": "*",
"symfony/polyfill-php82": "*",
"symfony/polyfill-php83": "*",
"symfony/polyfill-php84": "*"
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install %PUBLIC_DIR%": "symfony-cmd"
},
"post-install-cmd": [
"@auto-scripts"
],
"post-update-cmd": [
"@auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*"
},
"extra": {
"symfony": {
"allow-contrib": false,
"require": "8.0.*"
}
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^4.3",
"friendsofphp/php-cs-fixer": "^3.94",
"phpunit/phpunit": "^13.0"
}
}

25
config/bundles.php Normal file
View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
use ApiPlatform\Symfony\Bundle\ApiPlatformBundle;
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle;
use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
use Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle;
use Nelmio\CorsBundle\NelmioCorsBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\MonologBundle\MonologBundle;
use Symfony\Bundle\SecurityBundle\SecurityBundle;
return [
FrameworkBundle::class => ['all' => true],
SecurityBundle::class => ['all' => true],
DoctrineBundle::class => ['all' => true],
DoctrineMigrationsBundle::class => ['all' => true],
NelmioCorsBundle::class => ['all' => true],
ApiPlatformBundle::class => ['all' => true],
DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
LexikJWTAuthenticationBundle::class => ['all' => true],
MonologBundle::class => ['all' => true],
];

View File

@@ -0,0 +1,12 @@
api_platform:
title: Coltura API
version: 1.0.0
formats:
jsonld: ['application/ld+json']
json: ['application/json']
patch_formats:
json: ['application/merge-patch+json']
defaults:
stateless: true
cache_headers:
vary: ['Content-Type', 'Authorization', 'Origin']

View File

@@ -0,0 +1,7 @@
framework:
cache:
#prefix_seed: your_vendor_name/app_name
# Redis
#app: cache.adapter.redis
#default_redis_provider: redis://localhost

View File

@@ -0,0 +1,42 @@
doctrine:
dbal:
url: '%env(resolve:DATABASE_URL)%'
profiling_collect_backtrace: '%kernel.debug%'
orm:
validate_xml_mapping: true
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
identity_generation_preferences:
Doctrine\DBAL\Platforms\PostgreSQLPlatform: identity
auto_mapping: true
mappings:
App:
type: attribute
is_bundle: false
dir: '%kernel.project_dir%/src/Entity'
prefix: 'App\Entity'
alias: App
controller_resolver:
auto_mapping: false
when@test:
doctrine:
dbal:
dbname_suffix: '_test%env(default::TEST_TOKEN)%'
when@prod:
doctrine:
orm:
query_cache_driver:
type: pool
pool: doctrine.system_cache_pool
result_cache_driver:
type: pool
pool: doctrine.result_cache_pool
framework:
cache:
pools:
doctrine.result_cache_pool:
adapter: cache.app
doctrine.system_cache_pool:
adapter: cache.system

View File

@@ -0,0 +1,4 @@
doctrine_migrations:
migrations_paths:
'DoctrineMigrations': '%kernel.project_dir%/migrations'
enable_profiler: false

View File

@@ -0,0 +1,12 @@
# see https://symfony.com/doc/current/reference/configuration/framework.html
framework:
secret: '%env(APP_SECRET)%'
# Note that the session will be started ONLY if you read or write from it.
session: true
when@test:
framework:
test: true
session:
storage_factory_id: session.storage.factory.mock_file

View File

@@ -0,0 +1,10 @@
services:
Psr\Http\Message\RequestFactoryInterface: '@http_discovery.psr17_factory'
Psr\Http\Message\ResponseFactoryInterface: '@http_discovery.psr17_factory'
Psr\Http\Message\ServerRequestFactoryInterface: '@http_discovery.psr17_factory'
Psr\Http\Message\StreamFactoryInterface: '@http_discovery.psr17_factory'
Psr\Http\Message\UploadedFileFactoryInterface: '@http_discovery.psr17_factory'
Psr\Http\Message\UriFactoryInterface: '@http_discovery.psr17_factory'
http_discovery.psr17_factory:
class: Http\Discovery\Psr17Factory

View File

@@ -0,0 +1,25 @@
lexik_jwt_authentication:
secret_key: '%env(resolve:JWT_SECRET_KEY)%'
public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
pass_phrase: '%env(JWT_PASSPHRASE)%'
token_ttl: '%env(int:JWT_TOKEN_TTL)%'
remove_token_from_body_when_cookies_used: true
token_extractors:
authorization_header:
enabled: false
cookie:
enabled: true
name: BEARER
query_parameter:
enabled: false
set_cookies:
BEARER:
lifetime: '%env(int:JWT_COOKIE_TTL)%'
samesite: lax
path: /
secure: '%env(bool:JWT_COOKIE_SECURE)%'
httpOnly: true
api_platform:
check_path: /api/login_check
username_path: username
password_path: password

View File

@@ -0,0 +1,56 @@
monolog:
channels:
- deprecation
when@dev:
monolog:
handlers:
main:
type: rotating_file
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
max_files: 7
channels: ["!event"]
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine", "!console"]
when@test:
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
channels: ["!event"]
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
when@prod:
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
channels: ["!deprecation"]
buffer_size: 50
nested:
type: rotating_file
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
max_files: 30
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine"]
deprecation:
type: rotating_file
channels: [deprecation]
path: "%kernel.logs_dir%/deprecations.log"
max_files: 7

View File

@@ -0,0 +1,11 @@
nelmio_cors:
defaults:
origin_regex: true
allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
allow_credentials: true
allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
allow_headers: ['Content-Type', 'Authorization']
expose_headers: ['Link']
max_age: 3600
paths:
'^/': null

View File

@@ -0,0 +1,3 @@
framework:
property_info:
with_constructor_extractor: true

View File

@@ -0,0 +1,8 @@
framework:
router:
default_uri: '%env(DEFAULT_URI)%'
when@prod:
framework:
router:
strict_requirements: null

View File

@@ -0,0 +1,57 @@
security:
role_hierarchy:
ROLE_ADMIN: [ROLE_USER]
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
providers:
app_user_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_profiler|_wdt|assets|build)/
security: false
login:
pattern: ^/login_check
stateless: true
provider: app_user_provider
login_throttling:
max_attempts: 5
interval: '1 minute'
json_login:
check_path: /login_check
username_path: username
password_path: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
provider: app_user_provider
jwt: ~
logout:
path: /api/logout
target: /login
enable_csrf: false
delete_cookies:
BEARER:
path: /
access_control:
- { path: ^/login_check, roles: PUBLIC_ACCESS }
- { path: ^/api/docs, roles: PUBLIC_ACCESS }
- { path: ^/api/version, roles: PUBLIC_ACCESS, methods: [ GET ] }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
when@test:
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto
cost: 4
time_cost: 3
memory_cost: 10

View File

@@ -0,0 +1,9 @@
framework:
validation:
#auto_mapping:
# App\Entity\: []
when@test:
framework:
validation:
not_compromised_password: false

7
config/preload.php Normal file
View File

@@ -0,0 +1,7 @@
<?php
declare(strict_types=1);
if (file_exists(dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__).'/var/cache/prod/App_KernelProdContainer.preload.php';
}

4
config/routes.yaml Normal file
View File

@@ -0,0 +1,4 @@
# yaml-language-server: $schema=../vendor/symfony/routing/Loader/schema/routing.schema.json
controllers:
resource: routing.controllers

View File

@@ -0,0 +1,4 @@
api_platform:
resource: .
type: api_platform
prefix: /api

17
config/services.yaml Normal file
View File

@@ -0,0 +1,17 @@
# yaml-language-server: $schema=../vendor/symfony/dependency-injection/Loader/schema/services.schema.json
parameters:
imports:
- { resource: version.yaml }
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'

2
config/version.yaml Normal file
View File

@@ -0,0 +1,2 @@
parameters:
app.version: '0.1.0'

60
docker-compose.yml Normal file
View File

@@ -0,0 +1,60 @@
services:
php:
container_name: php-${DOCKER_APP_NAME}-fpm
build:
context: ./infra/dev
dockerfile: Dockerfile
args:
DOCKER_PHP_VERSION: ${DOCKER_PHP_VERSION}
DOCKER_NODE_VERSION: ${DOCKER_NODE_VERSION}
CURRENT_UID: ${CURRENT_UID}
CURRENT_GID: ${CURRENT_GID}
environment:
PHP_IDE_CONFIG: serverName=${DOCKER_APP_NAME}-docker
XDEBUG_CLIENT_HOST: ${XDEBUG_CLIENT_HOST:-host.docker.internal}
XDEBUG_CONFIG: client_host=${XDEBUG_CLIENT_HOST:-host.docker.internal} client_port=9003
DATABASE_URL: "postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:${POSTGRES_PORT}/${POSTGRES_DB}?serverVersion=16&charset=utf8"
COMPOSER_HOME: /tmp/composer
COMPOSER_CACHE_DIR: /tmp/composer/cache
volumes:
- ./:/var/www/html
- ~/.cache:/var/www/.cache
- ~/.config:/var/www/.config
- ~/.composer:/var/www/.composer
- ./infra/dev/php.ini:/usr/local/etc/php/php.ini
- ./infra/dev/xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
- ./LOG:/var/www/html/LOG
- uploads_data:/var/www/html/var/uploads
extra_hosts:
- "host.docker.internal:host-gateway"
depends_on:
- db
ports:
- "3003:3003"
restart: unless-stopped
nginx:
image: nginx:1.27-alpine
container_name: nginx-${DOCKER_APP_NAME}
depends_on:
- php
ports:
- "8083:80"
volumes:
- ./:/var/www/html:ro
- ./infra/dev/nginx.conf:/etc/nginx/conf.d/coltura.conf:ro
restart: unless-stopped
db:
image: postgres:16-alpine
command: -p ${POSTGRES_PORT:-5436}
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- pg_data:/var/lib/postgresql/data
ports:
- "${POSTGRES_PORT:-5436}:${POSTGRES_PORT:-5436}"
restart: unless-stopped
volumes:
pg_data:
uploads_data:

13
frontend/app.vue Normal file
View File

@@ -0,0 +1,13 @@
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
<script setup lang="ts">
const { load } = useAppVersion()
onMounted(() => {
load()
})
</script>

View File

@@ -0,0 +1 @@
/* Coltura - Custom styles */

View File

@@ -0,0 +1,206 @@
import type { FetchOptions } from 'ofetch'
import { $fetch, FetchError } from 'ofetch'
import { useAuthStore } from '~/stores/auth'
export type AnyObject = Record<string, unknown>
export type ApiClient = {
get<T>(url: string, query?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
post<T>(url: string, body?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
put<T>(url: string, body?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
patch<T>(url: string, body?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
delete<T>(url: string, query?: AnyObject, options?: ApiFetchOptions<'json'>): Promise<T>
}
export type ApiFetchOptions<ResponseType extends 'json' | 'blob'> =
FetchOptions<ResponseType> & {
toast?: boolean
toastOn401?: boolean
toastTitle?: string
toastErrorMessage?: string
toastSuccessMessage?: string
toastErrorKey?: string
toastSuccessKey?: string
}
let isHandlingUnauthorized = false
export function useApi(): ApiClient {
const config = useRuntimeConfig()
const baseURL = config.public.apiBase || '/api'
const toast = useToast()
const auth = useAuthStore()
const nuxtApp = useNuxtApp()
const i18n = nuxtApp.$i18n as
| {
t: (key: string) => string
te?: (key: string) => boolean
}
| undefined
const t = (key: string) => (i18n?.t ? String(i18n.t(key)) : key)
const te = (key: string) => (i18n?.te ? i18n.te(key) : false)
function extractErrorMessage(error: unknown, responseData?: unknown): string {
const data = responseData ?? (error as FetchError)?.data
if (typeof data === 'string') {
return data
}
if (data && typeof data === 'object') {
const record = data as Record<string, unknown>
return (
(record['hydra:description'] as string) ||
(record.detail as string) ||
(record.message as string) ||
(record.error as string) ||
(record.title as string) ||
(record['hydra:title'] as string) ||
''
)
}
return (error as FetchError)?.message ?? 'Erreur inconnue.'
}
const methodErrorKeys: Record<string, string> = {
GET: 'errors.http.get',
POST: 'errors.http.post',
PUT: 'errors.http.put',
PATCH: 'errors.http.patch',
DELETE: 'errors.http.delete'
}
const client = $fetch.create({
baseURL,
retry: 0,
credentials: 'include',
onResponse({ options, response }) {
const apiOptions = options as ApiFetchOptions<'json'>
if (apiOptions?.toast === false) {
return
}
if (response?.status && response.status >= 400) {
return
}
const successKey = apiOptions?.toastSuccessKey
const successMessage =
apiOptions?.toastSuccessMessage ||
(successKey ? (te(successKey) ? t(successKey) : successKey) : '')
if (successMessage) {
toast.success({
title: 'Succes',
message: successMessage
})
}
},
async onResponseError({ response, error, options }) {
const apiOptions = options as ApiFetchOptions<'json'>
if (response?.status === 401) {
const requestUrl = typeof options?.url === 'string' ? options.url : ''
const isLoginCheck = requestUrl.includes('/login_check')
const isLogout = requestUrl.includes('/logout')
const shouldToast401 = apiOptions?.toastOn401 === true && apiOptions?.toast !== false
if (shouldToast401) {
const errorKey = apiOptions?.toastErrorKey
const errorMessage =
errorKey ? (te(errorKey) ? t(errorKey) : errorKey) : ''
const extractedMessage = extractErrorMessage(error, response?._data)
const message =
apiOptions?.toastErrorMessage ||
errorMessage ||
extractedMessage ||
'Une erreur est survenue.'
toast.error({
title: apiOptions?.toastTitle ?? 'Erreur',
message
})
}
if (!isLoginCheck && !isLogout) {
if (!isHandlingUnauthorized) {
isHandlingUnauthorized = true
auth.clearSession()
const route = useRoute()
if (route.path !== '/login') {
await navigateTo('/login')
}
isHandlingUnauthorized = false
}
}
return
}
if (apiOptions?.toast === false) {
return
}
const method =
typeof options?.method === 'string' ? options.method.toUpperCase() : 'GET'
const defaultKey = methodErrorKeys[method]
const defaultMessage =
defaultKey && te(defaultKey) ? t(defaultKey) : ''
const errorKey = apiOptions?.toastErrorKey
const errorMessage =
errorKey ? (te(errorKey) ? t(errorKey) : errorKey) : ''
const extractedMessage = extractErrorMessage(error, response?._data)
const message =
apiOptions?.toastErrorMessage ||
errorMessage ||
defaultMessage ||
extractedMessage ||
'Une erreur est survenue.'
toast.error({
title: apiOptions?.toastTitle ?? 'Erreur',
message
})
}
})
function request<T>(
method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE',
url: string,
options: ApiFetchOptions<'json'> = {}
) {
const needsJsonBody = method === 'POST' || method === 'PUT'
const needsMergePatch = method === 'PATCH'
const isFormData = typeof FormData !== 'undefined' && options.body instanceof FormData
const headers = new Headers(options.headers as HeadersInit | undefined)
if (!isFormData) {
if (needsMergePatch && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/merge-patch+json')
} else if (needsJsonBody && !headers.has('Content-Type')) {
headers.set('Content-Type', 'application/json')
}
}
return client<T>(url, { ...options, method, headers })
}
return {
get<T>(url: string, query: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
return request<T>('GET', url, { ...options, query })
},
post<T>(url: string, body: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
return request<T>('POST', url, { ...options, body })
},
put<T>(url: string, body: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
return request<T>('PUT', url, { ...options, body })
},
patch<T>(url: string, body: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
return request<T>('PATCH', url, { ...options, body })
},
delete<T>(url: string, query: AnyObject = {}, options: ApiFetchOptions<'json'> = {}) {
return request<T>('DELETE', url, { ...options, query })
}
}
}

View File

@@ -0,0 +1,15 @@
const version = ref('')
export function useAppVersion() {
async function load() {
try {
const api = useApi()
const data = await api.get<{ version: string }>('/version', {}, { toast: false })
version.value = data.version
} catch {
version.value = '?'
}
}
return { version, load }
}

5
frontend/i18n.config.ts Normal file
View File

@@ -0,0 +1,5 @@
export default defineI18nConfig(() => ({
legacy: false,
locale: 'fr',
fallbackLocale: 'fr',
}))

View File

@@ -0,0 +1,48 @@
{
"common": {
"loading": "Chargement...",
"save": "Enregistrer",
"cancel": "Annuler",
"delete": "Supprimer",
"edit": "Modifier",
"create": "Creer",
"search": "Rechercher",
"confirm": "Confirmer",
"yes": "Oui",
"no": "Non",
"actions": "Actions"
},
"nav": {
"dashboard": "Tableau de bord",
"admin": "Administration"
},
"dashboard": {
"title": "Tableau de bord",
"welcome": "Bienvenue sur Coltura"
},
"auth": {
"login": "Connexion",
"logout": "Deconnexion",
"username": "Nom d'utilisateur",
"password": "Mot de passe"
},
"errors": {
"auth": {
"login": "Identifiants invalides",
"session": "Session expir\u00e9e",
"logout": "Erreur lors de la deconnexion"
},
"http": {
"get": "Erreur lors du chargement",
"post": "Erreur lors de la creation",
"put": "Erreur lors de la mise a jour",
"patch": "Erreur lors de la modification",
"delete": "Erreur lors de la suppression"
}
},
"success": {
"auth": {
"logout": "Deconnexion reussie"
}
}
}

View File

@@ -0,0 +1,111 @@
<template>
<div class="h-screen overflow-hidden">
<div class="flex h-full">
<!-- Mobile sidebar overlay -->
<Transition name="sidebar-overlay">
<div
v-if="ui.sidebarOpen"
class="fixed inset-0 z-40 bg-black/50 lg:hidden"
@click="ui.closeMobileSidebar()"
/>
</Transition>
<aside
class="fixed inset-y-0 left-0 z-50 flex h-full flex-shrink-0 flex-col border-r border-neutral-200 bg-tertiary-500 transition-transform duration-300 lg:static lg:z-auto lg:translate-x-0"
:class="[
ui.sidebarCollapsed ? 'lg:w-16' : 'lg:w-64',
ui.sidebarOpen ? 'w-64 translate-x-0' : '-translate-x-full',
]"
>
<div class="flex items-center overflow-hidden" :class="sidebarIsCollapsed ? 'justify-center p-3' : 'justify-between'">
<span v-if="!sidebarIsCollapsed" class="px-4 py-3 text-lg font-bold text-white">
Coltura
</span>
<span v-else class="px-2 py-3 text-sm font-bold text-white">
C
</span>
<button
class="mr-2 rounded-md p-2 text-neutral-500 hover:bg-neutral-200 hover:text-neutral-700 transition-colors lg:hidden"
@click="ui.closeMobileSidebar()"
>
<Icon name="mdi:close" size="20" />
</button>
</div>
<nav class="flex-1 overflow-hidden" :class="sidebarIsCollapsed ? 'px-1 pb-6' : 'px-4 pb-6'">
<SidebarLink
to="/"
icon="mdi:view-dashboard-outline"
:label="$t('nav.dashboard')"
:collapsed="sidebarIsCollapsed"
:class="sidebarIsCollapsed ? 'mt-4' : 'border-t border-secondary-500 pt-6'"
@click="ui.closeMobileSidebar()"
/>
<SidebarLink
to="/admin"
icon="mdi:cog-outline"
:label="$t('nav.admin')"
:collapsed="sidebarIsCollapsed"
@click="ui.closeMobileSidebar()"
/>
</nav>
<div class="flex items-center justify-center p-4">
<p v-if="!sidebarIsCollapsed" class="font-bold text-white">v {{ version }}</p>
</div>
<!-- Collapse toggle button -->
<button
class="absolute top-1/2 -right-4 z-10 hidden h-8 w-8 -translate-y-1/2 items-center justify-center rounded-full border border-neutral-200 bg-white text-neutral-400 shadow-sm hover:text-neutral-700 transition-colors lg:flex"
:title="ui.sidebarCollapsed ? 'Ouvrir le menu' : 'Reduire le menu'"
@click="ui.toggleSidebar()"
>
<Icon
:name="ui.sidebarCollapsed ? 'mdi:chevron-right' : 'mdi:chevron-left'"
size="18"
/>
</button>
</aside>
<div class="h-full flex-1 flex flex-col min-h-0 min-w-0">
<AppTopNav :user="auth.user" />
<main class="flex flex-1 flex-col overflow-y-auto overflow-x-hidden bg-white px-4 pb-24 sm:px-8 lg:px-16">
<div aria-hidden="true" class="pointer-events-none sticky top-0 z-30 h-8 flex-shrink-0 bg-white sm:h-12" />
<slot/>
</main>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { useAppVersion } from '~/composables/useAppVersion'
const auth = useAuthStore()
const ui = useUiStore()
const {version} = useAppVersion()
const route = useRoute()
const sidebarIsCollapsed = computed(() => {
if (ui.sidebarOpen) return false
return ui.sidebarCollapsed
})
watch(() => route.path, () => {
ui.closeMobileSidebar()
})
useHead({
titleTemplate: (title) => title || 'Coltura',
})
</script>
<style scoped>
.sidebar-overlay-enter-active,
.sidebar-overlay-leave-active {
transition: opacity 0.3s ease;
}
.sidebar-overlay-enter-from,
.sidebar-overlay-leave-to {
opacity: 0;
}
</style>

View File

@@ -0,0 +1,16 @@
export default defineNuxtRouteMiddleware(async (to) => {
const auth = useAuthStore()
const isLogin = to.path === '/login'
if (!auth.checked) {
await auth.ensureSession()
}
if (!isLogin && !auth.isAuthenticated) {
return navigateTo('/login')
}
if (isLogin && auth.isAuthenticated) {
return navigateTo('/')
}
})

59
frontend/nuxt.config.ts Normal file
View File

@@ -0,0 +1,59 @@
export default defineNuxtConfig({
compatibilityDate: '2025-07-15',
devtools: {enabled: false},
ssr: false,
css: ['~/assets/css/main.css'],
app: {
baseURL: process.env.NODE_ENV === 'production'
? (process.env.NUXT_PUBLIC_APP_BASE || '/')
: '/'
},
extends: ['@malio/layer-ui'],
modules: [
'@nuxtjs/tailwindcss',
'@pinia/nuxt',
'nuxt-toast',
'@nuxtjs/i18n',
'@nuxt/icon',
],
runtimeConfig: {
public: {
apiBase: process.env.NUXT_PUBLIC_API_BASE
}
},
devServer: {
port: 3003,
},
components: [
{path: '~/components', pathPrefix: false},
],
vite: {
server: {
allowedHosts: true,
proxy: {
'/api': {
target: 'http://nginx',
changeOrigin: true,
},
},
},
},
toast: {
settings: {
timeout: 2000,
closeOnClick: true,
progressBar: false
}
},
i18n: {
strategy: 'no_prefix',
defaultLocale: 'fr',
langDir: 'locales',
locales: [
{code: 'fr', file: 'fr.json', name: 'Français'}
],
},
typescript: {
strict: true
},
})

25
frontend/package.json Normal file
View File

@@ -0,0 +1,25 @@
{
"name": "coltura-frontend",
"type": "module",
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"build:dist": "nuxt generate && rm -rf dist && cp -R .output/public dist"
},
"dependencies": {
"@malio/layer-ui": "^1.2.0",
"@nuxt/icon": "^2.2.1",
"@nuxtjs/i18n": "^10.2.3",
"@nuxtjs/tailwindcss": "^6.14.0",
"@pinia/nuxt": "^0.11.3",
"nuxt": "^4.3.1",
"nuxt-toast": "^1.4.0",
"pinia": "^3.0.4",
"vue": "^3.5.29",
"vue-router": "^4.6.4"
}
}

12
frontend/pages/index.vue Normal file
View File

@@ -0,0 +1,12 @@
<template>
<div>
<h1 class="text-xl font-bold text-primary-500 sm:text-2xl">{{ $t('dashboard.title') }}</h1>
<p class="mt-4 text-neutral-500">{{ $t('dashboard.welcome') }}</p>
</div>
</template>
<script setup lang="ts">
const { t } = useI18n()
useHead({ title: t('dashboard.title') })
</script>

68
frontend/pages/login.vue Normal file
View File

@@ -0,0 +1,68 @@
<template>
<div class="mx-auto w-full max-w-lg">
<span
class="flex items-center justify-center bg-white text-xl font-bold uppercase text-primary-500 p-4"
>
<img src="/coltura.png" alt="Logo" class="w-[150px]"/>
</span>
<form
class="mt-8 space-y-6 rounded-lg border border-neutral-200 bg-white p-6 shadow-sm"
@submit.prevent="handleSubmit"
>
<MalioInputText
label="Nom d'utilisateur"
autocomplete="username"
group-class="mt-0"
inputClass="w-full"
v-model="username"
/>
<div>
<label class="text-sm font-semibold text-neutral-700" for="password">
Mot de passe
</label>
<input
id="password"
v-model="password"
type="password"
autocomplete="current-password"
class="mt-2 w-full rounded-md border border-neutral-300 bg-white px-3 py-2 text-base text-neutral-900 focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-secondary-500/20"
/>
</div>
<MalioButton
label="Se connecter"
button-class="w-full"
:disabled="isSubmitting"
@click="handleSubmit"
/>
<p class="font-bold">v{{ version }}</p>
</form>
</div>
</template>
<script setup lang="ts">
definePageMeta({layout: 'auth'})
useHead({
title: 'Connexion'
})
const auth = useAuthStore()
const {version} = useAppVersion()
const username = ref('')
const password = ref('')
const isSubmitting = ref(false)
async function handleSubmit() {
if (isSubmitting.value) return
isSubmitting.value = true
try {
await auth.login(username.value, password.value)
await navigateTo('/')
} finally {
isSubmitting.value = false
}
}
</script>

22
frontend/services/auth.ts Normal file
View File

@@ -0,0 +1,22 @@
import type { UserData } from './dto/user-data'
export function getCurrentUser() {
const api = useApi()
return api.get<UserData>('/me', {}, { toastErrorKey: 'errors.auth.session' })
}
export function login(username: string, password: string) {
const api = useApi()
return api.post('/login_check', { username, password }, {
toastOn401: true,
toastErrorKey: 'errors.auth.login'
})
}
export function logout() {
const api = useApi()
return api.post('/logout', {}, {
toastErrorKey: 'errors.auth.logout',
toastSuccessKey: 'success.auth.logout'
})
}

View File

@@ -0,0 +1,5 @@
export interface UserData {
id: number
username: string
roles: string[]
}

71
frontend/stores/auth.ts Normal file
View File

@@ -0,0 +1,71 @@
import { defineStore } from 'pinia'
import type { UserData } from '~/services/dto/user-data'
import { getCurrentUser, login, logout } from '~/services/auth'
export const useAuthStore = defineStore('auth', {
state: () => ({
user: null as UserData | null,
isLoading: false,
checked: false
}),
getters: {
isAuthenticated: (state) => Boolean(state.user)
},
actions: {
clearSession() {
this.user = null
this.checked = true
this.isLoading = false
},
async ensureSession() {
if (this.checked) {
return this.user
}
this.checked = true
try {
const me = await getCurrentUser()
this.user = me
return me
} catch {
this.user = null
return null
}
},
async login(username: string, password: string) {
this.isLoading = true
try {
await login(username, password)
const me = await getCurrentUser()
this.user = me
this.checked = true
return me
} finally {
this.isLoading = false
}
},
async logout() {
this.isLoading = true
try {
await logout()
} catch {
// Ignore logout errors so we can still clear local auth state.
} finally {
this.user = null
this.checked = true
this.isLoading = false
}
},
async refreshUser() {
try {
const me = await getCurrentUser()
this.user = me
} catch {
// Silently fail — user session might have expired
}
}
}
})

19
frontend/stores/ui.ts Normal file
View File

@@ -0,0 +1,19 @@
import { defineStore } from 'pinia'
export const useUiStore = defineStore('ui', {
state: () => ({
sidebarCollapsed: false,
sidebarOpen: false,
}),
actions: {
toggleSidebar() {
this.sidebarCollapsed = !this.sidebarCollapsed
},
openMobileSidebar() {
this.sidebarOpen = true
},
closeMobileSidebar() {
this.sidebarOpen = false
},
},
})

View File

@@ -0,0 +1,12 @@
import type { Config } from 'tailwindcss'
export default <Partial<Config>>{
content: [
'./components/**/*.{vue,js,ts}',
'./layouts/**/*.vue',
'./pages/**/*.vue',
'./composables/**/*.{js,ts}',
'./plugins/**/*.{js,ts}',
'./app.vue',
],
}

17
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"files": [],
"references": [
{
"path": "./.nuxt/tsconfig.app.json"
},
{
"path": "./.nuxt/tsconfig.server.json"
},
{
"path": "./.nuxt/tsconfig.shared.json"
},
{
"path": "./.nuxt/tsconfig.node.json"
}
]
}

8
frontend/utils/api.ts Normal file
View File

@@ -0,0 +1,8 @@
export interface HydraCollection<T> {
'hydra:member': T[]
'hydra:totalItems': number
}
export function extractHydraMembers<T>(collection: HydraCollection<T>): T[] {
return collection['hydra:member'] ?? []
}

9
infra/dev/.env.docker Normal file
View File

@@ -0,0 +1,9 @@
DOCKER_APP_NAME=coltura
DOCKER_PHP_VERSION=8.4.6
DOCKER_NODE_VERSION=24.12.0
APP_USER=www-data
POSTGRES_DB=coltura
POSTGRES_USER=root
POSTGRES_PASSWORD=root
POSTGRES_PORT=5436
XDEBUG_CLIENT_HOST=host.docker.internal

102
infra/dev/Dockerfile Normal file
View File

@@ -0,0 +1,102 @@
ARG DOCKER_PHP_VERSION
FROM php:${DOCKER_PHP_VERSION}-fpm-bullseye
ARG DOCKER_NODE_VERSION
ENV DOCKER_NODE_VERSION="${DOCKER_NODE_VERSION}"
# Installer les dépendances et extensions PHP nécessaires
RUN apt-get update && apt-get install -y \
libicu-dev \
libpq-dev \
libpng-dev \
libzip-dev \
libxml2-dev \
ca-certificates \
gnupg \
libbz2-dev \
libgmp-dev \
libldap2-dev \
libonig-dev \
libsodium-dev \
libxslt1-dev \
unixodbc-dev \
libsqlite3-dev \
zlib1g-dev \
libssl-dev \
libc-client-dev \
libkrb5-dev \
freetds-dev \
vim \
tcpdump \
dnsutils \
wget \
git \
unzip \
&& docker-php-ext-install -j$(nproc) \
intl \
zip \
bcmath \
bz2 \
calendar \
exif \
gd \
gettext \
gmp \
ldap \
pcntl \
pdo_pgsql \
soap \
sockets \
sysvsem \
xsl
# Installation de node
RUN wget -qO- "https://nodejs.org/dist/v${DOCKER_NODE_VERSION}/node-v${DOCKER_NODE_VERSION}-linux-x64.tar.xz" | tar xJC /tmp/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/bin /usr/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/include /usr/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/lib /usr/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/share /usr/ && \
npm install --global yarn
# installation/activation d'extensions php
RUN pecl install xdebug
RUN docker-php-ext-enable xdebug && \
docker-php-ext-install zip && \
docker-php-ext-install gd && \
docker-php-ext-install soap && \
docker-php-ext-configure intl && \
docker-php-ext-install intl
RUN docker-php-ext-enable opcache
# installation de composer
RUN rm -rf /var/cache/apk/* && rm -rf /tmp/* && \
curl --insecure https://getcomposer.org/composer.phar -o /usr/bin/composer && chmod +x /usr/bin/composer
# cache Composer pour www-data
RUN mkdir -p /var/www/.composer/cache/vcs \
&& chown -R www-data:www-data /var/www/.composer
ENV COMPOSER_HOME=/var/www/.composer
# Création de la structure du projet
RUN mkdir /var/www/html/LOG
###> User ###
ARG CURRENT_UID
ARG CURRENT_GID
# mapping du user host avec www-data
RUN usermod -o -u ${CURRENT_UID} www-data && groupmod -o -g ${CURRENT_GID} www-data
RUN chown www-data:www-data -R /var/www/*
RUN chown www-data:www-data -R /var/www/.*
###< User ###
RUN rm -rf \
/var/lib/apt/lists/* \
/tmp/* \
/var/tmp/*
WORKDIR /var/www/html
EXPOSE 80

54
infra/dev/nginx.conf Normal file
View File

@@ -0,0 +1,54 @@
server {
listen 80;
server_name localhost;
root /var/www/html/frontend/dist;
index index.html;
client_max_body_size 55m;
location ^~ /api/ {
root /var/www/html/public;
try_files $uri /index.php?$query_string;
}
location ^~ /_wdt/ {
root /var/www/html/public;
try_files $uri /index.php?$query_string;
}
location ^~ /_profiler/ {
root /var/www/html/public;
try_files $uri /index.php?$query_string;
}
location ^~ /bundles/ {
root /var/www/html/public;
try_files $uri =404;
}
location = /api/login_check {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
fastcgi_param DOCUMENT_ROOT /var/www/html/public;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param PATH_INFO /login_check;
fastcgi_param REQUEST_URI /login_check;
fastcgi_pass php:9000;
}
location ~ ^/index\.php(/|$) {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
fastcgi_param DOCUMENT_ROOT /var/www/html/public;
fastcgi_pass php:9000;
}
location ~ \.php$ {
return 404;
}
location / {
try_files $uri $uri/ /index.html;
}
}

8
infra/dev/php.ini Normal file
View File

@@ -0,0 +1,8 @@
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Europe/Paris
[Upload]
upload_max_filesize = 50M
post_max_size = 55M

9
infra/dev/xdebug.ini Normal file
View File

@@ -0,0 +1,9 @@
zend_extension = /usr/local/lib/php/extensions/no-debug-non-zts-20240924/xdebug.so
xdebug.mode=debug
xdebug.idekey=PHPSTORM
xdebug.start_with_request=yes
xdebug.discover_client_host=1
xdebug.client_port=9003
xdebug.log="/var/www/html/LOG/xdebug.log"
xdebug.log_level=0
xdebug.connect_timeout_ms=2

View File

@@ -0,0 +1,16 @@
APP_ENV=prod
APP_DEBUG=0
APP_SECRET=CHANGE_ME_IN_PRODUCTION
POSTGRES_DB=coltura
POSTGRES_USER=coltura
POSTGRES_PASSWORD=CHANGE_ME_IN_PRODUCTION
APP_PORT=80
JWT_PASSPHRASE=CHANGE_ME_IN_PRODUCTION
JWT_COOKIE_SECURE=1
JWT_TOKEN_TTL=86400
JWT_COOKIE_TTL=86400
CORS_ALLOW_ORIGIN='^https://coltura\.malio-dev\.fr$'

86
infra/prod/Dockerfile Normal file
View File

@@ -0,0 +1,86 @@
ARG DOCKER_PHP_VERSION=8.4.6
FROM php:${DOCKER_PHP_VERSION}-fpm-bullseye AS php-base
ARG DOCKER_NODE_VERSION=24.12.0
ENV DOCKER_NODE_VERSION="${DOCKER_NODE_VERSION}"
# Installer les dépendances et extensions PHP nécessaires
RUN apt-get update && apt-get install -y \
libicu-dev \
libpq-dev \
libpng-dev \
libzip-dev \
libxml2-dev \
ca-certificates \
gnupg \
libbz2-dev \
libgmp-dev \
libldap2-dev \
libonig-dev \
libsodium-dev \
libxslt1-dev \
zlib1g-dev \
libssl-dev \
wget \
git \
unzip \
&& docker-php-ext-install -j$(nproc) \
intl \
zip \
bcmath \
bz2 \
calendar \
exif \
gd \
gettext \
gmp \
ldap \
pcntl \
pdo_pgsql \
soap \
sockets \
sysvsem \
xsl \
&& docker-php-ext-enable opcache \
&& rm -rf /var/lib/apt/lists/* /tmp/*
# Installation de node
RUN wget -qO- "https://nodejs.org/dist/v${DOCKER_NODE_VERSION}/node-v${DOCKER_NODE_VERSION}-linux-x64.tar.xz" | tar xJC /tmp/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/bin /usr/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/include /usr/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/lib /usr/ && \
cp -r /tmp/node-v${DOCKER_NODE_VERSION}-linux-x64/share /usr/ && \
rm -rf /tmp/*
# Installation de composer
RUN curl --insecure https://getcomposer.org/composer.phar -o /usr/bin/composer && chmod +x /usr/bin/composer
WORKDIR /var/www/html
# Copier les fichiers projet
COPY . /var/www/html
# Installation des dépendances PHP (prod)
RUN composer install --no-dev --optimize-autoloader --no-interaction
# Génération des clés JWT si absentes
RUN php bin/console lexik:jwt:generate-keypair --skip-if-exists
# Build du frontend
RUN cd frontend && npm ci && npm run build:dist && rm -rf node_modules
# Permissions
RUN chown -R www-data:www-data /var/www/html/var /var/www/html/frontend/dist
# PHP prod config
COPY infra/deploy/php-prod.ini /usr/local/etc/php/php.ini
EXPOSE 9000
# ── Nginx stage ──
FROM nginx:1.27-alpine AS nginx
COPY infra/deploy/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=php-base /var/www/html/public /var/www/html/public
COPY --from=php-base /var/www/html/frontend/dist /var/www/html/frontend/dist

View File

@@ -0,0 +1,42 @@
services:
php:
container_name: php-coltura-fpm
build:
context: ../../
dockerfile: infra/deploy/Dockerfile
target: php-base
environment:
APP_ENV: prod
APP_DEBUG: 0
DATABASE_URL: "postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?serverVersion=16&charset=utf8"
volumes:
- uploads_data:/var/www/html/var/uploads
depends_on:
- db
restart: unless-stopped
nginx:
container_name: nginx-coltura
build:
context: ../../
dockerfile: infra/deploy/Dockerfile
target: nginx
depends_on:
- php
ports:
- "${APP_PORT:-80}:80"
restart: unless-stopped
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- pg_data:/var/lib/postgresql/data
restart: unless-stopped
volumes:
pg_data:
uploads_data:

44
infra/prod/nginx.conf Normal file
View File

@@ -0,0 +1,44 @@
server {
listen 80;
server_name _;
root /var/www/html/frontend/dist;
index index.html;
client_max_body_size 55m;
location ^~ /api/ {
root /var/www/html/public;
try_files $uri /index.php?$query_string;
}
location = /api/login_check {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
fastcgi_param DOCUMENT_ROOT /var/www/html/public;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param PATH_INFO /login_check;
fastcgi_param REQUEST_URI /login_check;
fastcgi_pass php:9000;
}
location ^~ /bundles/ {
root /var/www/html/public;
try_files $uri =404;
}
location ~ ^/index\.php(/|$) {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /var/www/html/public/index.php;
fastcgi_param DOCUMENT_ROOT /var/www/html/public;
fastcgi_pass php:9000;
}
location ~ \.php$ {
return 404;
}
location / {
try_files $uri $uri/ /index.html;
}
}

18
infra/prod/php-prod.ini Normal file
View File

@@ -0,0 +1,18 @@
[Date]
date.timezone = Europe/Paris
[Upload]
upload_max_filesize = 50M
post_max_size = 55M
[opcache]
opcache.enable = 1
opcache.memory_consumption = 256
opcache.max_accelerated_files = 20000
opcache.validate_timestamps = 0
opcache.preload = /var/www/html/config/preload.php
opcache.preload_user = www-data
[Performance]
realpath_cache_size = 4096K
realpath_cache_ttl = 600

125
makefile Normal file
View File

@@ -0,0 +1,125 @@
# Permet d'utiliser un .env.docker.local pour override
ENV_DEFAULT = infra/dev/.env.docker
ENV_LOCAL = infra/dev/.env.docker.local
ENV_FILE := $(if $(wildcard $(ENV_LOCAL)),$(ENV_LOCAL),$(ENV_DEFAULT))
# Permet d'avoir les variables du fichier .env.docker.local
include $(ENV_DEFAULT)
-include $(ENV_LOCAL)
PHP_CONTAINER = php-$(DOCKER_APP_NAME)-fpm
SYMFONY_CONSOLE = $(EXEC_PHP) php bin/console
DOCKER_COMPOSE = docker compose --env-file $(ENV_FILE)
DOCKER = docker
EXEC_PHP = $(DOCKER) exec -t -u $(APP_USER) $(PHP_CONTAINER)
EXEC_PHP_CS_FIXER = $(EXEC_PHP) php vendor/bin/php-cs-fixer
EXEC_PHP_ROOT = $(DOCKER) exec -t -u root $(PHP_CONTAINER)
EXEC_PHP_INTERACTIVE = $(DOCKER) exec -it -u $(APP_USER) $(PHP_CONTAINER)
EXEC_PHP_INTERACTIVE_ROOT = $(DOCKER) exec -it -u root $(PHP_CONTAINER)
FILES =
#========================================================================================
env-init:
@cp --update=none $(ENV_DEFAULT) $(ENV_LOCAL)
# Lance le container
start: env-init
@echo "**** START CONTAINERS ****"
CURRENT_UID=$(shell id -u) CURRENT_GID=$(shell id -g) $(DOCKER_COMPOSE) up -d
# Éteint le container
stop:
$(DOCKER_COMPOSE) stop
restart: env-init
$(DOCKER_COMPOSE) down
CURRENT_UID=$(shell id -u) CURRENT_GID=$(shell id -g) $(DOCKER_COMPOSE) up -d
install: copy-git-hook composer-install cache-clear node-use build-nuxtJS migration-migrate
# Supprime tout est réinstalle tout (Attention ça supprime la bdd aussi)
reset: delete_built_dir remove_orphans build-without-cache start wait install
composer-install:
$(EXEC_PHP) composer install
$(SYMFONY_CONSOLE) lexik:jwt:generate-keypair --skip-if-exists
build-nuxtJS:
$(EXEC_PHP) sh -lc "cd frontend && npm install && npm run build:dist"
dev-nuxt:
$(EXEC_PHP) sh -c "cd frontend && npm run dev"
delete_built_dir:
CURRENT_UID=$(shell id -u) CURRENT_GID=$(shell id -g) $(DOCKER_COMPOSE) up -d
$(DOCKER) exec -u root $(PHP_CONTAINER) rm -rf vendor/
$(DOCKER) exec -u root $(PHP_CONTAINER) rm -rf frontend/node_modules
remove_orphans:
$(DOCKER_COMPOSE) kill
$(DOCKER_COMPOSE) down --volumes --remove-orphans
build-without-cache:
$(DOCKER_COMPOSE) build \
--build-arg="DOCKER_PHP_VERSION=$(DOCKER_PHP_VERSION)" \
--build-arg="DOCKER_NODE_VERSION=$(DOCKER_NODE_VERSION)" \
--build-arg="CURRENT_UID=$(shell id -u)" \
--build-arg="CURRENT_GID=$(shell id -g)" \
--no-cache
migration-migrate:
$(SYMFONY_CONSOLE) doctrine:migrations:migrate --no-interaction
fixtures:
$(SYMFONY_CONSOLE) --no-interaction doctrine:fixtures:load
# Attention, supprime votre bdd local
db-reset:
$(DOCKER_COMPOSE) down -v
$(DOCKER_COMPOSE) up -d
$(MAKE) wait
$(SYMFONY_CONSOLE) doctrine:database:create --if-not-exists
$(MAKE) migration-migrate
$(MAKE) fixtures
# Restart la bdd
db-restart:
$(DOCKER_COMPOSE) down
$(DOCKER_COMPOSE) up -d
cache-clear:
$(SYMFONY_CONSOLE) cache:clear
copy-git-hook:
$(EXEC_PHP) cp pre-commit .git/hooks/
$(EXEC_PHP) cp commit-msg .git/hooks/
$(EXEC_PHP) chmod a+x .git/hooks/pre-commit
$(EXEC_PHP) chmod a+x .git/hooks/commit-msg
shell:
$(EXEC_PHP_INTERACTIVE) bash
shell-root:
$(EXEC_PHP_INTERACTIVE_ROOT) bash
# Suivi temps réel des logs dev
logs-dev:
$(EXEC_PHP_INTERACTIVE) sh -lc "tail -f var/log/dev.log"
# Force la version node
node-use:
bash -lc 'source "$$HOME/.nvm/nvm.sh" && nvm install && nvm use'
# Utilisé par le pre-commit pour fix les fichiers modifiés
php-cs-fixer-allow-risky:
@echo "Fixing files: $(FILES)"
$(EXEC_PHP_CS_FIXER) fix --config=.php-cs-fixer.dist.php --allow-risky=yes $(FILES)
test:
$(EXEC_PHP) php -d memory_limit="512M" vendor/bin/phpunit $(FILES)
wait:
sleep 10

44
phpunit.dist.xml Normal file
View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
colors="true"
failOnDeprecation="true"
failOnNotice="true"
failOnWarning="true"
bootstrap="tests/bootstrap.php"
cacheDirectory=".phpunit.cache"
>
<php>
<ini name="display_errors" value="1" />
<ini name="error_reporting" value="-1" />
<server name="APP_ENV" value="test" force="true" />
<server name="SHELL_VERBOSITY" value="-1" />
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<source ignoreSuppressionOfDeprecations="true"
ignoreIndirectDeprecations="true"
restrictNotices="true"
restrictWarnings="true"
>
<include>
<directory>src</directory>
</include>
<deprecationTrigger>
<method>Doctrine\Deprecations\Deprecation::trigger</method>
<method>Doctrine\Deprecations\Deprecation::delegateTriggerToBackend</method>
<function>trigger_deprecation</function>
</deprecationTrigger>
</source>
<extensions>
</extensions>
</phpunit>

38
pre-commit Executable file
View File

@@ -0,0 +1,38 @@
#!/bin/sh
echo "######### Pre-commit hook start #############"
echo "--- php-cs-fixer pre commit hook start ---"
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.php$')
# Vérifier s'il y a des fichiers PHP modifiés
if [ -n "$FILES" ]; then
echo "Running PHP CS Fixer on staged PHP files..."
# Convertir la liste des fichiers en une chaîne séparée par des espaces
FILES_LIST=""
for FILE in $FILES; do
FILES_LIST="$FILES_LIST $FILE"
done
# Exécuter la cible make pour PHP CS Fixer
make php-cs-fixer-allow-risky FILES="$FILES_LIST"
# Ajouter les fichiers corrigés au commit
git add $FILES
else
echo "No PHP files to fix."
fi
echo "--- php-cs-fixer pre commit hook finish---"
echo "--- phpunit pre commit hook start ---"
make test
PHPUNIT_RESULT=$?
if [ $PHPUNIT_RESULT -ne 0 ]; then
echo "PHPUnit tests failed. Aborting commit."
exit 1
fi
echo "--- phpunit pre commit hook finished ---"
echo "All checks passed. Proceeding with commit."
exit 0

11
public/index.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};

View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\ApiResource;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use App\State\AppVersionProvider;
#[ApiResource(
operations: [
new Get(
uriTemplate: '/version',
provider: AppVersionProvider::class,
),
],
)]
class AppVersion
{
public function __construct(
public readonly string $version,
) {}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\DataFixtures;
use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class AppFixtures extends Fixture
{
public function __construct(
private readonly UserPasswordHasherInterface $passwordHasher,
) {}
public function load(ObjectManager $manager): void
{
$admin = new User();
$admin->setUsername('admin');
$admin->setRoles(['ROLE_ADMIN']);
$admin->setPassword($this->passwordHasher->hashPassword($admin, 'admin'));
$manager->persist($admin);
$alice = new User();
$alice->setUsername('alice');
$alice->setRoles(['ROLE_USER']);
$alice->setPassword($this->passwordHasher->hashPassword($alice, 'alice'));
$manager->persist($alice);
$bob = new User();
$bob->setUsername('bob');
$bob->setRoles(['ROLE_USER']);
$bob->setPassword($this->passwordHasher->hashPassword($bob, 'bob'));
$manager->persist($bob);
$manager->flush();
}
}

153
src/Entity/User.php Normal file
View File

@@ -0,0 +1,153 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use App\Repository\UserRepository;
use App\State\MeProvider;
use App\State\UserPasswordHasherProcessor;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Attribute\Groups;
#[ApiResource(
operations: [
new Get(
uriTemplate: '/me',
provider: MeProvider::class,
normalizationContext: ['groups' => ['me:read']],
),
new Get(
normalizationContext: ['groups' => ['user:list']],
),
new GetCollection(
normalizationContext: ['groups' => ['user:list']],
),
new Post(security: "is_granted('ROLE_ADMIN')", processor: UserPasswordHasherProcessor::class),
new Patch(security: "is_granted('ROLE_ADMIN')", processor: UserPasswordHasherProcessor::class),
new Delete(security: "is_granted('ROLE_ADMIN')"),
],
denormalizationContext: ['groups' => ['user:write']],
)]
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: '`user`')]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['me:read', 'user:list'])]
private ?int $id = null;
#[ORM\Column(length: 180, unique: true)]
#[Groups(['me:read', 'user:list', 'user:write'])]
private ?string $username = null;
/** @var list<string> */
#[ORM\Column]
#[Groups(['me:read', 'user:list', 'user:write'])]
private array $roles = [];
#[ORM\Column]
private ?string $password = null;
#[Groups(['user:write'])]
private ?string $plainPassword = null;
#[ORM\Column(type: 'datetime_immutable')]
private ?DateTimeImmutable $createdAt = null;
public function __construct()
{
$this->createdAt = new DateTimeImmutable();
}
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): static
{
$this->username = $username;
return $this;
}
public function getUserIdentifier(): string
{
return (string) $this->username;
}
/** @return list<string> */
public function getRoles(): array
{
$roles = $this->roles;
$roles[] = 'ROLE_USER';
return array_values(array_unique($roles));
}
/** @param list<string> $roles */
public function setRoles(array $roles): static
{
$this->roles = $roles;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): static
{
$this->password = $password;
return $this;
}
public function getCreatedAt(): ?DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(DateTimeImmutable $createdAt): static
{
$this->createdAt = $createdAt;
return $this;
}
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(?string $plainPassword): static
{
$this->plainPassword = $plainPassword;
return $this;
}
public function eraseCredentials(): void
{
$this->plainPassword = null;
}
}

13
src/Kernel.php Normal file
View File

@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
}

View File

@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Repository;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<User>
*/
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
}

View File

@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/**
* @implements ProviderInterface<object>
*/
class AppVersionProvider implements ProviderInterface
{
public function __construct(
#[Autowire(param: 'app.version')]
private readonly string $appVersion,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object
{
return new \App\ApiResource\AppVersion($this->appVersion);
}
}

24
src/State/MeProvider.php Normal file
View File

@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use Symfony\Bundle\SecurityBundle\Security;
/**
* @implements ProviderInterface<\App\Entity\User>
*/
class MeProvider implements ProviderInterface
{
public function __construct(
private readonly Security $security,
) {}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): ?object
{
return $this->security->getUser();
}
}

View File

@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\User;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
/**
* @implements ProcessorInterface<User, User>
*/
class UserPasswordHasherProcessor implements ProcessorInterface
{
public function __construct(
/** @var ProcessorInterface<User, User> */
private readonly ProcessorInterface $persistProcessor,
private readonly UserPasswordHasherInterface $passwordHasher,
) {}
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
if ($data instanceof User && null !== $data->getPlainPassword()) {
$data->setPassword(
$this->passwordHasher->hashPassword($data, $data->getPlainPassword())
);
$data->eraseCredentials();
}
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
}
}

15
tests/bootstrap.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
use Symfony\Component\Dotenv\Dotenv;
require dirname(__DIR__).'/vendor/autoload.php';
if (method_exists(Dotenv::class, 'bootEnv')) {
new Dotenv()->bootEnv(dirname(__DIR__).'/.env');
}
if ($_SERVER['APP_DEBUG']) {
umask(0o000);
}