changement vers springboot

master
Maxime ROCHER 3 weeks ago
parent b6ddc8d42d
commit ca0f1509a7

8
.idea/.gitignore vendored

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="WF-WEBAPI" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="WF-WEBAPI" options="-parameters" />
</option>
</component>
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/WF-WEBAPI/src/main/java" charset="UTF-8" />
</component>
</project>

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/WF-WEBAPI/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_23" default="true" project-jdk-name="openjdk-23" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/WF-WEB-API.iml" filepath="$PROJECT_DIR$/.idea/WF-WEB-API.iml" />
</modules>
</component>
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

@ -1,2 +0,0 @@
# WF-WEB-API

@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

@ -0,0 +1,19 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

@ -0,0 +1,13 @@
# Étape de build
FROM maven:3.8.6-openjdk-21 AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests
# Étape d'exécution
FROM openjdk:21-jdk
WORKDIR /app
COPY --from=build /app/target/demo-1.0.0.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

@ -0,0 +1,14 @@
kind: pipeline
type: docker
name: default
steps:
- name: build
image: maven:3.8.6-openjdk-21
commands:
- mvn clean package -DskipTests
- name: test
image: maven:3.8.6-openjdk-21
commands:
- mvn test

259
WF-WEBAPI/mvnw vendored

@ -0,0 +1,259 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

149
WF-WEBAPI/mvnw.cmd vendored

@ -0,0 +1,149 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>WF-WEBAPI</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>WF-WEBAPI</name>
<description>WF-WEBAPI</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,11 @@
package com.example.wfwebapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WfWebapiApplication {
public static void main(String[] args) {
SpringApplication.run(WfWebapiApplication.class, args);
}
}

@ -0,0 +1,18 @@
package com.example.wfwebapi.assembler;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import com.example.wfwebapi.controller.QuoteController;
import com.example.wfwebapi.model.Quote;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;
@Component
public class QuoteModelAssembler implements RepresentationModelAssembler<Quote, EntityModel<Quote>> {
@Override
public EntityModel<Quote> toModel(Quote quote) {
return EntityModel.of(quote,
linkTo(methodOn(QuoteController.class).getQuoteById(quote.getId())).withSelfRel(),
linkTo(methodOn(QuoteController.class).getAllQuotes(0, 10)).withRel("quotes"));
}
}

@ -0,0 +1,18 @@
package com.example.wfwebapi.assembler;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import com.example.wfwebapi.controller.UserController;
import com.example.wfwebapi.model.User;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;
@Component
public class UserModelAssembler implements RepresentationModelAssembler<User, EntityModel<User>> {
@Override
public EntityModel<User> toModel(User user) {
return EntityModel.of(user,
linkTo(methodOn(UserController.class).getUserById(user.getId())).withSelfRel(),
linkTo(methodOn(UserController.class).getAllUsers(0, 5)).withRel("users"));
}
}

@ -0,0 +1,33 @@
package com.example.wfwebapi.config;
import com.example.wfwebapi.security.JwtAuthenticationFilter;
import com.example.wfwebapi.security.JwtTokenProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityConfig {
private final JwtTokenProvider tokenProvider;
public SecurityConfig(JwtTokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/v1/auth/**").permitAll() // par exemple, pour la connexion
.anyRequest().authenticated()
)
.addFilterBefore(new JwtAuthenticationFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}

@ -0,0 +1,21 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Admin;
import com.example.wfwebapi.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/admin")
public class AdminController {
@Autowired
private AdminRepository adminRepository;
@GetMapping("/{userId}")
public Admin getAdmin(@PathVariable Long userId) {
return adminRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("Admin non trouvé pour l'utilisateur : " + userId));
}
}

@ -0,0 +1,48 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.model.User;
import com.example.wfwebapi.repository.UserRepository;
import com.example.wfwebapi.security.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
@Autowired
private UserRepository userRepository;
@Autowired
private JwtTokenProvider tokenProvider;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) {
User user = userRepository.findByUsername(authRequest.getUsername())
.orElseThrow(() -> new RuntimeException("Utilisateur non trouvé"));
if (!user.getPassword().equals(authRequest.getPassword())) {
return ResponseEntity.status(401).body("Mot de passe invalide");
}
String token = tokenProvider.createToken(user.getUsername());
return ResponseEntity.ok(new AuthResponse(token));
}
public static class AuthRequest {
private String username;
private String password;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
public static class AuthResponse {
private String token;
public AuthResponse(String token) { this.token = token; }
public String getToken() { return token; }
public void setToken(String token) { this.token = token; }
}
}

@ -0,0 +1,43 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Caracter;
import com.example.wfwebapi.repository.CaracterRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/caracter")
public class CaracterController {
@Autowired
private CaracterRepository caracterRepository;
@GetMapping("/{id}")
public Caracter getCaracterById(@PathVariable Long id) {
return caracterRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Caracter non trouvé : " + id));
}
@PostMapping
public Caracter createCaracter(@RequestBody Caracter caracter) {
return caracterRepository.save(caracter);
}
@PutMapping
public Caracter updateCaracter(@RequestBody Caracter updatedCaracter) {
return caracterRepository.findById(updatedCaracter.getId())
.map(c -> {
c.setCaracter(updatedCaracter.getCaracter());
c.setImage(updatedCaracter.getImage());
return caracterRepository.save(c);
}).orElseThrow(() -> new ResourceNotFoundException("Caracter non trouvé : " + updatedCaracter.getId()));
}
@DeleteMapping
public void deleteCaracter(@RequestParam Long id) {
if (!caracterRepository.existsById(id))
throw new ResourceNotFoundException("Caracter non trouvé : " + id);
caracterRepository.deleteById(id);
}
}

@ -0,0 +1,35 @@
package com.example.wfwebapi.controller;
import java.util.List;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Commentary;
import com.example.wfwebapi.repository.CommentaryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/commentary")
public class CommentaryController {
@Autowired
private CommentaryRepository commentaryRepository;
@GetMapping("/{quoteId}")
public List<Commentary> getCommentariesByQuote(@PathVariable Long quoteId) {
return commentaryRepository.findByQuote_Id(quoteId);
}
@PostMapping
public Commentary addCommentary(@RequestParam Long quote, @RequestBody Commentary commentary) {
commentary.setQuote(new com.example.wfwebapi.model.Quote() {{ setId(quote); }});
return commentaryRepository.save(commentary);
}
@DeleteMapping
public void deleteCommentariesByQuote(@RequestParam Long id) {
List<Commentary> comments = commentaryRepository.findByQuote_Id(id);
if(comments.isEmpty())
throw new ResourceNotFoundException("Aucun commentaire trouvé pour la citation " + id);
commentaryRepository.deleteAll(comments);
}
}

@ -0,0 +1,21 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.DailyQuote;
import com.example.wfwebapi.repository.DailyQuoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/dailyquote")
public class DailyQuoteController {
@Autowired
private DailyQuoteRepository dailyQuoteRepository;
@GetMapping
public DailyQuote getDailyQuote() {
return dailyQuoteRepository.findAll().stream().findFirst()
.orElseThrow(() -> new ResourceNotFoundException("Aucune DailyQuote définie"));
}
}

@ -0,0 +1,37 @@
package com.example.wfwebapi.controller;
import java.util.List;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Favorite;
import com.example.wfwebapi.model.FavoriteId;
import com.example.wfwebapi.repository.FavoriteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/favorite")
public class FavoriteController {
@Autowired
private FavoriteRepository favoriteRepository;
@GetMapping("/{userId}")
public List<Favorite> getFavoritesByUser(@PathVariable Long userId) {
return favoriteRepository.findByUser_Id(userId);
}
@PostMapping
public Favorite addFavorite(@RequestParam Long user, @RequestParam Long quote) {
Favorite favorite = new Favorite();
favorite.setId(new FavoriteId(user, quote));
return favoriteRepository.save(favorite);
}
@DeleteMapping
public void deleteFavorite(@RequestParam Long user, @RequestParam Long quote) {
FavoriteId id = new FavoriteId(user, quote);
if (!favoriteRepository.existsById(id))
throw new ResourceNotFoundException("Favorite non trouvée");
favoriteRepository.deleteById(id);
}
}

@ -0,0 +1,42 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Image;
import com.example.wfwebapi.repository.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/image")
public class ImageController {
@Autowired
private ImageRepository imageRepository;
@GetMapping("/{id}")
public Image getImageById(@PathVariable Long id) {
return imageRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Image non trouvée : " + id));
}
@PostMapping
public Image createImage(@RequestBody Image image) {
return imageRepository.save(image);
}
@PutMapping
public Image updateImage(@RequestBody Image updatedImage) {
return imageRepository.findById(updatedImage.getId())
.map(img -> {
img.setImgPath(updatedImage.getImgPath());
return imageRepository.save(img);
}).orElseThrow(() -> new ResourceNotFoundException("Image non trouvée : " + updatedImage.getId()));
}
@DeleteMapping
public void deleteImage(@RequestParam Long id) {
if (!imageRepository.existsById(id))
throw new ResourceNotFoundException("Image non trouvée : " + id);
imageRepository.deleteById(id);
}
}

@ -0,0 +1,47 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Question;
import com.example.wfwebapi.repository.QuestionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/question")
public class QuestionController {
@Autowired
private QuestionRepository questionRepository;
@GetMapping("/{id}")
public Question getQuestionById(@PathVariable Long id) {
return questionRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Question non trouvée : " + id));
}
@PostMapping
public Question createQuestion(@RequestBody Question question) {
return questionRepository.save(question);
}
@PutMapping
public Question updateQuestion(@RequestBody Question updatedQuestion) {
return questionRepository.findById(updatedQuestion.getId())
.map(q -> {
q.setTexte(updatedQuestion.getTexte());
q.setAnswerA(updatedQuestion.getAnswerA());
q.setAnswerB(updatedQuestion.getAnswerB());
q.setAnswerC(updatedQuestion.getAnswerC());
q.setAnswerD(updatedQuestion.getAnswerD());
q.setCAnswer(updatedQuestion.getCAnswer());
return questionRepository.save(q);
}).orElseThrow(() -> new ResourceNotFoundException("Question non trouvée : " + updatedQuestion.getId()));
}
@DeleteMapping
public void deleteQuestion(@RequestParam Long id) {
if (!questionRepository.existsById(id))
throw new ResourceNotFoundException("Question non trouvée : " + id);
questionRepository.deleteById(id);
}
}

@ -0,0 +1,50 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Quiz;
import com.example.wfwebapi.repository.QuizRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/v1/quiz")
public class QuizController {
@Autowired
private QuizRepository quizRepository;
@GetMapping
public List<Quiz> getAllQuiz() {
return quizRepository.findAll();
}
@GetMapping("/{id}")
public Quiz getQuizById(@PathVariable Long id) {
return quizRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Quiz non trouvé : " + id));
}
@PostMapping
public Quiz createQuiz(@RequestBody Quiz quiz) {
return quizRepository.save(quiz);
}
@PutMapping
public Quiz updateQuiz(@RequestBody Quiz updatedQuiz) {
return quizRepository.findById(updatedQuiz.getId())
.map(q -> {
q.setTitle(updatedQuiz.getTitle());
q.setImage(updatedQuiz.getImage());
return quizRepository.save(q);
}).orElseThrow(() -> new ResourceNotFoundException("Quiz non trouvé : " + updatedQuiz.getId()));
}
@DeleteMapping
public void deleteQuiz(@RequestParam Long id) {
if (!quizRepository.existsById(id))
throw new ResourceNotFoundException("Quiz non trouvé : " + id);
quizRepository.deleteById(id);
}
}

@ -0,0 +1,80 @@
package com.example.wfwebapi.controller;
import java.util.List;
import java.util.stream.Collectors;
import com.example.wfwebapi.assembler.QuoteModelAssembler;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Quote;
import com.example.wfwebapi.repository.QuoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/quote")
public class QuoteController {
@Autowired
private QuoteRepository quoteRepository;
@Autowired
private QuoteModelAssembler assembler;
@GetMapping("/{id}")
public EntityModel<Quote> getQuoteById(@PathVariable Long id) {
Quote quote = quoteRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Citation non trouvée : " + id));
return assembler.toModel(quote);
}
@GetMapping("/all")
public CollectionModel<EntityModel<Quote>> getAllQuotes(@RequestParam int index, @RequestParam int count) {
List<EntityModel<Quote>> quotes = quoteRepository.findAll(PageRequest.of(index, count))
.stream().map(assembler::toModel)
.collect(Collectors.toList());
return CollectionModel.of(quotes);
}
@GetMapping("/dailyquote")
public EntityModel<Quote> getDailyQuote(@RequestParam int year, @RequestParam int month,
@RequestParam int day, @RequestParam String lang) {
// Exemple : renvoi la première citation correspondant à la langue
Quote quote = quoteRepository.findAll().stream()
.filter(q -> q.getLangue().equalsIgnoreCase(lang))
.findFirst()
.orElseThrow(() -> new ResourceNotFoundException("Aucune citation trouvée pour la langue " + lang));
return assembler.toModel(quote);
}
@PostMapping
public EntityModel<Quote> createQuote(@RequestBody Quote newQuote) {
Quote quote = quoteRepository.save(newQuote);
return assembler.toModel(quote);
}
@PutMapping
public EntityModel<Quote> updateQuote(@RequestBody Quote updatedQuote) {
Quote quote = quoteRepository.findById(updatedQuote.getId())
.map(q -> {
q.setContent(updatedQuote.getContent());
q.setLangue(updatedQuote.getLangue());
q.setLikes(updatedQuote.getLikes());
q.setIsValide(updatedQuote.getIsValide());
q.setReason(updatedQuote.getReason());
q.setCaracter(updatedQuote.getCaracter());
q.setSource(updatedQuote.getSource());
q.setUserVerif(updatedQuote.getUserVerif());
return quoteRepository.save(q);
}).orElseThrow(() -> new ResourceNotFoundException("Citation non trouvée : " + updatedQuote.getId()));
return assembler.toModel(quote);
}
@DeleteMapping("/delete")
public void deleteQuote(@RequestParam Long idQuote) {
if (!quoteRepository.existsById(idQuote))
throw new ResourceNotFoundException("Citation non trouvée : " + idQuote);
quoteRepository.deleteById(idQuote);
}
}

@ -0,0 +1,44 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.RecordQuiz;
import com.example.wfwebapi.model.RecordQuizId;
import com.example.wfwebapi.repository.RecordQuizRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/recordquiz")
public class RecordQuizController {
@Autowired
private RecordQuizRepository recordQuizRepository;
@GetMapping
public RecordQuiz getRecord(@RequestParam Long user, @RequestParam Long quiz) {
RecordQuizId id = new RecordQuizId(user, quiz);
return recordQuizRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("RecordQuiz non trouvé"));
}
@PostMapping
public RecordQuiz createRecord(@RequestBody RecordQuiz recordQuiz) {
return recordQuizRepository.save(recordQuiz);
}
@PutMapping
public RecordQuiz updateRecord(@RequestBody RecordQuiz recordQuiz) {
RecordQuizId id = recordQuiz.getId();
if (!recordQuizRepository.existsById(id))
throw new ResourceNotFoundException("RecordQuiz non trouvé");
return recordQuizRepository.save(recordQuiz);
}
@DeleteMapping
public void deleteRecord(@RequestParam Long user, @RequestParam Long quiz) {
RecordQuizId id = new RecordQuizId(user, quiz);
if (!recordQuizRepository.existsById(id))
throw new ResourceNotFoundException("RecordQuiz non trouvé");
recordQuizRepository.deleteById(id);
}
}

@ -0,0 +1,43 @@
package com.example.wfwebapi.controller;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.Source;
import com.example.wfwebapi.repository.SourceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/source")
public class SourceController {
@Autowired
private SourceRepository sourceRepository;
@GetMapping("/{id}")
public Source getSourceById(@PathVariable Long id) {
return sourceRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Source non trouvée : " + id));
}
@PostMapping
public Source createSource(@RequestBody Source source) {
return sourceRepository.save(source);
}
@PutMapping
public Source updateSource(@RequestBody Source updatedSource) {
return sourceRepository.findById(updatedSource.getId())
.map(s -> {
s.setTitle(updatedSource.getTitle());
s.setDateS(updatedSource.getDateS());
return sourceRepository.save(s);
}).orElseThrow(() -> new ResourceNotFoundException("Source non trouvée : " + updatedSource.getId()));
}
@DeleteMapping
public void deleteSource(@RequestParam Long id) {
if (!sourceRepository.existsById(id))
throw new ResourceNotFoundException("Source non trouvée : " + id);
sourceRepository.deleteById(id);
}
}

@ -0,0 +1,71 @@
package com.example.wfwebapi.controller;
import java.util.List;
import java.util.stream.Collectors;
import com.example.wfwebapi.assembler.UserModelAssembler;
import com.example.wfwebapi.exception.ResourceNotFoundException;
import com.example.wfwebapi.model.User;
import com.example.wfwebapi.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private UserModelAssembler assembler;
// GET /api/v1/users/{id}
@GetMapping("/{id}")
public EntityModel<User> getUserById(@PathVariable Long id) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Utilisateur non trouvé : " + id));
return assembler.toModel(user);
}
// GET /api/v1/users/all?index=0&count=5
@GetMapping("/all")
public CollectionModel<EntityModel<User>> getAllUsers(@RequestParam int index, @RequestParam int count) {
List<EntityModel<User>> users = userRepository.findAll(PageRequest.of(index, count))
.stream().map(assembler::toModel)
.collect(Collectors.toList());
return CollectionModel.of(users);
}
// POST /api/v1/users
@PostMapping
public EntityModel<User> createUser(@RequestBody User newUser) {
User user = userRepository.save(newUser);
return assembler.toModel(user);
}
// PUT /api/v1/users?id=1
@PutMapping
public EntityModel<User> updateUser(@RequestParam Long id, @RequestBody User updatedUser) {
User user = userRepository.findById(id)
.map(u -> {
u.setUsername(updatedUser.getUsername());
u.setEmail(updatedUser.getEmail());
u.setPassword(updatedUser.getPassword());
u.setImage(updatedUser.getImage());
u.setCreation(updatedUser.getCreation());
return userRepository.save(u);
}).orElseThrow(() -> new ResourceNotFoundException("Utilisateur non trouvé : " + id));
return assembler.toModel(user);
}
// DELETE /api/v1/users?id=1
@DeleteMapping
public void deleteUser(@RequestParam Long id) {
if (!userRepository.existsById(id))
throw new ResourceNotFoundException("Utilisateur non trouvé : " + id);
userRepository.deleteById(id);
}
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.exception;
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.exception;
public class UnauthorizedException extends RuntimeException {
public UnauthorizedException(String message) {
super(message);
}
}

@ -0,0 +1,21 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Admin")
public class Admin {
@Id
@Column(name = "users")
private Long userId;
@OneToOne
@JoinColumn(name = "users", insertable = false, updatable = false)
private User user;
// Getters et setters
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
}

@ -0,0 +1,27 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Caracter")
public class Caracter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_caracter")
private Long id;
@Column(name = "caracter", nullable = false, length = 100)
private String caracter;
@ManyToOne
@JoinColumn(name = "id_img", nullable = false)
private Image image;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getCaracter() { return caracter; }
public void setCaracter(String caracter) { this.caracter = caracter; }
public Image getImage() { return image; }
public void setImage(Image image) { this.image = image; }
}

@ -0,0 +1,39 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
import java.time.LocalDate;
@Entity
@Table(name = "Commentary")
public class Commentary {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_comment")
private Long id;
@ManyToOne
@JoinColumn(name = "quote", nullable = false)
private Quote quote;
@ManyToOne
@JoinColumn(name = "users", nullable = false)
private User user;
@Column(name = "dateC", nullable = false)
private LocalDate dateC;
@Column(name = "comment", nullable = false, columnDefinition = "text")
private String comment;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Quote getQuote() { return quote; }
public void setQuote(Quote quote) { this.quote = quote; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public LocalDate getDateC() { return dateC; }
public void setDateC(LocalDate dateC) { this.dateC = dateC; }
public String getComment() { return comment; }
public void setComment(String comment) { this.comment = comment; }
}

@ -0,0 +1,21 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "DailyQuote")
public class DailyQuote {
@Id
@Column(name = "citation_id")
private Long citationId;
@OneToOne
@JoinColumn(name = "citation_id", insertable = false, updatable = false)
private Quote quote;
// Getters et setters
public Long getCitationId() { return citationId; }
public void setCitationId(Long citationId) { this.citationId = citationId; }
public Quote getQuote() { return quote; }
public void setQuote(Quote quote) { this.quote = quote; }
}

@ -0,0 +1,28 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Favorite")
public class Favorite {
@EmbeddedId
private FavoriteId id;
@ManyToOne
@MapsId("user")
@JoinColumn(name = "users")
private User user;
@ManyToOne
@MapsId("quote")
@JoinColumn(name = "quote")
private Quote quote;
// Getters et setters
public FavoriteId getId() { return id; }
public void setId(FavoriteId id) { this.id = id; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Quote getQuote() { return quote; }
public void setQuote(Quote quote) { this.quote = quote; }
}

@ -0,0 +1,37 @@
package com.example.wfwebapi.model;
import java.io.Serializable;
import java.util.Objects;
import jakarta.persistence.Embeddable;
@Embeddable
public class FavoriteId implements Serializable {
private Long user;
private Long quote;
public FavoriteId() {}
public FavoriteId(Long user, Long quote) {
this.user = user;
this.quote = quote;
}
public Long getUser() { return user; }
public void setUser(Long user) { this.user = user; }
public Long getQuote() { return quote; }
public void setQuote(Long quote) { this.quote = quote; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FavoriteId)) return false;
FavoriteId that = (FavoriteId) o;
return Objects.equals(getUser(), that.getUser()) &&
Objects.equals(getQuote(), that.getQuote());
}
@Override
public int hashCode() {
return Objects.hash(getUser(), getQuote());
}
}

@ -0,0 +1,21 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Image")
public class Image {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_img")
private Long id;
@Column(name = "imgPath", nullable = false, unique = true, length = 300)
private String imgPath;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getImgPath() { return imgPath; }
public void setImgPath(String imgPath) { this.imgPath = imgPath; }
}

@ -0,0 +1,46 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Question")
public class Question {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_question")
private Long id;
@Column(name = "texte", nullable = false, columnDefinition = "text", unique = true)
private String texte;
@Column(name = "answerA", nullable = false, length = 30)
private String answerA;
@Column(name = "answerB", nullable = false, length = 30)
private String answerB;
@Column(name = "answerC", nullable = false, length = 30)
private String answerC;
@Column(name = "answerD", nullable = false, length = 30)
private String answerD;
@Column(name = "cAnswer", nullable = false, length = 30)
private String cAnswer;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTexte() { return texte; }
public void setTexte(String texte) { this.texte = texte; }
public String getAnswerA() { return answerA; }
public void setAnswerA(String answerA) { this.answerA = answerA; }
public String getAnswerB() { return answerB; }
public void setAnswerB(String answerB) { this.answerB = answerB; }
public String getAnswerC() { return answerC; }
public void setAnswerC(String answerC) { this.answerC = answerC; }
public String getAnswerD() { return answerD; }
public void setAnswerD(String answerD) { this.answerD = answerD; }
public String getCAnswer() { return cAnswer; }
public void setCAnswer(String cAnswer) { this.cAnswer = cAnswer; }
}

@ -0,0 +1,32 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Quiz")
public class Quiz {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_quiz")
private Long id;
@Column(name = "title", nullable = false, length = 40)
private String title;
@ManyToOne
@JoinColumn(name = "img", nullable = false)
private Image image;
@Column(name = "nb_quest")
private Integer nbQuest;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public Image getImage() { return image; }
public void setImage(Image image) { this.image = image; }
public Integer getNbQuest() { return nbQuest; }
public void setNbQuest(Integer nbQuest) { this.nbQuest = nbQuest; }
}

@ -0,0 +1,28 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Quiz_Question")
public class QuizQuestion {
@EmbeddedId
private QuizQuestionId id;
@ManyToOne
@MapsId("quiz")
@JoinColumn(name = "quiz")
private Quiz quiz;
@ManyToOne
@MapsId("question")
@JoinColumn(name = "question")
private Question question;
// Getters et setters
public QuizQuestionId getId() { return id; }
public void setId(QuizQuestionId id) { this.id = id; }
public Quiz getQuiz() { return quiz; }
public void setQuiz(Quiz quiz) { this.quiz = quiz; }
public Question getQuestion() { return question; }
public void setQuestion(Question question) { this.question = question; }
}

@ -0,0 +1,37 @@
package com.example.wfwebapi.model;
import java.io.Serializable;
import java.util.Objects;
import jakarta.persistence.Embeddable;
@Embeddable
public class QuizQuestionId implements Serializable {
private Long quiz;
private Long question;
public QuizQuestionId() {}
public QuizQuestionId(Long quiz, Long question) {
this.quiz = quiz;
this.question = question;
}
public Long getQuiz() { return quiz; }
public void setQuiz(Long quiz) { this.quiz = quiz; }
public Long getQuestion() { return question; }
public void setQuestion(Long question) { this.question = question; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof QuizQuestionId)) return false;
QuizQuestionId that = (QuizQuestionId) o;
return Objects.equals(getQuiz(), that.getQuiz()) &&
Objects.equals(getQuestion(), that.getQuestion());
}
@Override
public int hashCode() {
return Objects.hash(getQuiz(), getQuestion());
}
}

@ -0,0 +1,59 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Quote")
public class Quote {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_quote")
private Long id;
@Column(name = "content", nullable = false, columnDefinition = "text")
private String content;
@Column(name = "likes")
private Integer likes;
@Column(name = "langue", nullable = false, length = 2)
private String langue;
@Column(name = "isValide", nullable = false)
private Boolean isValide;
@Column(name = "reason", nullable = false, length = 100)
private String reason;
@ManyToOne
@JoinColumn(name = "id_caracter", nullable = false)
private Caracter caracter;
@ManyToOne
@JoinColumn(name = "id_source", nullable = false)
private Source source;
@ManyToOne
@JoinColumn(name = "id_user_verif", nullable = false)
private User userVerif;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getContent() { return content; }
public void setContent(String content) { this.content = content; }
public Integer getLikes() { return likes; }
public void setLikes(Integer likes) { this.likes = likes; }
public String getLangue() { return langue; }
public void setLangue(String langue) { this.langue = langue; }
public Boolean getIsValide() { return isValide; }
public void setIsValide(Boolean isValide) { this.isValide = isValide; }
public String getReason() { return reason; }
public void setReason(String reason) { this.reason = reason; }
public Caracter getCaracter() { return caracter; }
public void setCaracter(Caracter caracter) { this.caracter = caracter; }
public Source getSource() { return source; }
public void setSource(Source source) { this.source = source; }
public User getUserVerif() { return userVerif; }
public void setUserVerif(User userVerif) { this.userVerif = userVerif; }
}

@ -0,0 +1,38 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Record_quiz")
public class RecordQuiz {
@EmbeddedId
private RecordQuizId id;
@ManyToOne
@MapsId("user")
@JoinColumn(name = "users")
private User user;
@ManyToOne
@MapsId("quiz")
@JoinColumn(name = "quiz")
private Quiz quiz;
@Column(name = "nbPoint")
private Integer nbPoint;
@Column(name = "timeQ")
private Integer timeQ;
// Getters et setters
public RecordQuizId getId() { return id; }
public void setId(RecordQuizId id) { this.id = id; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Quiz getQuiz() { return quiz; }
public void setQuiz(Quiz quiz) { this.quiz = quiz; }
public Integer getNbPoint() { return nbPoint; }
public void setNbPoint(Integer nbPoint) { this.nbPoint = nbPoint; }
public Integer getTimeQ() { return timeQ; }
public void setTimeQ(Integer timeQ) { this.timeQ = timeQ; }
}

@ -0,0 +1,37 @@
package com.example.wfwebapi.model;
import java.io.Serializable;
import java.util.Objects;
import jakarta.persistence.Embeddable;
@Embeddable
public class RecordQuizId implements Serializable {
private Long user;
private Long quiz;
public RecordQuizId() {}
public RecordQuizId(Long user, Long quiz) {
this.user = user;
this.quiz = quiz;
}
public Long getUser() { return user; }
public void setUser(Long user) { this.user = user; }
public Long getQuiz() { return quiz; }
public void setQuiz(Long quiz) { this.quiz = quiz; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RecordQuizId)) return false;
RecordQuizId that = (RecordQuizId) o;
return Objects.equals(getUser(), that.getUser()) &&
Objects.equals(getQuiz(), that.getQuiz());
}
@Override
public int hashCode() {
return Objects.hash(getUser(), getQuiz());
}
}

@ -0,0 +1,26 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
@Entity
@Table(name = "Source")
public class Source {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_source")
private Long id;
@Column(name = "title", nullable = false, length = 100)
private String title;
@Column(name = "dateS", nullable = false)
private Integer dateS;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public Integer getDateS() { return dateS; }
public void setDateS(Integer dateS) { this.dateS = dateS; }
}

@ -0,0 +1,43 @@
package com.example.wfwebapi.model;
import jakarta.persistence.*;
import java.time.LocalDate;
@Entity
@Table(name = "Users", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_user")
private Long id;
@Column(name = "username", nullable = false, length = 50)
private String username;
@Column(name = "email", nullable = false, length = 50)
private String email;
@Column(name = "password", nullable = false, length = 100)
private String password;
@ManyToOne
@JoinColumn(name = "img", nullable = false)
private Image image;
@Column(name = "creation", nullable = false)
private LocalDate creation;
// Getters et setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public Image getImage() { return image; }
public void setImage(Image image) { this.image = image; }
public LocalDate getCreation() { return creation; }
public void setCreation(LocalDate creation) { this.creation = creation; }
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Admin;
public interface AdminRepository extends JpaRepository<Admin, Long> {
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Caracter;
public interface CaracterRepository extends JpaRepository<Caracter, Long> {
}

@ -0,0 +1,9 @@
package com.example.wfwebapi.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Commentary;
public interface CommentaryRepository extends JpaRepository<Commentary, Long> {
List<Commentary> findByQuote_Id(Long quoteId);
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.DailyQuote;
public interface DailyQuoteRepository extends JpaRepository<DailyQuote, Long> {
}

@ -0,0 +1,10 @@
package com.example.wfwebapi.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Favorite;
import com.example.wfwebapi.model.FavoriteId;
public interface FavoriteRepository extends JpaRepository<Favorite, FavoriteId> {
List<Favorite> findByUser_Id(Long userId);
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Image;
public interface ImageRepository extends JpaRepository<Image, Long> {
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Question;
public interface QuestionRepository extends JpaRepository<Question, Long> {
}

@ -0,0 +1,8 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.QuizQuestion;
import com.example.wfwebapi.model.QuizQuestionId;
public interface QuizQuestionRepository extends JpaRepository<QuizQuestion, QuizQuestionId> {
}

@ -0,0 +1,8 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Quote;
public interface QuoteRepository extends JpaRepository<Quote, Long> {
}

@ -0,0 +1,8 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.RecordQuiz;
import com.example.wfwebapi.model.RecordQuizId;
public interface RecordQuizRepository extends JpaRepository<RecordQuiz, RecordQuizId> {
}

@ -0,0 +1,7 @@
package com.example.wfwebapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.Source;
public interface SourceRepository extends JpaRepository<Source, Long> {
}

@ -0,0 +1,12 @@
package com.example.wfwebapi.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.wfwebapi.model.User;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Optional<User> findByEmail(String email);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}

@ -0,0 +1,38 @@
package com.example.wfwebapi.security;
import com.example.wfwebapi.exception.UnauthorizedException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenProvider tokenProvider;
public JwtAuthenticationFilter(JwtTokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token manquant ou invalide");
return;
}
String token = header.substring(7);
if (!tokenProvider.validateToken(token)) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token invalide ou expiré");
return;
}
filterChain.doFilter(request, response);
}
}

@ -0,0 +1,45 @@
package com.example.wfwebapi.security;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;
import org.springframework.stereotype.Component;
@Component
public class JwtTokenProvider {
// Clé secrète (à stocker en sécurité dans une variable d'environnement en production)
private final Key secretKey = Keys.hmacShaKeyFor("MaCléSuperSecrètePourJWTQueJeDoisChanger".getBytes());
// Durée de validité du token (par exemple 1h)
private final long validityInMilliseconds = 3600000;
// Création du token
public String createToken(String username) {
Claims claims = Jwts.claims().setSubject(username);
Date now = new Date();
Date validity = new Date(now.getTime() + validityInMilliseconds);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(validity)
.signWith(secretKey, SignatureAlgorithm.HS256)
.compact();
}
// Validation du token
public boolean validateToken(String token) {
try {
Jws<Claims> claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
return !claims.getBody().getExpiration().before(new Date());
} catch (JwtException | IllegalArgumentException e) {
return false;
}
}
// Récupération du nom d'utilisateur depuis le token
public String getUsername(String token) {
return Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody().getSubject();
}
}

@ -0,0 +1,12 @@
spring.application.name=WF-WEBAPI
# Utilisation de H2 avec le script d'initialisation
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:init.sql
spring.jpa.hibernate.ddl-auto=none
spring.h2.console.enabled=true
server.port=8080

@ -45,10 +45,12 @@ BEGIN
END; END;
$$ LANGUAGE plpgsql ; $$ LANGUAGE plpgsql ;
Create Trigger IfUserIsAdmin BEFORE DELETE on Users Create Trigger IfUserIsAdmin BEFORE DELETE on Users
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION IfUserIsAdmin(); EXECUTE FUNCTION IfUserIsAdmin();
Create OR REPLACE Function DeleteUserFavorite() RETURNS trigger AS $$ Create OR REPLACE Function DeleteUserFavorite() RETURNS trigger AS $$
DECLARE DECLARE
@ -60,6 +62,7 @@ BEGIN
END; END;
$$ LANGUAGE plpgsql ; $$ LANGUAGE plpgsql ;
Create Trigger DeleteUserFavorite BEFORE DELETE on Users Create Trigger DeleteUserFavorite BEFORE DELETE on Users
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION DeleteUserFavorite(); EXECUTE FUNCTION DeleteUserFavorite();
@ -75,6 +78,7 @@ BEGIN
END; END;
$$ LANGUAGE plpgsql ; $$ LANGUAGE plpgsql ;
Create Trigger DeleteUserCommentary BEFORE DELETE on Users Create Trigger DeleteUserCommentary BEFORE DELETE on Users
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION DeleteUserCommentary(); EXECUTE FUNCTION DeleteUserCommentary();
@ -240,6 +244,7 @@ Create Trigger DeleteQuoteBEFORE BEFORE DELETE on Quote
FOR EACH ROW FOR EACH ROW
EXECUTE FUNCTION DeleteQuoteBEFORE(); EXECUTE FUNCTION DeleteQuoteBEFORE();
Create OR REPLACE Function DeleteQuoteAFTER() RETURNS trigger AS $$ Create OR REPLACE Function DeleteQuoteAFTER() RETURNS trigger AS $$
DECLARE DECLARE
nb numeric; nb numeric;
@ -308,6 +313,7 @@ EXECUTE FUNCTION UniqueDailyQuote();
------------------------------------------------------------------------- -------------------------------------------------------------------------
CREATE TABLE Favorite( CREATE TABLE Favorite(
users SERIAL NOT NULL, users SERIAL NOT NULL,
quote SERIAL NOT NULL, quote SERIAL NOT NULL,
@ -327,3 +333,6 @@ CREATE TABLE Commentary(
CONSTRAINT fk_quote FOREIGN KEY(quote) REFERENCES Quote(id_quote), CONSTRAINT fk_quote FOREIGN KEY(quote) REFERENCES Quote(id_quote),
CONSTRAINT fk_user FOREIGN KEY(users) REFERENCES Users(id_user) CONSTRAINT fk_user FOREIGN KEY(users) REFERENCES Users(id_user)
); );
-------------------------------------------------------------------------

@ -0,0 +1,13 @@
package com.example.wfwebapi;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WfWebapiApplicationTests {
@Test
void contextLoads() {
}
}

@ -1,13 +0,0 @@
{
"require": {
"slim/slim": "^4.8",
"slim/psr7": "^1.5",
"php-di/php-di": "^6.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}

1000
composer.lock generated

File diff suppressed because it is too large Load Diff

@ -1,29 +0,0 @@
version: '3.8'
services:
db:
image: postgres:13
container_name: my_api_db
restart: always
environment:
POSTGRES_DB: dbwikifantasy
POSTGRES_USER: postgres
POSTGRES_PASSWORD: sucepute
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "5432:5432"
app:
build: .
container_name: my_api_app
restart: always
depends_on:
- db
environment:
DB_HOST: db
DB_NAME: dbwikifantasy
DB_USER: postgres
DB_PASSWORD: sucepute
ports:
- "8080:80"

@ -1,22 +0,0 @@
FROM php:8.1-apache
# Installation de l'extension PDO PostgreSQL
RUN docker-php-ext-install pdo pdo_pgsql
# Installer Composer depuis l'image officielle Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# Définir le répertoire de travail
WORKDIR /var/www/html
# Copier le fichier de composer et installer les dépendances
COPY composer.json composer.lock ./
RUN composer install
# Copier l'ensemble du projet dans le conteneur
COPY . /var/www/html
# Ajuster les droits sur les fichiers (si nécessaire)
RUN chown -R www-data:www-data /var/www/html
EXPOSE 80

@ -1,16 +0,0 @@
<?php
require __DIR__ . '/../vendor/autoload.php';
use DI\Container;
use Slim\Factory\AppFactory;
$container = new Container();
AppFactory::setContainer($container);
$app = AppFactory::create();
// Inclusion des settings, dépendances et routes
require __DIR__ . '/../src/settings.php';
require __DIR__ . '/../src/dependencies.php';
require __DIR__ . '/../src/routes.php';
$app->run();

@ -1,66 +0,0 @@
<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class ImageController {
protected $db;
public function __construct($container) {
$this->db = $container->get('db');
}
// Récupérer toutes les images
public function getImages(Request $request, Response $response, $args) {
$sql = "SELECT * FROM Image";
try {
$stmt = $this->db->query($sql);
$images = $stmt->fetchAll(\PDO::FETCH_OBJ);
$payload = json_encode($images);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Récupérer une image par son ID
public function getImage(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "SELECT * FROM Image WHERE id_img = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$image = $stmt->fetch(\PDO::FETCH_OBJ);
if(!$image){
$payload = json_encode(['message' => 'Image not found']);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
$payload = json_encode($image);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Créer une nouvelle image
public function createImage(Request $request, Response $response, $args) {
$data = $request->getParsedBody();
$sql = "INSERT INTO Image (imgPath) VALUES (:imgPath)";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("imgPath", $data['imgPath']);
$stmt->execute();
$data['id_img'] = $this->db->lastInsertId();
$payload = json_encode($data);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
}

@ -1,84 +0,0 @@
<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class QuizController {
protected $db;
public function __construct($container) {
$this->db = $container->get('db');
}
// Récupérer tous les quiz
public function getQuizzes(Request $request, Response $response, $args) {
$sql = "SELECT * FROM Quiz";
try {
$stmt = $this->db->query($sql);
$quizzes = $stmt->fetchAll(\PDO::FETCH_OBJ);
$payload = json_encode($quizzes);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Récupérer un quiz par son ID
public function getQuiz(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "SELECT * FROM Quiz WHERE id_quiz = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$quiz = $stmt->fetch(\PDO::FETCH_OBJ);
if(!$quiz){
$payload = json_encode(['message' => 'Quiz not found']);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
$payload = json_encode($quiz);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Créer un nouveau quiz
public function createQuiz(Request $request, Response $response, $args) {
$data = $request->getParsedBody();
$sql = "INSERT INTO Quiz (title, img, nb_quest) VALUES (:title, :img, :nb_quest)";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("title", $data['title']);
$stmt->bindParam("img", $data['img']);
$stmt->bindParam("nb_quest", $data['nb_quest']);
$stmt->execute();
$data['id_quiz'] = $this->db->lastInsertId();
$payload = json_encode($data);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Supprimer un quiz
public function deleteQuiz(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "DELETE FROM Quiz WHERE id_quiz = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$payload = json_encode(['message' => 'Quiz deleted']);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
}

@ -1,89 +0,0 @@
<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class QuoteController {
protected $db;
public function __construct($container) {
$this->db = $container->get('db');
}
// Récupérer toutes les citations
public function getQuotes(Request $request, Response $response, $args) {
$sql = "SELECT * FROM Quote";
try {
$stmt = $this->db->query($sql);
$quotes = $stmt->fetchAll(\PDO::FETCH_OBJ);
$payload = json_encode($quotes);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Récupérer une citation par son ID
public function getQuote(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "SELECT * FROM Quote WHERE id_quote = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$quote = $stmt->fetch(\PDO::FETCH_OBJ);
if(!$quote){
$payload = json_encode(['message' => 'Quote not found']);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
$payload = json_encode($quote);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Créer une nouvelle citation
public function createQuote(Request $request, Response $response, $args) {
$data = $request->getParsedBody();
$sql = "INSERT INTO Quote (content, likes, langue, isValide, reason, id_caracter, id_source, id_user_verif) VALUES (:content, :likes, :langue, :isValide, :reason, :id_caracter, :id_source, :id_user_verif)";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("content", $data['content']);
$stmt->bindParam("likes", $data['likes']);
$stmt->bindParam("langue", $data['langue']);
$stmt->bindParam("isValide", $data['isValide']);
$stmt->bindParam("reason", $data['reason']);
$stmt->bindParam("id_caracter", $data['id_caracter']);
$stmt->bindParam("id_source", $data['id_source']);
$stmt->bindParam("id_user_verif", $data['id_user_verif']);
$stmt->execute();
$data['id_quote'] = $this->db->lastInsertId();
$payload = json_encode($data);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Supprimer une citation
public function deleteQuote(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "DELETE FROM Quote WHERE id_quote = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$payload = json_encode(['message' => 'Quote deleted']);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
}

@ -1,108 +0,0 @@
<?php
namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class UserController {
protected $db;
public function __construct($container) {
$this->db = $container->get('db');
}
// Récupérer tous les utilisateurs
public function getUsers(Request $request, Response $response, $args) {
$sql = "SELECT * FROM Users";
try {
$stmt = $this->db->query($sql);
$users = $stmt->fetchAll(\PDO::FETCH_OBJ);
$payload = json_encode($users);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Récupérer un utilisateur par son ID
public function getUser(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "SELECT * FROM Users WHERE id_user = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$user = $stmt->fetch(\PDO::FETCH_OBJ);
if(!$user){
$payload = json_encode(['message' => 'User not found']);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json')->withStatus(404);
}
$payload = json_encode($user);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Créer un nouvel utilisateur
public function createUser(Request $request, Response $response, $args) {
$data = $request->getParsedBody();
$sql = "INSERT INTO Users (username, email, password, img, creation) VALUES (:username, :email, :password, :img, :creation)";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("username", $data['username']);
$stmt->bindParam("email", $data['email']);
$stmt->bindParam("password", $data['password']);
$stmt->bindParam("img", $data['img']);
$stmt->bindParam("creation", $data['creation']);
$stmt->execute();
$data['id_user'] = $this->db->lastInsertId();
$payload = json_encode($data);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Mettre à jour un utilisateur
public function updateUser(Request $request, Response $response, $args) {
$id = $args['id'];
$data = $request->getParsedBody();
$sql = "UPDATE Users SET username = :username, email = :email, password = :password, img = :img, creation = :creation WHERE id_user = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("username", $data['username']);
$stmt->bindParam("email", $data['email']);
$stmt->bindParam("password", $data['password']);
$stmt->bindParam("img", $data['img']);
$stmt->bindParam("creation", $data['creation']);
$stmt->bindParam("id", $id);
$stmt->execute();
$payload = json_encode(['message' => 'User updated']);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
// Supprimer un utilisateur
public function deleteUser(Request $request, Response $response, $args) {
$id = $args['id'];
$sql = "DELETE FROM Users WHERE id_user = :id";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$payload = json_encode(['message' => 'User deleted']);
} catch (\PDOException $e) {
$payload = json_encode(['error' => $e->getMessage()]);
}
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
}
}

@ -1,24 +0,0 @@
<?php
use App\Controllers\UserController;
use App\Controllers\ImageController;
use App\Controllers\QuoteController;
use App\Controllers\QuizController;
$container = $app->getContainer();
$container->set(UserController::class, function($container) {
return new UserController($container);
});
$container->set(ImageController::class, function($container) {
return new ImageController($container);
});
$container->set(QuoteController::class, function($container) {
return new QuoteController($container);
});
$container->set(QuizController::class, function($container) {
return new QuizController($container);
});

@ -1,39 +0,0 @@
<?php
use Slim\Routing\RouteCollectorProxy;
use App\Controllers\UserController;
use App\Controllers\ImageController;
use App\Controllers\QuoteController;
use App\Controllers\QuizController;
// Routes pour les Users
$app->group('/users', function (RouteCollectorProxy $group) {
$group->get('', UserController::class . ':getUsers');
$group->get('/{id}', UserController::class . ':getUser');
$group->post('', UserController::class . ':createUser');
$group->put('/{id}', UserController::class . ':updateUser');
$group->delete('/{id}', UserController::class . ':deleteUser');
});
// Routes pour les Images
$app->group('/images', function (RouteCollectorProxy $group) {
$group->get('', ImageController::class . ':getImages');
$group->get('/{id}', ImageController::class . ':getImage');
$group->post('', ImageController::class . ':createImage');
});
// Routes pour les Quotes
$app->group('/quotes', function (RouteCollectorProxy $group) {
$group->get('', QuoteController::class . ':getQuotes');
$group->get('/{id}', QuoteController::class . ':getQuote');
$group->post('', QuoteController::class . ':createQuote');
$group->delete('/{id}', QuoteController::class . ':deleteQuote');
});
// Routes pour les Quizzes
$app->group('/quizzes', function (RouteCollectorProxy $group) {
$group->get('', QuizController::class . ':getQuizzes');
$group->get('/{id}', QuizController::class . ':getQuiz');
$group->post('', QuizController::class . ':createQuiz');
$group->delete('/{id}', QuizController::class . ':deleteQuiz');
});

@ -1,20 +0,0 @@
<?php
// Récupération du conteneur de l'application
$container = $app->getContainer();
$container->set('db', function () {
// On récupère les paramètres depuis les variables d'environnement
$host = getenv('DB_HOST') ?: 'db';
$dbname = getenv('DB_NAME') ?: 'dbwikifantasy';
$user = getenv('DB_USER') ?: 'postgres';
$pass = getenv('DB_PASSWORD') ?: 'sucepute';
$dsn = "pgsql:host=$host;dbname=$dbname";
try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
die('Database connection failed: ' . $e->getMessage());
}
});

@ -1,25 +0,0 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitf27925eac6aff16ca9ab89f53d568cb9::getLoader();

@ -1,579 +0,0 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}

@ -1,359 +0,0 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer;
use Composer\Autoload\ClassLoader;
use Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
return false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir.'/composer/installed.php';
$installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array()) {
$installed[] = self::$installed;
}
return $installed;
}
}

@ -1,21 +0,0 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -1,15 +0,0 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);

@ -1,13 +0,0 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php',
'7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php',
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'b33e3d135e5d9e47d845c576147bda89' => $vendorDir . '/php-di/php-di/src/functions.php',
);

@ -1,9 +0,0 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);

@ -1,23 +0,0 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Slim\\Psr7\\' => array($vendorDir . '/slim/psr7/src'),
'Slim\\' => array($vendorDir . '/slim/slim/Slim'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
'Psr\\Http\\Server\\' => array($vendorDir . '/psr/http-server-handler/src', $vendorDir . '/psr/http-server-middleware/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'),
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'PhpDocReader\\' => array($vendorDir . '/php-di/phpdoc-reader/src/PhpDocReader'),
'Laravel\\SerializableClosure\\' => array($vendorDir . '/laravel/serializable-closure/src'),
'Invoker\\' => array($vendorDir . '/php-di/invoker/src'),
'Fig\\Http\\Message\\' => array($vendorDir . '/fig/http-message-util/src'),
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
'DI\\' => array($vendorDir . '/php-di/php-di/src'),
'App\\' => array($baseDir . '/src'),
);

@ -1,50 +0,0 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitf27925eac6aff16ca9ab89f53d568cb9
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitf27925eac6aff16ca9ab89f53d568cb9', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitf27925eac6aff16ca9ab89f53d568cb9', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::getInitializer($loader));
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}, null, null);
foreach ($filesToLoad as $fileIdentifier => $file) {
$requireFile($fileIdentifier, $file);
}
return $loader;
}
}

@ -1,133 +0,0 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9
{
public static $files = array (
'253c157292f75eb38082b5acb06f3f01' => __DIR__ . '/..' . '/nikic/fast-route/src/functions.php',
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'b33e3d135e5d9e47d845c576147bda89' => __DIR__ . '/..' . '/php-di/php-di/src/functions.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Php80\\' => 23,
'Slim\\Psr7\\' => 10,
'Slim\\' => 5,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Server\\' => 16,
'Psr\\Http\\Message\\' => 17,
'Psr\\Container\\' => 14,
'PhpDocReader\\' => 13,
),
'L' =>
array (
'Laravel\\SerializableClosure\\' => 28,
),
'I' =>
array (
'Invoker\\' => 8,
),
'F' =>
array (
'Fig\\Http\\Message\\' => 17,
'FastRoute\\' => 10,
),
'D' =>
array (
'DI\\' => 3,
),
'A' =>
array (
'App\\' => 4,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Php80\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
),
'Slim\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/slim/psr7/src',
),
'Slim\\' =>
array (
0 => __DIR__ . '/..' . '/slim/slim/Slim',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/src',
),
'Psr\\Http\\Server\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-server-handler/src',
1 => __DIR__ . '/..' . '/psr/http-server-middleware/src',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-message/src',
1 => __DIR__ . '/..' . '/psr/http-factory/src',
),
'Psr\\Container\\' =>
array (
0 => __DIR__ . '/..' . '/psr/container/src',
),
'PhpDocReader\\' =>
array (
0 => __DIR__ . '/..' . '/php-di/phpdoc-reader/src/PhpDocReader',
),
'Laravel\\SerializableClosure\\' =>
array (
0 => __DIR__ . '/..' . '/laravel/serializable-closure/src',
),
'Invoker\\' =>
array (
0 => __DIR__ . '/..' . '/php-di/invoker/src',
),
'Fig\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/fig/http-message-util/src',
),
'FastRoute\\' =>
array (
0 => __DIR__ . '/..' . '/nikic/fast-route/src',
),
'DI\\' =>
array (
0 => __DIR__ . '/..' . '/php-di/php-di/src',
),
'App\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitf27925eac6aff16ca9ab89f53d568cb9::$classMap;
}, null, ClassLoader::class);
}
}

File diff suppressed because it is too large Load Diff

@ -1,185 +0,0 @@
<?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '125ed0da41ed191fb7b6fed7ff678984b90699dc',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '125ed0da41ed191fb7b6fed7ff678984b90699dc',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'fig/http-message-util' => array(
'pretty_version' => '1.1.5',
'version' => '1.1.5.0',
'reference' => '9d94dc0154230ac39e5bf89398b324a86f63f765',
'type' => 'library',
'install_path' => __DIR__ . '/../fig/http-message-util',
'aliases' => array(),
'dev_requirement' => false,
),
'laravel/serializable-closure' => array(
'pretty_version' => 'v1.3.7',
'version' => '1.3.7.0',
'reference' => '4f48ade902b94323ca3be7646db16209ec76be3d',
'type' => 'library',
'install_path' => __DIR__ . '/../laravel/serializable-closure',
'aliases' => array(),
'dev_requirement' => false,
),
'nikic/fast-route' => array(
'pretty_version' => 'v1.3.0',
'version' => '1.3.0.0',
'reference' => '181d480e08d9476e61381e04a71b34dc0432e812',
'type' => 'library',
'install_path' => __DIR__ . '/../nikic/fast-route',
'aliases' => array(),
'dev_requirement' => false,
),
'php-di/invoker' => array(
'pretty_version' => '2.3.6',
'version' => '2.3.6.0',
'reference' => '59f15608528d8a8838d69b422a919fd6b16aa576',
'type' => 'library',
'install_path' => __DIR__ . '/../php-di/invoker',
'aliases' => array(),
'dev_requirement' => false,
),
'php-di/php-di' => array(
'pretty_version' => '6.4.0',
'version' => '6.4.0.0',
'reference' => 'ae0f1b3b03d8b29dff81747063cbfd6276246cc4',
'type' => 'library',
'install_path' => __DIR__ . '/../php-di/php-di',
'aliases' => array(),
'dev_requirement' => false,
),
'php-di/phpdoc-reader' => array(
'pretty_version' => '2.2.1',
'version' => '2.2.1.0',
'reference' => '66daff34cbd2627740ffec9469ffbac9f8c8185c',
'type' => 'library',
'install_path' => __DIR__ . '/../php-di/phpdoc-reader',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/container' => array(
'pretty_version' => '1.1.2',
'version' => '1.1.2.0',
'reference' => '513e0666f7216c7459170d56df27dfcefe1689ea',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/container',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/container-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '^1.0',
),
),
'psr/http-factory' => array(
'pretty_version' => '1.1.0',
'version' => '1.1.0.0',
'reference' => '2b4765fddfe3b508ac62f829e852b1501d3f6e8a',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-factory',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-factory-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '^1.0',
),
),
'psr/http-message' => array(
'pretty_version' => '2.0',
'version' => '2.0.0.0',
'reference' => '402d35bcb92c70c026d1a6a9883f06b2ead23d71',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-message',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-message-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '^1.0 || ^2.0',
),
),
'psr/http-server-handler' => array(
'pretty_version' => '1.0.2',
'version' => '1.0.2.0',
'reference' => '84c4fb66179be4caaf8e97bd239203245302e7d4',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-server-handler',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/http-server-middleware' => array(
'pretty_version' => '1.0.2',
'version' => '1.0.2.0',
'reference' => 'c1481f747daaa6a0782775cd6a8c26a1bf4a3829',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/http-server-middleware',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/log' => array(
'pretty_version' => '3.0.2',
'version' => '3.0.2.0',
'reference' => 'f16e1d5863e37f8d8c2a01719f5b34baa2b714d3',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/log',
'aliases' => array(),
'dev_requirement' => false,
),
'ralouphie/getallheaders' => array(
'pretty_version' => '3.0.3',
'version' => '3.0.3.0',
'reference' => '120b605dfeb996808c31b6477290a714d356e822',
'type' => 'library',
'install_path' => __DIR__ . '/../ralouphie/getallheaders',
'aliases' => array(),
'dev_requirement' => false,
),
'slim/psr7' => array(
'pretty_version' => '1.7.0',
'version' => '1.7.0.0',
'reference' => '753e9646def5ff4db1a06e5cf4ef539bfd30f467',
'type' => 'library',
'install_path' => __DIR__ . '/../slim/psr7',
'aliases' => array(),
'dev_requirement' => false,
),
'slim/slim' => array(
'pretty_version' => '4.14.0',
'version' => '4.14.0.0',
'reference' => '5943393b88716eb9e82c4161caa956af63423913',
'type' => 'library',
'install_path' => __DIR__ . '/../slim/slim',
'aliases' => array(),
'dev_requirement' => false,
),
'symfony/polyfill-php80' => array(
'pretty_version' => 'v1.31.0',
'version' => '1.31.0.0',
'reference' => '60328e362d4c2c802a54fcbf04f9d3fb892b4cf8',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/polyfill-php80',
'aliases' => array(),
'dev_requirement' => false,
),
),
);

@ -1,26 +0,0 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 80000)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}

@ -1,147 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 1.1.5 - 2020-11-24
### Added
- [#19](https://github.com/php-fig/http-message-util/pull/19) adds support for PHP 8.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 1.1.4 - 2020-02-05
### Added
- Nothing.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- [#15](https://github.com/php-fig/http-message-util/pull/15) removes the dependency on psr/http-message, as it is not technically necessary for usage of this package.
### Fixed
- Nothing.
## 1.1.3 - 2018-11-19
### Added
- [#10](https://github.com/php-fig/http-message-util/pull/10) adds the constants `StatusCodeInterface::STATUS_EARLY_HINTS` (103) and
`StatusCodeInterface::STATUS_TOO_EARLY` (425).
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 1.1.2 - 2017-02-09
### Added
- [#4](https://github.com/php-fig/http-message-util/pull/4) adds the constant
`StatusCodeInterface::STATUS_MISDIRECTED_REQUEST` (421).
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 1.1.1 - 2017-02-06
### Added
- [#3](https://github.com/php-fig/http-message-util/pull/3) adds the constant
`StatusCodeInterface::STATUS_IM_A_TEAPOT` (418).
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 1.1.0 - 2016-09-19
### Added
- [#1](https://github.com/php-fig/http-message-util/pull/1) adds
`Fig\Http\Message\StatusCodeInterface`, with constants named after common
status reason phrases, with values indicating the status codes themselves.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 1.0.0 - 2017-08-05
### Added
- Adds `Fig\Http\Message\RequestMethodInterface`, with constants covering the
most common HTTP request methods as specified by the IETF.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.

@ -1,19 +0,0 @@
Copyright (c) 2016 PHP Framework Interoperability Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@ -1,17 +0,0 @@
# PSR Http Message Util
This repository holds utility classes and constants to facilitate common
operations of [PSR-7](https://www.php-fig.org/psr/psr-7/); the primary purpose is
to provide constants for referring to request methods, response status codes and
messages, and potentially common headers.
Implementation of PSR-7 interfaces is **not** within the scope of this package.
## Installation
Install by adding the package as a [Composer](https://getcomposer.org)
requirement:
```bash
$ composer require fig/http-message-util
```

@ -1,28 +0,0 @@
{
"name": "fig/http-message-util",
"description": "Utility classes and constants for use with PSR-7 (psr/http-message)",
"keywords": ["psr", "psr-7", "http", "http-message", "request", "response"],
"license": "MIT",
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"require": {
"php": "^5.3 || ^7.0 || ^8.0"
},
"suggest": {
"psr/http-message": "The package containing the PSR-7 interfaces"
},
"autoload": {
"psr-4": {
"Fig\\Http\\Message\\": "src/"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
}
}

@ -1,34 +0,0 @@
<?php
namespace Fig\Http\Message;
/**
* Defines constants for common HTTP request methods.
*
* Usage:
*
* <code>
* class RequestFactory implements RequestMethodInterface
* {
* public static function factory(
* $uri = '/',
* $method = self::METHOD_GET,
* $data = []
* ) {
* }
* }
* </code>
*/
interface RequestMethodInterface
{
const METHOD_HEAD = 'HEAD';
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_PURGE = 'PURGE';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_TRACE = 'TRACE';
const METHOD_CONNECT = 'CONNECT';
}

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

Loading…
Cancel
Save