Add .fit feature
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
parent
15e854a508
commit
1fdce42f49
@ -0,0 +1,33 @@
|
||||
@startuml
|
||||
class phpFITFileAnalysis
|
||||
{
|
||||
data_mesgs : array
|
||||
dev_field_descriptions : array
|
||||
options : null
|
||||
file_contents : string
|
||||
file_pointer : integer
|
||||
defn_mesgs : array
|
||||
defn_mesgs_all : array
|
||||
file_header : array
|
||||
php_trader_ext_loaded : boolean
|
||||
types : null
|
||||
garmin_timestamps : boolean
|
||||
readDataRecords : function
|
||||
fixData($options) : function
|
||||
interpolateMissingData(&$missing_keys, &$array)
|
||||
}
|
||||
|
||||
ProjectModel --|> Project
|
||||
AttributeModel --|> Element
|
||||
UMLModel --|> Element
|
||||
UMLClassDiagram --|> Element
|
||||
UMLClassView --|> View
|
||||
UMLNameCompartmentView --|> View
|
||||
UMLAttributeCompartmentView --|> View
|
||||
UMLOperationCompartmentView --|> View
|
||||
UMLReceptionCompartmentView --|> View
|
||||
UMLTemplateParameterCompartmentView --|> View
|
||||
LabelView --|> View
|
||||
|
||||
@enduml
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,30 +1,278 @@
|
||||
<?php
|
||||
/**
|
||||
* Nom du fichier: Activity.php
|
||||
*
|
||||
* @author PEREDERII Antoine
|
||||
* @date 2023-11-25
|
||||
* @description Classe Activity représentant une activité physique.
|
||||
*
|
||||
* @package model
|
||||
*/
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Cassandra\Date;
|
||||
use Cassandra\Time;
|
||||
|
||||
/**
|
||||
* @class Activity
|
||||
* @brief Classe représentant une activité physique.
|
||||
*/
|
||||
class Activity
|
||||
{
|
||||
private static int $lastId = 0;
|
||||
private int $idActivity;
|
||||
private String $type;
|
||||
private Date $date;
|
||||
private time $heureDebut;
|
||||
private time $heureFin;
|
||||
private \DateTime $date;
|
||||
private \DateTime $heureDebut;
|
||||
private \DateTime $heureFin;
|
||||
private int $effortRessenti;
|
||||
private float $variability;
|
||||
private float $variance;
|
||||
private float $standardDeviation;
|
||||
private float $average;
|
||||
private int $average;
|
||||
private int $maximum;
|
||||
private int $minimum;
|
||||
private float $avrTemperature;
|
||||
private Data $arrayData;
|
||||
private function getActivity():Activity{
|
||||
return $this;
|
||||
private bool $hasAutoPause;
|
||||
|
||||
/**
|
||||
* Constructeur de la classe Activity.
|
||||
*
|
||||
* @param String $type Le type d'activité.
|
||||
* @param \DateTime $date La date de l'activité.
|
||||
* @param \DateTime $heureDebut L'heure de début de l'activité.
|
||||
* @param \DateTime $heureFin L'heure de fin de l'activité.
|
||||
* @param int $effortRessenti L'effort ressenti pour l'activité (entre 0 et 5).
|
||||
* @param float $variability La variabilité de la fréquence cardiaque.
|
||||
* @param float $variance La variance de la fréquence cardiaque.
|
||||
* @param float $standardDeviation L'écart type de la fréquence cardiaque.
|
||||
* @param int $average La moyenne de la fréquence cardiaque.
|
||||
* @param int $maximum La fréquence cardiaque maximale.
|
||||
* @param int $minimum La fréquence cardiaque minimale.
|
||||
* @param float $avrTemperature La température moyenne pendant l'activité.
|
||||
* @param bool $hasAutoPause Indique si la pause automatique est activée.
|
||||
*
|
||||
* @throws \Exception Si l'effort ressenti n'est pas compris entre 0 et 5.
|
||||
*/
|
||||
public function __construct(
|
||||
String $type,
|
||||
\DateTime $date,
|
||||
\DateTime $heureDebut,
|
||||
\DateTime $heureFin,
|
||||
int $effortRessenti,
|
||||
float $variability,
|
||||
float $variance,
|
||||
float $standardDeviation,
|
||||
float $average,
|
||||
int $maximum,
|
||||
int $minimum,
|
||||
float $avrTemperature,
|
||||
bool $hasPause
|
||||
) {
|
||||
$this->idActivity = self::generateId();
|
||||
$this->type = $type;
|
||||
$this->date = $date;
|
||||
$this->heureDebut = $heureDebut;
|
||||
$this->heureFin = $heureFin;
|
||||
|
||||
if ($effortRessenti < 0 || $effortRessenti > 5) {
|
||||
throw new \Exception("L'effort ressenti doit être compris entre 0 et 5");
|
||||
}
|
||||
|
||||
$this->effortRessenti = $effortRessenti;
|
||||
$this->variability = $variability;
|
||||
$this->variance = $variance;
|
||||
$this->standardDeviation = $standardDeviation;
|
||||
$this->average = $average;
|
||||
$this->maximum = $maximum;
|
||||
$this->minimum = $minimum;
|
||||
$this->avrTemperature = $avrTemperature;
|
||||
$this->hasAutoPause = $hasPause;
|
||||
}
|
||||
|
||||
/**
|
||||
* Génère un identifiant unique pour l'activité.
|
||||
*
|
||||
* @return int L'identifiant unique généré.
|
||||
*/
|
||||
private static function generateId(): int
|
||||
{
|
||||
self::$lastId++;
|
||||
return self::$lastId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient l'identifiant de l'activité.
|
||||
*
|
||||
* @return int L'identifiant de l'activité.
|
||||
*/
|
||||
public function getIdActivity(): int
|
||||
{
|
||||
return $this->idActivity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient le type d'activité.
|
||||
*
|
||||
* @return String Le type d'activité.
|
||||
*/
|
||||
public function getType(): String
|
||||
{
|
||||
return $this->type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la date de l'activité.
|
||||
*
|
||||
* @return \DateTime La date de l'activité.
|
||||
*/
|
||||
public function getDate(): \DateTime
|
||||
{
|
||||
return $this->date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient l'heure de début de l'activité.
|
||||
*
|
||||
* @return \DateTime L'heure de début de l'activité.
|
||||
*/
|
||||
public function getHeureDebut(): \DateTime
|
||||
{
|
||||
return $this->heureDebut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient l'heure de fin de l'activité.
|
||||
*
|
||||
* @return \DateTime L'heure de fin de l'activité.
|
||||
*/
|
||||
public function getHeureFin(): \DateTime
|
||||
{
|
||||
return $this->heureFin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient l'effort ressenti pour l'activité.
|
||||
*
|
||||
* @return int L'effort ressenti pour l'activité.
|
||||
*/
|
||||
public function getEffortRessenti(): int
|
||||
{
|
||||
return $this->effortRessenti;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la variabilité de la fréquence cardiaque.
|
||||
*
|
||||
* @return float La variabilité de la fréquence cardiaque.
|
||||
*/
|
||||
public function getVariability(): float
|
||||
{
|
||||
return $this->variability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la variance de la fréquence cardiaque.
|
||||
*
|
||||
* @return float La variance de la fréquence cardiaque.
|
||||
*/
|
||||
public function getVariance(): float
|
||||
{
|
||||
return $this->variance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient l'écart type de la fréquence cardiaque.
|
||||
*
|
||||
* @return float L'écart type de la fréquence cardiaque.
|
||||
*/
|
||||
public function getStandardDeviation(): float
|
||||
{
|
||||
return $this->standardDeviation;
|
||||
}
|
||||
private function getAnalyse(Activity $activity):String{
|
||||
return $this->arrayData[$activity]->__to_String();
|
||||
|
||||
/**
|
||||
* Obtient la moyenne de la fréquence cardiaque.
|
||||
*
|
||||
* @return float La moyenne de la fréquence cardiaque.
|
||||
*/
|
||||
public function getAverage(): float
|
||||
{
|
||||
return $this->average;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la fréquence cardiaque maximale.
|
||||
*
|
||||
* @return int La fréquence cardiaque maximale.
|
||||
*/
|
||||
public function getMaximum(): int
|
||||
{
|
||||
return $this->maximum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la fréquence cardiaque minimale.
|
||||
*
|
||||
* @return int La fréquence cardiaque minimale.
|
||||
*/
|
||||
public function getMinimum(): int
|
||||
{
|
||||
return $this->minimum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la température moyenne pendant l'activité.
|
||||
*
|
||||
* @return float La température moyenne pendant l'activité.
|
||||
*/
|
||||
public function getAvrTemperature(): float
|
||||
{
|
||||
return $this->avrTemperature;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifie le type d'activité.
|
||||
*
|
||||
* @param String $type Le nouveau type d'activité.
|
||||
*/
|
||||
public function setType(String $type): void
|
||||
{
|
||||
$this->type = $type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifie l'effort ressenti pour l'activité.
|
||||
*
|
||||
* @param int $effortRessenti Le nouvel effort ressenti.
|
||||
* @throws \Exception Si l'effort ressenti n'est pas compris entre 0 et 5.
|
||||
*/
|
||||
public function setEffortRessenti(int $effortRessenti): void
|
||||
{
|
||||
if ($effortRessenti < 0 || $effortRessenti > 5) {
|
||||
throw new \Exception("L'effort ressenti doit être compris entre 0 et 5");
|
||||
}
|
||||
|
||||
$this->effortRessenti = $effortRessenti;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convertit l'objet Activity en chaîne de caractères.
|
||||
*
|
||||
* @return String La représentation de l'activité sous forme de chaîne de caractères.
|
||||
*/
|
||||
public function __toString(): String
|
||||
{
|
||||
return "Activité n°" . $this->idActivity . " : " .
|
||||
$this->type . " le " . $this->date->format('d/m/Y') .
|
||||
" de " . $this->heureDebut->format('H:i:s') . " à " . $this->heureFin->format('H:i:s') .
|
||||
" avec un effort ressenti de " . $this->effortRessenti . "/5" .
|
||||
" et une température moyenne de " . $this->avrTemperature . "°C" .
|
||||
" et une variabilité de " . $this->variability . " bpm" .
|
||||
" et une variance de " . $this->variance . " bpm" .
|
||||
" et un écart type de " . $this->standardDeviation . " bpm" .
|
||||
" et une moyenne de " . $this->average . " bpm" .
|
||||
" et un maximum de " . $this->maximum . " bpm" .
|
||||
" et un minimum de " . $this->minimum . " bpm" .
|
||||
" et une pause automatique " . ($this->hasAutoPause ? "activée" : "désactivée") . ".\n";
|
||||
}
|
||||
}
|
||||
?>
|
||||
|
@ -1,100 +1,224 @@
|
||||
<?php
|
||||
namespace Model;
|
||||
/**
|
||||
* Nom du fichier: Athlete.php
|
||||
*
|
||||
* @author PEREDERII Antoine
|
||||
* @date 2023-11-25
|
||||
* @description Classe Athlete représentant le rôle d'un athlète.
|
||||
*
|
||||
* @package model
|
||||
*/
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Shared\Exception\NotImplementedException;
|
||||
use Stub\TrainingRepository;
|
||||
|
||||
/**
|
||||
* @class Athlete
|
||||
* @brief Classe représentant le rôle d'un athlète.
|
||||
*/
|
||||
class Athlete extends Role {
|
||||
// Attributs spécifiques a l'athlete si nécessaire
|
||||
// Attributs spécifiques à l'athlète si nécessaire
|
||||
private array $statsList = [];
|
||||
private array $activityList = [];
|
||||
private array $dataSourcesList = [];
|
||||
|
||||
/**
|
||||
* Constructeur de la classe Athlete.
|
||||
*
|
||||
* @param TrainingRepository|null $trainingRepository Le repository des entraînements (optionnel).
|
||||
*/
|
||||
public function __construct(?TrainingRepository $trainingRepository) {
|
||||
$this->trainingRepository = $trainingRepository;
|
||||
}
|
||||
public function getAthlete():Athlete {
|
||||
|
||||
/**
|
||||
* Obtient l'instance d'athlète.
|
||||
*
|
||||
* @return Athlete L'instance d'athlète.
|
||||
*/
|
||||
public function getAthlete(): Athlete {
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStatistic():?array{
|
||||
/**
|
||||
* Obtient la liste des statistiques de l'athlète.
|
||||
*
|
||||
* @return array|null La liste des statistiques de l'athlète, ou null si aucune.
|
||||
*/
|
||||
public function getStatistic(): ?array {
|
||||
return $this->statsList;
|
||||
}
|
||||
|
||||
public function getActivite():?array{
|
||||
/**
|
||||
* Obtient la liste des activités de l'athlète.
|
||||
*
|
||||
* @return array|null La liste des activités de l'athlète, ou null si aucune.
|
||||
*/
|
||||
public function getActivite(): ?array {
|
||||
return $this->activityList;
|
||||
}
|
||||
|
||||
public function getDataSource():?array{
|
||||
/**
|
||||
* Obtient la liste des sources de données de l'athlète.
|
||||
*
|
||||
* @return array|null La liste des sources de données de l'athlète, ou null si aucune.
|
||||
*/
|
||||
public function getDataSource(): ?array {
|
||||
return $this->dataSourcesList;
|
||||
}
|
||||
|
||||
public function getUsersList(): array{
|
||||
/**
|
||||
* Obtient la liste des utilisateurs associés à l'athlète.
|
||||
*
|
||||
* @return array La liste des utilisateurs associés à l'athlète.
|
||||
*/
|
||||
public function getUsersList(): array {
|
||||
return $this->usersList;
|
||||
}
|
||||
public function getUserList(User $user): \Model\User{
|
||||
|
||||
/**
|
||||
* Obtient un utilisateur spécifique associé à l'athlète.
|
||||
*
|
||||
* @param User $user L'utilisateur recherché.
|
||||
* @return User L'utilisateur recherché.
|
||||
*/
|
||||
public function getUserList(User $user): User {
|
||||
return $user;
|
||||
}
|
||||
public function getTraining(): ?TrainingRepository{
|
||||
return null;
|
||||
|
||||
/**
|
||||
* Obtient le repository des entraînements de l'athlète.
|
||||
*
|
||||
* @return TrainingRepository|null Le repository des entraînements de l'athlète, ou null.
|
||||
* @throws NotImplementedException Si la méthode n'est pas implémentée.
|
||||
*/
|
||||
public function getTraining(): ?TrainingRepository {
|
||||
throw new NotImplementedException("Pas de get Training");
|
||||
}
|
||||
// public function getTrainingsList(): ?array {
|
||||
// if(foreach())
|
||||
// }
|
||||
|
||||
/**
|
||||
* Obtient la liste des entraînements de l'athlète.
|
||||
*
|
||||
* @param Training $training L'entraînement recherché.
|
||||
* @return Training|null L'entraînement recherché, ou null si non trouvé.
|
||||
*/
|
||||
public function getTrainingList(Training $training): ?Training {
|
||||
return $training;
|
||||
}
|
||||
|
||||
/**
|
||||
* Modifie la liste des entraînements de l'athlète.
|
||||
*
|
||||
* @param array $newTrainingsList La nouvelle liste des entraînements.
|
||||
*/
|
||||
public function setTrainingsList(array $newTrainingsList): void {
|
||||
$this->trainingRepository->setTrainingsList($newTrainingsList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtient la liste des activités de l'athlète.
|
||||
*
|
||||
* @return array La liste des activités de l'athlète.
|
||||
*/
|
||||
public function getActivities(): array {
|
||||
return $this->activityList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si un utilisateur peut être ajouté en tant qu'athlète.
|
||||
*
|
||||
* @param User $user L'utilisateur à vérifier.
|
||||
* @return bool True si l'utilisateur peut être ajouté, sinon false.
|
||||
*/
|
||||
public function CheckAdd(User $user): bool {
|
||||
if($user instanceof \Model\Athlete){
|
||||
if ($user instanceof Athlete) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public function CheckAddTraining(Training $training) : bool {
|
||||
|
||||
/**
|
||||
* Vérifie si un entraînement peut être ajouté à l'athlète.
|
||||
*
|
||||
* @param Training $training L'entraînement à vérifier.
|
||||
* @return bool False (toujours, car l'athlète ne peut pas avoir d'entraînement).
|
||||
*/
|
||||
public function CheckAddTraining(Training $training): bool {
|
||||
return false;
|
||||
}
|
||||
public function addUser(\Model\User $user): bool
|
||||
{
|
||||
if($this->CheckAdd($user)){
|
||||
|
||||
/**
|
||||
* Ajoute un utilisateur à la liste des utilisateurs associés à l'athlète.
|
||||
*
|
||||
* @param User $user L'utilisateur à ajouter.
|
||||
* @return bool True si l'ajout est réussi, sinon false.
|
||||
*/
|
||||
public function addUser(User $user): bool {
|
||||
if ($this->CheckAdd($user)) {
|
||||
$this->usersList[] = $user;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function removeUser(\Model\User $user): bool
|
||||
{
|
||||
if($this->CheckAdd($user)){
|
||||
/**
|
||||
* Supprime un utilisateur de la liste des utilisateurs associés à l'athlète.
|
||||
*
|
||||
* @param User $user L'utilisateur à supprimer.
|
||||
* @return bool True si la suppression est réussie, sinon false.
|
||||
*/
|
||||
public function removeUser(User $user): bool {
|
||||
if ($this->CheckAdd($user)) {
|
||||
$this->usersList[] = $user;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function delUser(\Model\User $user):bool{
|
||||
if($this->CheckAdd($user)){
|
||||
|
||||
/**
|
||||
* Supprime un utilisateur de la liste des utilisateurs associés à l'athlète (méthode fictive).
|
||||
*
|
||||
* @param User $user L'utilisateur à supprimer.
|
||||
* @return bool True si la suppression est réussie, sinon false.
|
||||
*/
|
||||
public function delUser(User $user): bool {
|
||||
if ($this->CheckAdd($user)) {
|
||||
$this->usersList[] = null;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function addTraining(Training $training): bool {
|
||||
/**
|
||||
* Ajoute une activité à la liste des activités de l'athlète.
|
||||
*
|
||||
* @param Activity $myActivity L'activité à ajouter.
|
||||
* @return bool True si l'ajout est réussi, sinon false.
|
||||
*/
|
||||
public function addActivity(Activity $myActivity): bool {
|
||||
if (isset($myActivity)) {
|
||||
$this->activityList[] = $myActivity;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeTraining(Training $training): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getTrainingsList(): ?array
|
||||
{
|
||||
// TODO: Implement getTrainingsList() method.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function addTraining(Training $training): bool
|
||||
{
|
||||
// TODO: Implement addTraining() method.
|
||||
}
|
||||
|
||||
public function removeTraining(Training $training): bool
|
||||
{
|
||||
// TODO: Implement removeTraining() method.
|
||||
}
|
||||
}
|
||||
?>
|
@ -1,25 +0,0 @@
|
||||
<?php
|
||||
namespace Model;
|
||||
|
||||
use Stub\TrainingRepository;
|
||||
|
||||
abstract class Coach extends Role {
|
||||
|
||||
public abstract function __construct(?TrainingRepository $trainingRepository);
|
||||
|
||||
public abstract function getUsersList(): ?array;
|
||||
public abstract function getUserList(User $user): \Model\User;
|
||||
public abstract function getTraining(): ?TrainingRepository;
|
||||
public abstract function getTrainingsList(): ?array;
|
||||
public abstract function getTrainingList(Training $training): ?Training;
|
||||
|
||||
|
||||
public abstract function CheckAdd(User $user) : bool;
|
||||
public abstract function CheckAddTraining(Training $training) : bool;
|
||||
public abstract function addUser(User $user): bool;
|
||||
public abstract function removeUser(User $user): bool;
|
||||
public abstract function addTraining(Training $training): bool;
|
||||
public abstract function removeTraining(Training $training): bool;
|
||||
}
|
||||
|
||||
?>
|
@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Stub\TrainingRepository;
|
||||
|
||||
class CoachAthlete extends Coach {
|
||||
|
||||
public function __construct(?TrainingRepository $trainingRepository) {
|
||||
$this->trainingRepository = $trainingRepository;
|
||||
}
|
||||
public function getUsersList(): ?array {
|
||||
if (!empty($this->usersList)) {
|
||||
return $this->usersList;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function getUserList(User $user): User {
|
||||
foreach ($this->usersList as $existingUser) {
|
||||
if ($existingUser->getId() === $user->getId()) {
|
||||
return $existingUser; // L'utilisateur est présent dans la liste
|
||||
}
|
||||
}
|
||||
return null; // L'utilisateur n'est pas dans la liste
|
||||
}
|
||||
public function getTraining(): TrainingRepository {
|
||||
return $this->trainingRepository;
|
||||
}
|
||||
public function getTrainingsList(): ?array {
|
||||
if (!empty($this->trainingRepository->getTrainingsList())) {
|
||||
return $this->trainingRepository->getTrainingsList();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function getTrainingList(Training $training): ?Training {
|
||||
foreach ($this->trainingRepository->getTrainingsList() as $existingTraining) {
|
||||
if ($existingTraining->getId() === $training->getId()) {
|
||||
return $existingTraining; // L'utilisateur est présent dans la liste
|
||||
}
|
||||
}
|
||||
return null; // L'utilisateur n'est pas dans la liste
|
||||
}
|
||||
public function CheckAdd(User $user) : bool {
|
||||
if($user->getRole() instanceof \Model\Athlete){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function CheckAddTraining(Training $training) : bool {
|
||||
if($training instanceof \Model\Training){
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function addUser(User $user): bool {
|
||||
if($this->CheckAdd($user)){
|
||||
array_push($this->usersList, $user);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeUser(User $user): bool {
|
||||
if($this->CheckAdd($user)){
|
||||
$key = array_search($user, $this->usersList);
|
||||
if ($key !== false) {
|
||||
array_splice($this->usersList, $key, 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function addTraining(Training $training): bool {
|
||||
if($this->CheckAddTraining($training)){
|
||||
$this->trainingRepository->getTrainingsList()[] = $training;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeTraining(Training $training): bool {
|
||||
if($this->CheckAddTraining($training)){
|
||||
$array = (array)$this->trainingRepository->getTrainingsList();
|
||||
$key = array_search($training, $array);
|
||||
if ($key !== false) {
|
||||
array_splice($array, $key, 1);
|
||||
$this->trainingRepository->setTrainingsList($array);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
@ -1,7 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Model;
|
||||
|
||||
abstract class Data {
|
||||
private int $idData;
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Cassandra\Date;
|
||||
|
||||
class DataSource
|
||||
{
|
||||
private int $idSource;
|
||||
private enum $type;
|
||||
private String $model;
|
||||
private enum $precision;
|
||||
private Date $dateLastUse;
|
||||
public function getDataSource(DataSource $dataSource):String {
|
||||
return $this->__to_String($dataSource);
|
||||
}
|
||||
public function __to_String(DataSource $dataSource):String{
|
||||
return "Source de données :" . $dataSource;
|
||||
}
|
||||
}
|
@ -1,32 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Cassandra\Time;
|
||||
|
||||
class HeartRate extends Data {
|
||||
private float $altitude;
|
||||
private time $time;
|
||||
private int $bpm;
|
||||
private float $longitude;
|
||||
private float $latitude;
|
||||
private float $temperature;
|
||||
public function getAltitude():String{
|
||||
return $this->altitude;
|
||||
}
|
||||
public function getTime():String{
|
||||
return $this->time;
|
||||
}
|
||||
public function getBpm():String{
|
||||
return $this->bpm;
|
||||
}
|
||||
public function getLongitude():String{
|
||||
return $this->longitude;
|
||||
}
|
||||
public function getLatitude():String{
|
||||
return $this->altitude;
|
||||
}
|
||||
public function getTemperature():String{
|
||||
return $this->temperature;
|
||||
}
|
||||
}
|
@ -1,36 +1,117 @@
|
||||
<?php
|
||||
/**
|
||||
* Nom du fichier: Role.php
|
||||
*
|
||||
* @author PEREDERII Antoine
|
||||
* @date 2023-11-25
|
||||
* @description Classe abstraite Role représentant le rôle d'un utilisateur.
|
||||
*
|
||||
* @package model
|
||||
*/
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Model\User;
|
||||
use PhpParser\Node\Expr\Array_;
|
||||
use Model\Coach;
|
||||
use Stub\TrainingRepository;
|
||||
|
||||
/**
|
||||
* @class Role
|
||||
* @brief Classe abstraite représentant le rôle d'un utilisateur.
|
||||
*/
|
||||
abstract class Role {
|
||||
protected int $id;
|
||||
protected array $usersList = [];
|
||||
protected ?TrainingRepository $trainingRepository;
|
||||
|
||||
/**
|
||||
* Constructeur abstrait de la classe Role.
|
||||
*
|
||||
* @param TrainingRepository|null $trainingRepository Le repository des entraînements (optionnel).
|
||||
*/
|
||||
public abstract function __construct(?TrainingRepository $trainingRepository);
|
||||
|
||||
// Méthode pour ajouter un utilisateur à la liste
|
||||
|
||||
/**
|
||||
* Obtient la liste des utilisateurs associés au rôle.
|
||||
*
|
||||
* @return array|null La liste des utilisateurs associés au rôle, ou null si aucune.
|
||||
*/
|
||||
public abstract function getUsersList(): ?array;
|
||||
public abstract function getUserList(User $user): \Model\User;
|
||||
|
||||
/**
|
||||
* Obtient un utilisateur spécifique associé au rôle.
|
||||
*
|
||||
* @param User $user L'utilisateur recherché.
|
||||
* @return User L'utilisateur recherché.
|
||||
*/
|
||||
public abstract function getUserList(User $user): User;
|
||||
|
||||
/**
|
||||
* Obtient le repository des entraînements associé au rôle.
|
||||
*
|
||||
* @return TrainingRepository|null Le repository des entraînements associé au rôle, ou null.
|
||||
*/
|
||||
public abstract function getTraining(): ?TrainingRepository;
|
||||
|
||||
/**
|
||||
* Obtient la liste des entraînements associés au rôle.
|
||||
*
|
||||
* @return array|null La liste des entraînements associés au rôle, ou null si aucune.
|
||||
*/
|
||||
public abstract function getTrainingsList(): ?array;
|
||||
|
||||
/**
|
||||
* Obtient un entraînement spécifique associé au rôle.
|
||||
*
|
||||
* @param Training $training L'entraînement recherché.
|
||||
* @return Training|null L'entraînement recherché, ou null si non trouvé.
|
||||
*/
|
||||
public abstract function getTrainingList(Training $training): ?Training;
|
||||
|
||||
/**
|
||||
* Vérifie si un utilisateur peut être ajouté au rôle.
|
||||
*
|
||||
* @param User $user L'utilisateur à vérifier.
|
||||
* @return bool True si l'utilisateur peut être ajouté, sinon false.
|
||||
*/
|
||||
public abstract function CheckAdd(User $user): bool;
|
||||
|
||||
/**
|
||||
* Vérifie si un entraînement peut être ajouté au rôle.
|
||||
*
|
||||
* @param Training $training L'entraînement à vérifier.
|
||||
* @return bool True si l'entraînement peut être ajouté, sinon false.
|
||||
*/
|
||||
public abstract function CheckAddTraining(Training $training): bool;
|
||||
|
||||
public abstract function CheckAdd(User $user) : bool;
|
||||
public abstract function CheckAddTraining(Training $training) : bool;
|
||||
/**
|
||||
* Ajoute un utilisateur à la liste des utilisateurs associés au rôle.
|
||||
*
|
||||
* @param User $user L'utilisateur à ajouter.
|
||||
* @return bool True si l'ajout est réussi, sinon false.
|
||||
*/
|
||||
public abstract function addUser(User $user): bool;
|
||||
|
||||
/**
|
||||
* Supprime un utilisateur de la liste des utilisateurs associés au rôle.
|
||||
*
|
||||
* @param User $user L'utilisateur à supprimer.
|
||||
* @return bool True si la suppression est réussie, sinon false.
|
||||
*/
|
||||
public abstract function removeUser(User $user): bool;
|
||||
|
||||
/**
|
||||
* Ajoute un entraînement à la liste des entraînements associés au rôle.
|
||||
*
|
||||
* @param Training $training L'entraînement à ajouter.
|
||||
* @return bool True si l'ajout est réussi, sinon false.
|
||||
*/
|
||||
public abstract function addTraining(Training $training): bool;
|
||||
|
||||
/**
|
||||
* Supprime un entraînement de la liste des entraînements associés au rôle.
|
||||
*
|
||||
* @param Training $training L'entraînement à supprimer.
|
||||
* @return bool True si la suppression est réussie, sinon false.
|
||||
*/
|
||||
public abstract function removeTraining(Training $training): bool;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
?>
|
@ -1,44 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Cassandra\Time;
|
||||
|
||||
class Statistic
|
||||
{
|
||||
private int $idStatistic;
|
||||
private float $totalDistance;
|
||||
private float $weight;
|
||||
private time $totalTime;
|
||||
private int $avrHeartRate;
|
||||
private int $minHeartRate;
|
||||
private int $maxHeartRate;
|
||||
private int $caloriesBurned;
|
||||
public function __construct(
|
||||
int $idStatistic,
|
||||
float $totalDistance,
|
||||
float $weight,
|
||||
time $totalTime,
|
||||
int $avrHeartRate,
|
||||
int $minHeartRate,
|
||||
int $maxHeartRate,
|
||||
int $caloriesBurned
|
||||
) {
|
||||
$this->idStatistic = $idStatistic;
|
||||
$this->totalDistance = $totalDistance;
|
||||
$this->weight = $weight;
|
||||
$this->totalTime = $totalTime;
|
||||
$this->avrHeartRate = $avrHeartRate;
|
||||
$this->minHeartRate = $minHeartRate;
|
||||
$this->maxHeartRate = $maxHeartRate;
|
||||
$this->caloriesBurned = $caloriesBurned;
|
||||
}
|
||||
|
||||
public function getStatistic():Statistic{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function __toString(Statistic $stat):String{
|
||||
return "Statistiques : " . $this->getStatistic();
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Cassandra\Date;
|
||||
use SebastianBergmann\CodeCoverage\Report\Text;
|
||||
|
||||
class Training
|
||||
{
|
||||
private int $idTraining;
|
||||
private \DateTime $date;
|
||||
private float $latitude;
|
||||
private float $longitude;
|
||||
private ?String $description;
|
||||
private ?String $feedback;
|
||||
|
||||
public function __construct(
|
||||
int $idTraining,
|
||||
\DateTime $date,
|
||||
float $latitude,
|
||||
float $longitude,
|
||||
?String $description = null,
|
||||
?String $feedback = null
|
||||
) {
|
||||
$this->idTraining = $idTraining;
|
||||
$this->date = $date;
|
||||
$this->latitude = $latitude;
|
||||
$this->longitude = $longitude;
|
||||
$this->description = $description;
|
||||
$this->feedback = $feedback;
|
||||
}
|
||||
public function getId():int {
|
||||
return $this->idTraining;
|
||||
}
|
||||
public function getDate():\DateTime {
|
||||
return $this->date;
|
||||
}
|
||||
public function getLocation(): String {
|
||||
return $this->longitude . $this->latitude;
|
||||
}
|
||||
public function getDescription(): String
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
public function getFeedback(): String {
|
||||
return $this->feedback;
|
||||
}
|
||||
|
||||
public function __toString(): String {
|
||||
return $this->idTraining . " - " . $this->description;
|
||||
}
|
||||
}
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,161 @@
|
||||
<?php
|
||||
/**
|
||||
* Nom du fichier: ActivityManager.php
|
||||
*
|
||||
* @author PEREDERII Antoine
|
||||
* @date 2023-11-25
|
||||
* @description Classe ActivityManager pour gérer les opérations liées aux activités avec l'upload de données de fichiers .fit.
|
||||
*
|
||||
* @package manager
|
||||
*/
|
||||
namespace Manager;
|
||||
|
||||
use adriangibbons\phpFITFileAnalysis;
|
||||
use Exception;
|
||||
use Model\Activity;
|
||||
use Stub\AuthService;
|
||||
|
||||
/**
|
||||
* @class ActivityManager
|
||||
* @brief Classe pour gérer les opérations liées aux activités.
|
||||
*/
|
||||
class ActivityManager
|
||||
{
|
||||
private AuthService $authService;
|
||||
|
||||
/**
|
||||
* Constructeur de la classe ActivityManager.
|
||||
*
|
||||
* @param AuthService $authService Le service d'authentification utilisé pour vérifier l'utilisateur actuel.
|
||||
*/
|
||||
public function __construct(AuthService $authService)
|
||||
{
|
||||
$this->authService = $authService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enregistre les données d'un fichier FIT au format JSON.
|
||||
*
|
||||
* @param object $monFichierFit L'objet FIT File à partir duquel extraire les données.
|
||||
* @return bool Retourne true en cas de succès, sinon false.
|
||||
* @throws Exception En cas d'erreur lors de l'ouverture ou de l'enregistrement du fichier FIT.
|
||||
*/
|
||||
public function saveFitFileToJSON($monFichierFit): bool
|
||||
{
|
||||
try {
|
||||
// Extraction des données du fichier FIT
|
||||
$fitData = [
|
||||
'timestamps' => $monFichierFit->data_mesgs['record']['timestamp'],
|
||||
'latitudes' => $monFichierFit->data_mesgs['record']['position_lat'],
|
||||
'longitudes' => $monFichierFit->data_mesgs['record']['position_long'],
|
||||
'altitudes' => $monFichierFit->data_mesgs['record']['altitude'],
|
||||
'heartRates' => $monFichierFit->data_mesgs['record']['heart_rate'],
|
||||
'cadences' => $monFichierFit->data_mesgs['record']['cadence'],
|
||||
'distances' => $monFichierFit->data_mesgs['record']['distance'],
|
||||
'speeds' => $monFichierFit->data_mesgs['record']['speed'],
|
||||
'powers' => $monFichierFit->data_mesgs['record']['power'],
|
||||
'temperatures' => $monFichierFit->data_mesgs['record']['temperature'],
|
||||
];
|
||||
|
||||
// Conversion des données en format JSON
|
||||
$jsonFitData = json_encode($fitData, JSON_PRETTY_PRINT);
|
||||
|
||||
// Enregistrement du fichier JSON
|
||||
file_put_contents('/Users/Perederii/SAE/git/Web/Sources/src/data/model/fitFileSaver/jsonFiles/ActivitySave.json', $jsonFitData);
|
||||
|
||||
return true;
|
||||
} catch (\Exception $e) {
|
||||
echo $e;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Télécharge un fichier FIT, extrait les données pertinentes et crée une nouvelle activité associée.
|
||||
*
|
||||
* @param string $type Le type d'activité.
|
||||
* @param int $effortRessenti L'effort ressenti pour l'activité.
|
||||
* @param string|resource $file_path_or_data Le chemin du fichier FIT ou les données brutes du fichier FIT.
|
||||
* @param array|null $options Les options de téléchargement du fichier FIT (facultatif).
|
||||
* @return bool Retourne true en cas de succès, sinon false.
|
||||
* @throws Exception En cas d'erreur lors du téléchargement, du traitement ou de l'enregistrement des données.
|
||||
*/
|
||||
public function uploadFile($type, $effortRessenti, $file_path_or_data, ?array $options = null): bool
|
||||
{
|
||||
try {
|
||||
// Vérification des options par défaut
|
||||
if (empty($options)) {
|
||||
$options = [
|
||||
'fix_data' => ['all'],
|
||||
'data_every_second' => false,
|
||||
'units' => 'metric',
|
||||
'pace' => true,
|
||||
'garmin_timestamps' => false,
|
||||
'overwrite_with_dev_data' => false
|
||||
];
|
||||
}
|
||||
|
||||
// Ouverture du fichier FIT
|
||||
if (!($monFichierFit = new phpFITFileAnalysis($file_path_or_data, $options))) {
|
||||
throw new Exception("Problème lors de l'ouverture du fichier FIT");
|
||||
}
|
||||
|
||||
// Extraction du premier et du dernier timestamp
|
||||
$firstTimestamp = $monFichierFit->data_mesgs['record']['timestamp'][0];
|
||||
$lastTimestamp = end($monFichierFit->data_mesgs['record']['timestamp']);
|
||||
|
||||
// Conversion des timestamps en objets DateTime
|
||||
$startDate = \DateTime::createFromFormat('Y-m-d', date('Y-m-d', $firstTimestamp));
|
||||
$startTime = \DateTime::createFromFormat('H:i:s', date('H:i:s', $firstTimestamp));
|
||||
$endTime = ($lastTimestamp) ? \DateTime::createFromFormat('H:i:s', date('H:i:s', $lastTimestamp)) : null;
|
||||
|
||||
// Vérification des conversions en DateTime
|
||||
if (!$startDate || !$startTime || ($lastTimestamp && !$endTime)) {
|
||||
throw new \Exception("La conversion en DateTime a échoué.");
|
||||
}
|
||||
|
||||
// Extraction des autres données nécessaires
|
||||
$heartRateList = $monFichierFit->data_mesgs['record']['heart_rate'];
|
||||
$variability = max($heartRateList) - min($heartRateList);
|
||||
$average = number_format(array_sum($heartRateList) / count($heartRateList), 2);
|
||||
$varianceV = array_sum(array_map(fn($x) => pow($x - $average, 2), $heartRateList)) / count($heartRateList);
|
||||
$variance = number_format($varianceV, 2);
|
||||
$standardDeviation = number_format(sqrt($variance), 2);
|
||||
$maximum = max($heartRateList);
|
||||
$minimum = min($heartRateList);
|
||||
|
||||
$temperatureList = $monFichierFit->data_mesgs['record']['temperature'];
|
||||
$averageTemperature = (!empty($temperatureList)) ? number_format(array_sum($temperatureList) / count($temperatureList), 1) : -200;
|
||||
|
||||
$isPaused = count($monFichierFit->isPaused()) > 0;
|
||||
|
||||
// Création de l'objet Activity
|
||||
$newActivity = new Activity(
|
||||
$type,
|
||||
$startDate,
|
||||
$startTime,
|
||||
$endTime,
|
||||
$effortRessenti,
|
||||
$variability,
|
||||
$variance,
|
||||
$standardDeviation,
|
||||
$average,
|
||||
$maximum,
|
||||
$minimum,
|
||||
$averageTemperature,
|
||||
$isPaused
|
||||
);
|
||||
|
||||
// Ajout de l'activité et enregistrement du fichier FIT en JSON
|
||||
if ($this->authService->currentUser->getRole()->addActivity($newActivity) && $this->saveFitFileToJSON($monFichierFit)) {
|
||||
return true;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
echo $e;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
?>
|
@ -1,109 +1,44 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Nom du fichier: AthleteManager.php
|
||||
*
|
||||
* @author PEREDERII Antoine
|
||||
* @date 2023-11-25
|
||||
* @description Classe AthleteManager pour gérer les opérations liées aux athlètes et à leurs activités.
|
||||
*
|
||||
* @package VotrePackage
|
||||
*/
|
||||
namespace Manager;
|
||||
|
||||
use Model\Athlete;
|
||||
use Model\Coach;
|
||||
use Model\CoachAthlete;
|
||||
use Model\Training;
|
||||
use Model\User;
|
||||
use Stub\AuthService;
|
||||
|
||||
/**
|
||||
* @class AthleteManager
|
||||
* @brief Classe pour gérer les opérations liées aux athlètes.
|
||||
*/
|
||||
class AthleteManager {
|
||||
private AuthService $authService;
|
||||
|
||||
/**
|
||||
* Constructeur de la classe AthleteManager.
|
||||
*
|
||||
* @param AuthService $authService Le service d'authentification utilisé pour vérifier l'utilisateur actuel.
|
||||
*/
|
||||
function __construct(AuthService $authService)
|
||||
{
|
||||
$this->authService = $authService;
|
||||
}
|
||||
public function getCoachByName(String $coachUsername): ?User {
|
||||
if(($coach = $this->authService->getUserRepository()->getItemByName($coachUsername, 0, 1)) instanceof CoachAthlete) {
|
||||
return $coach;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function getAthleteByName(String $athleteUsername): ?User {
|
||||
if(($athlete =$this->authService->getUserRepository()->getItemByName($athleteUsername, 0, 1)) instanceof Athlete) {
|
||||
return $athlete;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function getUsersList(): ?array
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()->getUsersList()) {
|
||||
return $this->authService->currentUser->getRole()->getUsersList();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function getTrainingsList(): ?array {
|
||||
foreach ($this->authService->getUserRepository()->getItemByRole() as $coach) {
|
||||
foreach ($coach->getUsersList()->getUsername() as $username) {
|
||||
if($this->authService->currentUser->getUsername() == $username) {
|
||||
$this->authService->currentUser->getRole()->setTrainingsList($coach->getTrainingsList());
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()->getTrainingsList()) {
|
||||
return $this->authService->currentUser->getRole()->getTrainingsList();
|
||||
|
||||
/**
|
||||
* Récupère les activités de l'athlète actuel.
|
||||
*
|
||||
* @return array|null Retourne un tableau d'objets Activity en cas de succès, sinon null.
|
||||
*/
|
||||
public function getActivities(): ?array {
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()->getActivities()) {
|
||||
return $this->authService->currentUser->getRole()->getActivities();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function addUser(String $username): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if(($user = $this->authService->getUserRepository()->GetItemByName($username,0,1))) { // count 1 seul et debuis 0 (debut)
|
||||
if ($this->authService->currentUser->getRole()->addUser($user)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeUser(String $username): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if(($user = $this->authService->getUserRepository()->GetItemByName($username,0,1))) { // count 1 seul et debuis 0 (debut)
|
||||
if ($this->authService->currentUser->getRole()->removeUser($user)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function addTraining(Training $training): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if ($this->authService->currentUser->getRole()->addTraining($training)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeTraining(String $trainingId): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if(($training = $this->authService->currentUser->getRole()->getTraining()->getItemById($trainingId))) { // count 1 seul et debuis 0 (debut)
|
||||
if ($this->authService->currentUser->getRole()->removeTraining($training)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// public function getStatistics(User $user) : ?Statistic {
|
||||
// if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
// if (($arrayStat = $this->authService->currentUser->getRole()->getUserList($user)->getStatistic())) {
|
||||
// return $arrayStat;
|
||||
// }
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// public function getAnalyse(User $user): bool {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
?>
|
@ -1,95 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Manager;
|
||||
|
||||
use Model\Coach;
|
||||
use Model\Role;
|
||||
use Model\Statistic;
|
||||
use Model\User;
|
||||
use \Model\Training;
|
||||
use Network\IAuthService;
|
||||
use Stub\AuthService;
|
||||
use Stub\TrainingRepository;
|
||||
use Stub\UserRepository;
|
||||
|
||||
class CoachManager
|
||||
{
|
||||
// public ?User $currentUser = null; // Initialisé à null
|
||||
private AuthService $authService;
|
||||
|
||||
function __construct(AuthService $authService)
|
||||
{
|
||||
$this->authService = $authService;
|
||||
}
|
||||
public function getUsersList(): ?array
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()->getUsersList()) {
|
||||
return $this->authService->currentUser->getRole()->getUsersList();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function getTrainingsList(): ?array {
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()->getTrainingsList()) {
|
||||
return $this->authService->currentUser->getRole()->getTrainingsList();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public function addUser(String $username): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if(($user = $this->authService->getUserRepository()->GetItemByName($username,0,1))) { // count 1 seul et debuis 0 (debut)
|
||||
if ($this->authService->currentUser->getRole()->addUser($user)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeUser(String $username): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if(($user = $this->authService->getUserRepository()->GetItemByName($username,0,1))) { // count 1 seul et debuis 0 (debut)
|
||||
if ($this->authService->currentUser->getRole()->removeUser($user)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function addTraining(Training $training): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if ($this->authService->currentUser->getRole()->addTraining($training)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public function removeTraining(String $trainingId): bool
|
||||
{
|
||||
if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
if(($training = $this->authService->currentUser->getRole()->getTraining()->getItemById($trainingId))) { // count 1 seul et debuis 0 (debut)
|
||||
if ($this->authService->currentUser->getRole()->removeTraining($training)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// public function getStatistics(User $user) : ?Statistic {
|
||||
// if ($this->authService->currentUser && $this->authService->currentUser->getRole()) {
|
||||
// if (($arrayStat = $this->authService->currentUser->getRole()->getUserList($user)->getStatistic())) {
|
||||
// return $arrayStat;
|
||||
// }
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// public function getAnalyse(User $user): bool {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
?>
|
@ -1,23 +1,58 @@
|
||||
<?php
|
||||
/**
|
||||
* @file StubData.php
|
||||
* @brief Définition de la classe StubData.
|
||||
* @details Ce fichier contient la définition de la classe StubData, utilisée pour la gestion des données fictives
|
||||
* dans le cadre des tests et de la simulation.
|
||||
*
|
||||
* @package Stub
|
||||
*/
|
||||
|
||||
namespace Stub;
|
||||
use Model\Athlete;
|
||||
|
||||
use Manager\ActivityManager;
|
||||
use Manager\AthleteManager;
|
||||
use Manager\DataManager;
|
||||
use Manager\UserManager;
|
||||
use Shared\HashPassword;
|
||||
use Stub\AuthService;
|
||||
use Manager\{AthleteManager, CoachManager, DataManager, UserManager};
|
||||
use Stub\UserRepository;
|
||||
|
||||
/**
|
||||
* @class StubData
|
||||
* @brief Classe de gestion des données fictives pour les tests et la simulation.
|
||||
* @details Cette classe fournit des méthodes pour initialiser les gestionnaires d'utilisateurs, d'athlètes et d'activités
|
||||
* avec des données fictives.
|
||||
*
|
||||
* @author Votre Nom
|
||||
* @date YYYY-MM-DD
|
||||
* @author OpenAI
|
||||
*/
|
||||
class StubData extends DataManager {
|
||||
/**
|
||||
* @brief Constructeur de la classe StubData.
|
||||
* @details Initialise les dépôts, les services d'authentification et les gestionnaires nécessaires.
|
||||
*
|
||||
* @author Votre Nom
|
||||
* @date YYYY-MM-DD
|
||||
* @author OpenAI
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
$userRepository = new \Stub\UserRepository();
|
||||
$authService = new \Stub\AuthService($userRepository, new \Shared\HashPassword());
|
||||
// Initialisation du dépôt d'utilisateurs
|
||||
$userRepository = new UserRepository();
|
||||
// Initialisation du service d'authentification
|
||||
$authService = new AuthService($userRepository, new HashPassword());
|
||||
|
||||
// Initialisation du gestionnaire d'utilisateurs
|
||||
$this->userMgr = new UserManager($authService);
|
||||
|
||||
$this->coachMgr = new CoachManager($authService);
|
||||
// Initialisation du gestionnaire d'athlètes
|
||||
$this->athleteMgr = new AthleteManager($authService);
|
||||
|
||||
// Initialisation du gestionnaire d'activités
|
||||
$this->activityMgr = new ActivityManager($authService);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
?>
|
@ -1,86 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Stub;
|
||||
|
||||
use Model\Athlete;
|
||||
use Model\CoachAthlete;
|
||||
use Model\Training;
|
||||
use Model\User;
|
||||
use Repository\ITrainingRepository;
|
||||
|
||||
class TrainingRepository implements ITrainingRepository {
|
||||
private array $trainingsList = [];
|
||||
|
||||
public function __construct() {
|
||||
$this->trainingsList[] = new Training(1, new \DateTime("1985-05-10"), 48.5, 55.8, "john.doe@example.com", "hello");
|
||||
$this->trainingsList[] = new Training(2, new \DateTime("1986-06-12"), 48.5, 55.8, "john.doe@exavdffgmple.com", "hedfdffllo");
|
||||
$this->trainingsList[] = new Training(3, new \DateTime("1989-07-14"), 48.5, 55.8, "john.doe@exdfdfample.com", "hedfdfllo");
|
||||
$this->trainingsList[] = new Training(4, new \DateTime("1990-08-16"), 48.5, 55.8, "john.doe@exdfdfample.com", "hedffhdllo");
|
||||
$this->trainingsList[] = new Training(5, new \DateTime("2000-09-18"), 48.5, 55.8, "john.doe@exdffdample.com", "hedfdfgllo");
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array
|
||||
*/
|
||||
public function &getTrainingsList(): array {
|
||||
return $this->trainingsList;
|
||||
}
|
||||
|
||||
public function setTrainingsList(array $trainingsList): void {
|
||||
$this->trainingsList = $trainingsList;
|
||||
}
|
||||
|
||||
public function getItemById(int $id): ?Training {
|
||||
foreach ($this->trainingsList as $training) {
|
||||
if ($training->getId() === $id) {
|
||||
return $training;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public function GetNbItems(): int {
|
||||
return count($this->trainingsList);
|
||||
}
|
||||
|
||||
public function GetItems(int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false): array {
|
||||
// Cette méthode est un exemple simple, on ne gère pas l'ordonnancement ici
|
||||
return array_slice($this->trainingsList, $index, $count);
|
||||
}
|
||||
|
||||
|
||||
// should have type here
|
||||
public function UpdateItem($oldTraining, $newTraining): void {
|
||||
$index = array_search($oldTraining, $this->trainingsList);
|
||||
if ($index !== false) {
|
||||
$this->trainingsList[$index] = $newTraining;
|
||||
}
|
||||
}
|
||||
|
||||
// should have type here
|
||||
public function AddItem($training): void {
|
||||
$this->trainingsList[] = $training;
|
||||
}
|
||||
|
||||
// should have type here
|
||||
public function DeleteItem($training): bool {
|
||||
$index = array_search($training, $this->trainingsList);
|
||||
if ($index !== false) {
|
||||
unset($this->trainingsList[$index]);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public function GetItemsByName(string $substring, int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false): ?array
|
||||
{
|
||||
return null;
|
||||
// TODO: Implement GetItemsByName() method.
|
||||
}
|
||||
|
||||
public function GetItemByName(string $substring, int $index, int $count, ?string $orderingPropertyName = null, bool $descending = false)
|
||||
{
|
||||
return null;
|
||||
// TODO: Implement GetItemByName() method.
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
// platform_check.php @generated by Composer
|
||||
|
||||
$issues = array();
|
||||
|
||||
if (!(PHP_VERSION_ID >= 70205)) {
|
||||
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.5". 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
|
||||
);
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2020-2023 Graham Campbell <hello@gjcampbell.co.uk>
|
||||
|
||||
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.
|
@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "graham-campbell/result-type",
|
||||
"description": "An Implementation Of The Result Type",
|
||||
"keywords": ["result", "result-type", "Result", "Result Type", "Result-Type", "Graham Campbell", "GrahamCampbell"],
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.2.5 || ^8.0",
|
||||
"phpoption/phpoption": "^1.9.2"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GrahamCampbell\\ResultType\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GrahamCampbell\\Tests\\ResultType\\": "tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"preferred-install": "dist"
|
||||
}
|
||||
}
|
@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of Result Type.
|
||||
*
|
||||
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace GrahamCampbell\ResultType;
|
||||
|
||||
use PhpOption\None;
|
||||
use PhpOption\Some;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @template E
|
||||
*
|
||||
* @extends \GrahamCampbell\ResultType\Result<T,E>
|
||||
*/
|
||||
final class Error extends Result
|
||||
{
|
||||
/**
|
||||
* @var E
|
||||
*/
|
||||
private $value;
|
||||
|
||||
/**
|
||||
* Internal constructor for an error value.
|
||||
*
|
||||
* @param E $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function __construct($value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param F $value
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<T,F>
|
||||
*/
|
||||
public static function create($value)
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \PhpOption\Option<T>
|
||||
*/
|
||||
public function success()
|
||||
{
|
||||
return None::create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,E>
|
||||
*/
|
||||
public function map(callable $f)
|
||||
{
|
||||
return self::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat map over the success value.
|
||||
*
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,F>
|
||||
*/
|
||||
public function flatMap(callable $f)
|
||||
{
|
||||
/** @var \GrahamCampbell\ResultType\Result<S,F> */
|
||||
return self::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \PhpOption\Option<E>
|
||||
*/
|
||||
public function error()
|
||||
{
|
||||
return Some::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<T,F>
|
||||
*/
|
||||
public function mapError(callable $f)
|
||||
{
|
||||
return self::create($f($this->value));
|
||||
}
|
||||
}
|
@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of Result Type.
|
||||
*
|
||||
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace GrahamCampbell\ResultType;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @template E
|
||||
*/
|
||||
abstract class Result
|
||||
{
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \PhpOption\Option<T>
|
||||
*/
|
||||
abstract public function success();
|
||||
|
||||
/**
|
||||
* Map over the success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,E>
|
||||
*/
|
||||
abstract public function map(callable $f);
|
||||
|
||||
/**
|
||||
* Flat map over the success value.
|
||||
*
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,F>
|
||||
*/
|
||||
abstract public function flatMap(callable $f);
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \PhpOption\Option<E>
|
||||
*/
|
||||
abstract public function error();
|
||||
|
||||
/**
|
||||
* Map over the error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<T,F>
|
||||
*/
|
||||
abstract public function mapError(callable $f);
|
||||
}
|
@ -0,0 +1,120 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* This file is part of Result Type.
|
||||
*
|
||||
* (c) Graham Campbell <hello@gjcampbell.co.uk>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace GrahamCampbell\ResultType;
|
||||
|
||||
use PhpOption\None;
|
||||
use PhpOption\Some;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @template E
|
||||
*
|
||||
* @extends \GrahamCampbell\ResultType\Result<T,E>
|
||||
*/
|
||||
final class Success extends Result
|
||||
{
|
||||
/**
|
||||
* @var T
|
||||
*/
|
||||
private $value;
|
||||
|
||||
/**
|
||||
* Internal constructor for a success value.
|
||||
*
|
||||
* @param T $value
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function __construct($value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new error value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param S $value
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,E>
|
||||
*/
|
||||
public static function create($value)
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the success option value.
|
||||
*
|
||||
* @return \PhpOption\Option<T>
|
||||
*/
|
||||
public function success()
|
||||
{
|
||||
return Some::create($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the success value.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):S $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,E>
|
||||
*/
|
||||
public function map(callable $f)
|
||||
{
|
||||
return self::create($f($this->value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat map over the success value.
|
||||
*
|
||||
* @template S
|
||||
* @template F
|
||||
*
|
||||
* @param callable(T):\GrahamCampbell\ResultType\Result<S,F> $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<S,F>
|
||||
*/
|
||||
public function flatMap(callable $f)
|
||||
{
|
||||
return $f($this->value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the error option value.
|
||||
*
|
||||
* @return \PhpOption\Option<E>
|
||||
*/
|
||||
public function error()
|
||||
{
|
||||
return None::create();
|
||||
}
|
||||
|
||||
/**
|
||||
* Map over the error value.
|
||||
*
|
||||
* @template F
|
||||
*
|
||||
* @param callable(E):F $f
|
||||
*
|
||||
* @return \GrahamCampbell\ResultType\Result<T,F>
|
||||
*/
|
||||
public function mapError(callable $f)
|
||||
{
|
||||
return self::create($this->value);
|
||||
}
|
||||
}
|
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed 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.
|
@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "phpoption/phpoption",
|
||||
"description": "Option Type for PHP",
|
||||
"keywords": ["php", "option", "language", "type"],
|
||||
"license": "Apache-2.0",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Johannes M. Schmitt",
|
||||
"email": "schmittjoh@gmail.com",
|
||||
"homepage": "https://github.com/schmittjoh"
|
||||
},
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^7.2.5 || ^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"PhpOption\\": "src/PhpOption/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"PhpOption\\Tests\\": "tests/PhpOption/Tests/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"allow-plugins": {
|
||||
"bamarni/composer-bin-plugin": true
|
||||
},
|
||||
"preferred-install": "dist"
|
||||
},
|
||||
"extra": {
|
||||
"bamarni-bin": {
|
||||
"bin-links": true,
|
||||
"forward-command": true
|
||||
},
|
||||
"branch-alias": {
|
||||
"dev-master": "1.9-dev"
|
||||
}
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"prefer-stable": true
|
||||
}
|
@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
|
||||
*
|
||||
* Licensed 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.
|
||||
*/
|
||||
|
||||
namespace PhpOption;
|
||||
|
||||
use Traversable;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
*
|
||||
* @extends Option<T>
|
||||
*/
|
||||
final class LazyOption extends Option
|
||||
{
|
||||
/** @var callable(mixed...):(Option<T>) */
|
||||
private $callback;
|
||||
|
||||
/** @var array<int, mixed> */
|
||||
private $arguments;
|
||||
|
||||
/** @var Option<T>|null */
|
||||
private $option;
|
||||
|
||||
/**
|
||||
* @template S
|
||||
* @param callable(mixed...):(Option<S>) $callback
|
||||
* @param array<int, mixed> $arguments
|
||||
*
|
||||
* @return LazyOption<S>
|
||||
*/
|
||||
public static function create($callback, array $arguments = []): self
|
||||
{
|
||||
return new self($callback, $arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(mixed...):(Option<T>) $callback
|
||||
* @param array<int, mixed> $arguments
|
||||
*/
|
||||
public function __construct($callback, array $arguments = [])
|
||||
{
|
||||
if (!is_callable($callback)) {
|
||||
throw new \InvalidArgumentException('Invalid callback given');
|
||||
}
|
||||
|
||||
$this->callback = $callback;
|
||||
$this->arguments = $arguments;
|
||||
}
|
||||
|
||||
public function isDefined(): bool
|
||||
{
|
||||
return $this->option()->isDefined();
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return $this->option()->isEmpty();
|
||||
}
|
||||
|
||||
public function get()
|
||||
{
|
||||
return $this->option()->get();
|
||||
}
|
||||
|
||||
public function getOrElse($default)
|
||||
{
|
||||
return $this->option()->getOrElse($default);
|
||||
}
|
||||
|
||||
public function getOrCall($callable)
|
||||
{
|
||||
return $this->option()->getOrCall($callable);
|
||||
}
|
||||
|
||||
public function getOrThrow(\Exception $ex)
|
||||
{
|
||||
return $this->option()->getOrThrow($ex);
|
||||
}
|
||||
|
||||
public function orElse(Option $else)
|
||||
{
|
||||
return $this->option()->orElse($else);
|
||||
}
|
||||
|
||||
public function ifDefined($callable)
|
||||
{
|
||||
$this->option()->forAll($callable);
|
||||
}
|
||||
|
||||
public function forAll($callable)
|
||||
{
|
||||
return $this->option()->forAll($callable);
|
||||
}
|
||||
|
||||
public function map($callable)
|
||||
{
|
||||
return $this->option()->map($callable);
|
||||
}
|
||||
|
||||
public function flatMap($callable)
|
||||
{
|
||||
return $this->option()->flatMap($callable);
|
||||
}
|
||||
|
||||
public function filter($callable)
|
||||
{
|
||||
return $this->option()->filter($callable);
|
||||
}
|
||||
|
||||
public function filterNot($callable)
|
||||
{
|
||||
return $this->option()->filterNot($callable);
|
||||
}
|
||||
|
||||
public function select($value)
|
||||
{
|
||||
return $this->option()->select($value);
|
||||
}
|
||||
|
||||
public function reject($value)
|
||||
{
|
||||
return $this->option()->reject($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Traversable<T>
|
||||
*/
|
||||
public function getIterator(): Traversable
|
||||
{
|
||||
return $this->option()->getIterator();
|
||||
}
|
||||
|
||||
public function foldLeft($initialValue, $callable)
|
||||
{
|
||||
return $this->option()->foldLeft($initialValue, $callable);
|
||||
}
|
||||
|
||||
public function foldRight($initialValue, $callable)
|
||||
{
|
||||
return $this->option()->foldRight($initialValue, $callable);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Option<T>
|
||||
*/
|
||||
private function option(): Option
|
||||
{
|
||||
if (null === $this->option) {
|
||||
/** @var mixed */
|
||||
$option = call_user_func_array($this->callback, $this->arguments);
|
||||
if ($option instanceof Option) {
|
||||
$this->option = $option;
|
||||
} else {
|
||||
throw new \RuntimeException(sprintf('Expected instance of %s', Option::class));
|
||||
}
|
||||
}
|
||||
|
||||
return $this->option;
|
||||
}
|
||||
}
|
@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
|
||||
*
|
||||
* Licensed 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.
|
||||
*/
|
||||
|
||||
namespace PhpOption;
|
||||
|
||||
use EmptyIterator;
|
||||
|
||||
/**
|
||||
* @extends Option<mixed>
|
||||
*/
|
||||
final class None extends Option
|
||||
{
|
||||
/** @var None|null */
|
||||
private static $instance;
|
||||
|
||||
/**
|
||||
* @return None
|
||||
*/
|
||||
public static function create(): self
|
||||
{
|
||||
if (null === self::$instance) {
|
||||
self::$instance = new self();
|
||||
}
|
||||
|
||||
return self::$instance;
|
||||
}
|
||||
|
||||
public function get()
|
||||
{
|
||||
throw new \RuntimeException('None has no value.');
|
||||
}
|
||||
|
||||
public function getOrCall($callable)
|
||||
{
|
||||
return $callable();
|
||||
}
|
||||
|
||||
public function getOrElse($default)
|
||||
{
|
||||
return $default;
|
||||
}
|
||||
|
||||
public function getOrThrow(\Exception $ex)
|
||||
{
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function isDefined(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function orElse(Option $else)
|
||||
{
|
||||
return $else;
|
||||
}
|
||||
|
||||
public function ifDefined($callable)
|
||||
{
|
||||
// Just do nothing in that case.
|
||||
}
|
||||
|
||||
public function forAll($callable)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function map($callable)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function flatMap($callable)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function filter($callable)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function filterNot($callable)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function select($value)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function reject($value)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getIterator(): EmptyIterator
|
||||
{
|
||||
return new EmptyIterator();
|
||||
}
|
||||
|
||||
public function foldLeft($initialValue, $callable)
|
||||
{
|
||||
return $initialValue;
|
||||
}
|
||||
|
||||
public function foldRight($initialValue, $callable)
|
||||
{
|
||||
return $initialValue;
|
||||
}
|
||||
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
}
|
@ -0,0 +1,434 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
|
||||
*
|
||||
* Licensed 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.
|
||||
*/
|
||||
|
||||
namespace PhpOption;
|
||||
|
||||
use ArrayAccess;
|
||||
use IteratorAggregate;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
*
|
||||
* @implements IteratorAggregate<T>
|
||||
*/
|
||||
abstract class Option implements IteratorAggregate
|
||||
{
|
||||
/**
|
||||
* Creates an option given a return value.
|
||||
*
|
||||
* This is intended for consuming existing APIs and allows you to easily
|
||||
* convert them to an option. By default, we treat ``null`` as the None
|
||||
* case, and everything else as Some.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param S $value The actual return value.
|
||||
* @param S $noneValue The value which should be considered "None"; null by
|
||||
* default.
|
||||
*
|
||||
* @return Option<S>
|
||||
*/
|
||||
public static function fromValue($value, $noneValue = null)
|
||||
{
|
||||
if ($value === $noneValue) {
|
||||
return None::create();
|
||||
}
|
||||
|
||||
return new Some($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an option from an array's value.
|
||||
*
|
||||
* If the key does not exist in the array, the array is not actually an
|
||||
* array, or the array's value at the given key is null, None is returned.
|
||||
* Otherwise, Some is returned wrapping the value at the given key.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param array<string|int,S>|ArrayAccess<string|int,S>|null $array A potential array or \ArrayAccess value.
|
||||
* @param string $key The key to check.
|
||||
*
|
||||
* @return Option<S>
|
||||
*/
|
||||
public static function fromArraysValue($array, $key)
|
||||
{
|
||||
if (!(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) {
|
||||
return None::create();
|
||||
}
|
||||
|
||||
return new Some($array[$key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a lazy-option with the given callback.
|
||||
*
|
||||
* This is also a helper constructor for lazy-consuming existing APIs where
|
||||
* the return value is not yet an option. By default, we treat ``null`` as
|
||||
* None case, and everything else as Some.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable $callback The callback to evaluate.
|
||||
* @param array $arguments The arguments for the callback.
|
||||
* @param S $noneValue The value which should be considered "None";
|
||||
* null by default.
|
||||
*
|
||||
* @return LazyOption<S>
|
||||
*/
|
||||
public static function fromReturn($callback, array $arguments = [], $noneValue = null)
|
||||
{
|
||||
return new LazyOption(static function () use ($callback, $arguments, $noneValue) {
|
||||
/** @var mixed */
|
||||
$return = call_user_func_array($callback, $arguments);
|
||||
|
||||
if ($return === $noneValue) {
|
||||
return None::create();
|
||||
}
|
||||
|
||||
return new Some($return);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Option factory, which creates new option based on passed value.
|
||||
*
|
||||
* If value is already an option, it simply returns. If value is callable,
|
||||
* LazyOption with passed callback created and returned. If Option
|
||||
* returned from callback, it returns directly. On other case value passed
|
||||
* to Option::fromValue() method.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param Option<S>|callable|S $value
|
||||
* @param S $noneValue Used when $value is mixed or
|
||||
* callable, for None-check.
|
||||
*
|
||||
* @return Option<S>|LazyOption<S>
|
||||
*/
|
||||
public static function ensure($value, $noneValue = null)
|
||||
{
|
||||
if ($value instanceof self) {
|
||||
return $value;
|
||||
} elseif (is_callable($value)) {
|
||||
return new LazyOption(static function () use ($value, $noneValue) {
|
||||
/** @var mixed */
|
||||
$return = $value();
|
||||
|
||||
if ($return instanceof self) {
|
||||
return $return;
|
||||
} else {
|
||||
return self::fromValue($return, $noneValue);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
return self::fromValue($value, $noneValue);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lift a function so that it accepts Option as parameters.
|
||||
*
|
||||
* We return a new closure that wraps the original callback. If any of the
|
||||
* parameters passed to the lifted function is empty, the function will
|
||||
* return a value of None. Otherwise, we will pass all parameters to the
|
||||
* original callback and return the value inside a new Option, unless an
|
||||
* Option is returned from the function, in which case, we use that.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable $callback
|
||||
* @param mixed $noneValue
|
||||
*
|
||||
* @return callable
|
||||
*/
|
||||
public static function lift($callback, $noneValue = null)
|
||||
{
|
||||
return static function () use ($callback, $noneValue) {
|
||||
/** @var array<int, mixed> */
|
||||
$args = func_get_args();
|
||||
|
||||
$reduced_args = array_reduce(
|
||||
$args,
|
||||
/** @param bool $status */
|
||||
static function ($status, self $o) {
|
||||
return $o->isEmpty() ? true : $status;
|
||||
},
|
||||
false
|
||||
);
|
||||
// if at least one parameter is empty, return None
|
||||
if ($reduced_args) {
|
||||
return None::create();
|
||||
}
|
||||
|
||||
$args = array_map(
|
||||
/** @return T */
|
||||
static function (self $o) {
|
||||
// it is safe to do so because the fold above checked
|
||||
// that all arguments are of type Some
|
||||
/** @var T */
|
||||
return $o->get();
|
||||
},
|
||||
$args
|
||||
);
|
||||
|
||||
return self::ensure(call_user_func_array($callback, $args), $noneValue);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value if available, or throws an exception otherwise.
|
||||
*
|
||||
* @throws \RuntimeException If value is not available.
|
||||
*
|
||||
* @return T
|
||||
*/
|
||||
abstract public function get();
|
||||
|
||||
/**
|
||||
* Returns the value if available, or the default value if not.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param S $default
|
||||
*
|
||||
* @return T|S
|
||||
*/
|
||||
abstract public function getOrElse($default);
|
||||
|
||||
/**
|
||||
* Returns the value if available, or the results of the callable.
|
||||
*
|
||||
* This is preferable over ``getOrElse`` if the computation of the default
|
||||
* value is expensive.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable():S $callable
|
||||
*
|
||||
* @return T|S
|
||||
*/
|
||||
abstract public function getOrCall($callable);
|
||||
|
||||
/**
|
||||
* Returns the value if available, or throws the passed exception.
|
||||
*
|
||||
* @param \Exception $ex
|
||||
*
|
||||
* @return T
|
||||
*/
|
||||
abstract public function getOrThrow(\Exception $ex);
|
||||
|
||||
/**
|
||||
* Returns true if no value is available, false otherwise.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function isEmpty();
|
||||
|
||||
/**
|
||||
* Returns true if a value is available, false otherwise.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
abstract public function isDefined();
|
||||
|
||||
/**
|
||||
* Returns this option if non-empty, or the passed option otherwise.
|
||||
*
|
||||
* This can be used to try multiple alternatives, and is especially useful
|
||||
* with lazy evaluating options:
|
||||
*
|
||||
* ```php
|
||||
* $repo->findSomething()
|
||||
* ->orElse(new LazyOption(array($repo, 'findSomethingElse')))
|
||||
* ->orElse(new LazyOption(array($repo, 'createSomething')));
|
||||
* ```
|
||||
*
|
||||
* @param Option<T> $else
|
||||
*
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function orElse(self $else);
|
||||
|
||||
/**
|
||||
* This is similar to map() below except that the return value has no meaning;
|
||||
* the passed callable is simply executed if the option is non-empty, and
|
||||
* ignored if the option is empty.
|
||||
*
|
||||
* In all cases, the return value of the callable is discarded.
|
||||
*
|
||||
* ```php
|
||||
* $comment->getMaybeFile()->ifDefined(function($file) {
|
||||
* // Do something with $file here.
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If you're looking for something like ``ifEmpty``, you can use ``getOrCall``
|
||||
* and ``getOrElse`` in these cases.
|
||||
*
|
||||
* @deprecated Use forAll() instead.
|
||||
*
|
||||
* @param callable(T):mixed $callable
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
abstract public function ifDefined($callable);
|
||||
|
||||
/**
|
||||
* This is similar to map() except that the return value of the callable has no meaning.
|
||||
*
|
||||
* The passed callable is simply executed if the option is non-empty, and ignored if the
|
||||
* option is empty. This method is preferred for callables with side-effects, while map()
|
||||
* is intended for callables without side-effects.
|
||||
*
|
||||
* @param callable(T):mixed $callable
|
||||
*
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function forAll($callable);
|
||||
|
||||
/**
|
||||
* Applies the callable to the value of the option if it is non-empty,
|
||||
* and returns the return value of the callable wrapped in Some().
|
||||
*
|
||||
* If the option is empty, then the callable is not applied.
|
||||
*
|
||||
* ```php
|
||||
* (new Some("foo"))->map('strtoupper')->get(); // "FOO"
|
||||
* ```
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):S $callable
|
||||
*
|
||||
* @return Option<S>
|
||||
*/
|
||||
abstract public function map($callable);
|
||||
|
||||
/**
|
||||
* Applies the callable to the value of the option if it is non-empty, and
|
||||
* returns the return value of the callable directly.
|
||||
*
|
||||
* In contrast to ``map``, the return value of the callable is expected to
|
||||
* be an Option itself; it is not automatically wrapped in Some().
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param callable(T):Option<S> $callable must return an Option
|
||||
*
|
||||
* @return Option<S>
|
||||
*/
|
||||
abstract public function flatMap($callable);
|
||||
|
||||
/**
|
||||
* If the option is empty, it is returned immediately without applying the callable.
|
||||
*
|
||||
* If the option is non-empty, the callable is applied, and if it returns true,
|
||||
* the option itself is returned; otherwise, None is returned.
|
||||
*
|
||||
* @param callable(T):bool $callable
|
||||
*
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function filter($callable);
|
||||
|
||||
/**
|
||||
* If the option is empty, it is returned immediately without applying the callable.
|
||||
*
|
||||
* If the option is non-empty, the callable is applied, and if it returns false,
|
||||
* the option itself is returned; otherwise, None is returned.
|
||||
*
|
||||
* @param callable(T):bool $callable
|
||||
*
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function filterNot($callable);
|
||||
|
||||
/**
|
||||
* If the option is empty, it is returned immediately.
|
||||
*
|
||||
* If the option is non-empty, and its value does not equal the passed value
|
||||
* (via a shallow comparison ===), then None is returned. Otherwise, the
|
||||
* Option is returned.
|
||||
*
|
||||
* In other words, this will filter all but the passed value.
|
||||
*
|
||||
* @param T $value
|
||||
*
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function select($value);
|
||||
|
||||
/**
|
||||
* If the option is empty, it is returned immediately.
|
||||
*
|
||||
* If the option is non-empty, and its value does equal the passed value (via
|
||||
* a shallow comparison ===), then None is returned; otherwise, the Option is
|
||||
* returned.
|
||||
*
|
||||
* In other words, this will let all values through except the passed value.
|
||||
*
|
||||
* @param T $value
|
||||
*
|
||||
* @return Option<T>
|
||||
*/
|
||||
abstract public function reject($value);
|
||||
|
||||
/**
|
||||
* Binary operator for the initial value and the option's value.
|
||||
*
|
||||
* If empty, the initial value is returned. If non-empty, the callable
|
||||
* receives the initial value and the option's value as arguments.
|
||||
*
|
||||
* ```php
|
||||
*
|
||||
* $some = new Some(5);
|
||||
* $none = None::create();
|
||||
* $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6)
|
||||
* $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1)
|
||||
*
|
||||
* // This can be used instead of something like the following:
|
||||
* $option = Option::fromValue($integerOrNull);
|
||||
* $result = 1;
|
||||
* if ( ! $option->isEmpty()) {
|
||||
* $result += $option->get();
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param S $initialValue
|
||||
* @param callable(S, T):S $callable
|
||||
*
|
||||
* @return S
|
||||
*/
|
||||
abstract public function foldLeft($initialValue, $callable);
|
||||
|
||||
/**
|
||||
* foldLeft() but with reversed arguments for the callable.
|
||||
*
|
||||
* @template S
|
||||
*
|
||||
* @param S $initialValue
|
||||
* @param callable(T, S):S $callable
|
||||
*
|
||||
* @return S
|
||||
*/
|
||||
abstract public function foldRight($initialValue, $callable);
|
||||
}
|
@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com>
|
||||
*
|
||||
* Licensed 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.
|
||||
*/
|
||||
|
||||
namespace PhpOption;
|
||||
|
||||
use ArrayIterator;
|
||||
|
||||
/**
|
||||
* @template T
|
||||
*
|
||||
* @extends Option<T>
|
||||
*/
|
||||
final class Some extends Option
|
||||
{
|
||||
/** @var T */
|
||||
private $value;
|
||||
|
||||
/**
|
||||
* @param T $value
|
||||
*/
|
||||
public function __construct($value)
|
||||
{
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template U
|
||||
*
|
||||
* @param U $value
|
||||
*
|
||||
* @return Some<U>
|
||||
*/
|
||||
public static function create($value): self
|
||||
{
|
||||
return new self($value);
|
||||
}
|
||||
|
||||
public function isDefined(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function isEmpty(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function get()
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getOrElse($default)
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getOrCall($callable)
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function getOrThrow(\Exception $ex)
|
||||
{
|
||||
return $this->value;
|
||||
}
|
||||
|
||||
public function orElse(Option $else)
|
||||
{
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function ifDefined($callable)
|
||||
{
|
||||
$this->forAll($callable);
|
||||
}
|
||||
|
||||
public function forAll($callable)
|
||||
{
|
||||
$callable($this->value);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function map($callable)
|
||||
{
|
||||
return new self($callable($this->value));
|
||||
}
|
||||
|
||||
public function flatMap($callable)
|
||||
{
|
||||
/** @var mixed */
|
||||
$rs = $callable($this->value);
|
||||
if (!$rs instanceof Option) {
|
||||
throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?');
|
||||
}
|
||||
|
||||
return $rs;
|
||||
}
|
||||
|
||||
public function filter($callable)
|
||||
{
|
||||
if (true === $callable($this->value)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
return None::create();
|
||||
}
|
||||
|
||||
public function filterNot($callable)
|
||||
{
|
||||
if (false === $callable($this->value)) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
return None::create();
|
||||
}
|
||||
|
||||
public function select($value)
|
||||
{
|
||||
if ($this->value === $value) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
return None::create();
|
||||
}
|
||||
|
||||
public function reject($value)
|
||||
{
|
||||
if ($this->value === $value) {
|
||||
return None::create();
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ArrayIterator<int, T>
|
||||
*/
|
||||
public function getIterator(): ArrayIterator
|
||||
{
|
||||
return new ArrayIterator([$this->value]);
|
||||
}
|
||||
|
||||
public function foldLeft($initialValue, $callable)
|
||||
{
|
||||
return $callable($initialValue, $this->value);
|
||||
}
|
||||
|
||||
public function foldRight($initialValue, $callable)
|
||||
{
|
||||
return $callable($this->value, $initialValue);
|
||||
}
|
||||
}
|
@ -0,0 +1,232 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Polyfill\Ctype;
|
||||
|
||||
/**
|
||||
* Ctype implementation through regex.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @author Gert de Pagter <BackEndTea@gmail.com>
|
||||
*/
|
||||
final class Ctype
|
||||
{
|
||||
/**
|
||||
* Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-alnum
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_alnum($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is a letter, FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-alpha
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_alpha($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-cntrl
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_cntrl($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-digit
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_digit($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-graph
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_graph($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is a lowercase letter.
|
||||
*
|
||||
* @see https://php.net/ctype-lower
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_lower($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all.
|
||||
*
|
||||
* @see https://php.net/ctype-print
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_print($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-punct
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_punct($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters.
|
||||
*
|
||||
* @see https://php.net/ctype-space
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_space($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is an uppercase letter.
|
||||
*
|
||||
* @see https://php.net/ctype-upper
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_upper($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise.
|
||||
*
|
||||
* @see https://php.net/ctype-xdigit
|
||||
*
|
||||
* @param mixed $text
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function ctype_xdigit($text)
|
||||
{
|
||||
$text = self::convert_int_to_char_for_ctype($text, __FUNCTION__);
|
||||
|
||||
return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts integers to their char versions according to normal ctype behaviour, if needed.
|
||||
*
|
||||
* If an integer between -128 and 255 inclusive is provided,
|
||||
* it is interpreted as the ASCII value of a single character
|
||||
* (negative values have 256 added in order to allow characters in the Extended ASCII range).
|
||||
* Any other integer is interpreted as a string containing the decimal digits of the integer.
|
||||
*
|
||||
* @param mixed $int
|
||||
* @param string $function
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
private static function convert_int_to_char_for_ctype($int, $function)
|
||||
{
|
||||
if (!\is_int($int)) {
|
||||
return $int;
|
||||
}
|
||||
|
||||
if ($int < -128 || $int > 255) {
|
||||
return (string) $int;
|
||||
}
|
||||
|
||||
if (\PHP_VERSION_ID >= 80100) {
|
||||
@trigger_error($function.'(): Argument of type int will be interpreted as string in the future', \E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
if ($int < 0) {
|
||||
$int += 256;
|
||||
}
|
||||
|
||||
return \chr($int);
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2018-present Fabien Potencier
|
||||
|
||||
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.
|
@ -0,0 +1,12 @@
|
||||
Symfony Polyfill / Ctype
|
||||
========================
|
||||
|
||||
This component provides `ctype_*` functions to users who run php versions without the ctype extension.
|
||||
|
||||
More information can be found in the
|
||||
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
This library is released under the [MIT license](LICENSE).
|
@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use Symfony\Polyfill\Ctype as p;
|
||||
|
||||
if (\PHP_VERSION_ID >= 80000) {
|
||||
return require __DIR__.'/bootstrap80.php';
|
||||
}
|
||||
|
||||
if (!function_exists('ctype_alnum')) {
|
||||
function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); }
|
||||
}
|
||||
if (!function_exists('ctype_alpha')) {
|
||||
function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); }
|
||||
}
|
||||
if (!function_exists('ctype_cntrl')) {
|
||||
function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); }
|
||||
}
|
||||
if (!function_exists('ctype_digit')) {
|
||||
function ctype_digit($text) { return p\Ctype::ctype_digit($text); }
|
||||
}
|
||||
if (!function_exists('ctype_graph')) {
|
||||
function ctype_graph($text) { return p\Ctype::ctype_graph($text); }
|
||||
}
|
||||
if (!function_exists('ctype_lower')) {
|
||||
function ctype_lower($text) { return p\Ctype::ctype_lower($text); }
|
||||
}
|
||||
if (!function_exists('ctype_print')) {
|
||||
function ctype_print($text) { return p\Ctype::ctype_print($text); }
|
||||
}
|
||||
if (!function_exists('ctype_punct')) {
|
||||
function ctype_punct($text) { return p\Ctype::ctype_punct($text); }
|
||||
}
|
||||
if (!function_exists('ctype_space')) {
|
||||
function ctype_space($text) { return p\Ctype::ctype_space($text); }
|
||||
}
|
||||
if (!function_exists('ctype_upper')) {
|
||||
function ctype_upper($text) { return p\Ctype::ctype_upper($text); }
|
||||
}
|
||||
if (!function_exists('ctype_xdigit')) {
|
||||
function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); }
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use Symfony\Polyfill\Ctype as p;
|
||||
|
||||
if (!function_exists('ctype_alnum')) {
|
||||
function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); }
|
||||
}
|
||||
if (!function_exists('ctype_alpha')) {
|
||||
function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); }
|
||||
}
|
||||
if (!function_exists('ctype_cntrl')) {
|
||||
function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); }
|
||||
}
|
||||
if (!function_exists('ctype_digit')) {
|
||||
function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); }
|
||||
}
|
||||
if (!function_exists('ctype_graph')) {
|
||||
function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); }
|
||||
}
|
||||
if (!function_exists('ctype_lower')) {
|
||||
function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); }
|
||||
}
|
||||
if (!function_exists('ctype_print')) {
|
||||
function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); }
|
||||
}
|
||||
if (!function_exists('ctype_punct')) {
|
||||
function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); }
|
||||
}
|
||||
if (!function_exists('ctype_space')) {
|
||||
function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); }
|
||||
}
|
||||
if (!function_exists('ctype_upper')) {
|
||||
function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); }
|
||||
}
|
||||
if (!function_exists('ctype_xdigit')) {
|
||||
function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); }
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "symfony/polyfill-ctype",
|
||||
"type": "library",
|
||||
"description": "Symfony polyfill for ctype functions",
|
||||
"keywords": ["polyfill", "compatibility", "portable", "ctype"],
|
||||
"homepage": "https://symfony.com",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Gert de Pagter",
|
||||
"email": "BackEndTea@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=7.1"
|
||||
},
|
||||
"provide": {
|
||||
"ext-ctype": "*"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "Symfony\\Polyfill\\Ctype\\": "" },
|
||||
"files": [ "bootstrap.php" ]
|
||||
},
|
||||
"suggest": {
|
||||
"ext-ctype": "For best performance"
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.28-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
"url": "https://github.com/symfony/polyfill"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2015-present Fabien Potencier
|
||||
|
||||
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.
|
@ -0,0 +1,13 @@
|
||||
Symfony Polyfill / Mbstring
|
||||
===========================
|
||||
|
||||
This component provides a partial, native PHP implementation for the
|
||||
[Mbstring](https://php.net/mbstring) extension.
|
||||
|
||||
More information can be found in the
|
||||
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
This library is released under the [MIT license](LICENSE).
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use Symfony\Polyfill\Mbstring as p;
|
||||
|
||||
if (\PHP_VERSION_ID >= 80000) {
|
||||
return require __DIR__.'/bootstrap80.php';
|
||||
}
|
||||
|
||||
if (!function_exists('mb_convert_encoding')) {
|
||||
function mb_convert_encoding($string, $to_encoding, $from_encoding = null) { return p\Mbstring::mb_convert_encoding($string, $to_encoding, $from_encoding); }
|
||||
}
|
||||
if (!function_exists('mb_decode_mimeheader')) {
|
||||
function mb_decode_mimeheader($string) { return p\Mbstring::mb_decode_mimeheader($string); }
|
||||
}
|
||||
if (!function_exists('mb_encode_mimeheader')) {
|
||||
function mb_encode_mimeheader($string, $charset = null, $transfer_encoding = null, $newline = "\r\n", $indent = 0) { return p\Mbstring::mb_encode_mimeheader($string, $charset, $transfer_encoding, $newline, $indent); }
|
||||
}
|
||||
if (!function_exists('mb_decode_numericentity')) {
|
||||
function mb_decode_numericentity($string, $map, $encoding = null) { return p\Mbstring::mb_decode_numericentity($string, $map, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_encode_numericentity')) {
|
||||
function mb_encode_numericentity($string, $map, $encoding = null, $hex = false) { return p\Mbstring::mb_encode_numericentity($string, $map, $encoding, $hex); }
|
||||
}
|
||||
if (!function_exists('mb_convert_case')) {
|
||||
function mb_convert_case($string, $mode, $encoding = null) { return p\Mbstring::mb_convert_case($string, $mode, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_internal_encoding')) {
|
||||
function mb_internal_encoding($encoding = null) { return p\Mbstring::mb_internal_encoding($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_language')) {
|
||||
function mb_language($language = null) { return p\Mbstring::mb_language($language); }
|
||||
}
|
||||
if (!function_exists('mb_list_encodings')) {
|
||||
function mb_list_encodings() { return p\Mbstring::mb_list_encodings(); }
|
||||
}
|
||||
if (!function_exists('mb_encoding_aliases')) {
|
||||
function mb_encoding_aliases($encoding) { return p\Mbstring::mb_encoding_aliases($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_check_encoding')) {
|
||||
function mb_check_encoding($value = null, $encoding = null) { return p\Mbstring::mb_check_encoding($value, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_detect_encoding')) {
|
||||
function mb_detect_encoding($string, $encodings = null, $strict = false) { return p\Mbstring::mb_detect_encoding($string, $encodings, $strict); }
|
||||
}
|
||||
if (!function_exists('mb_detect_order')) {
|
||||
function mb_detect_order($encoding = null) { return p\Mbstring::mb_detect_order($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_parse_str')) {
|
||||
function mb_parse_str($string, &$result = []) { parse_str($string, $result); return (bool) $result; }
|
||||
}
|
||||
if (!function_exists('mb_strlen')) {
|
||||
function mb_strlen($string, $encoding = null) { return p\Mbstring::mb_strlen($string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strpos')) {
|
||||
function mb_strpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strpos($haystack, $needle, $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strtolower')) {
|
||||
function mb_strtolower($string, $encoding = null) { return p\Mbstring::mb_strtolower($string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strtoupper')) {
|
||||
function mb_strtoupper($string, $encoding = null) { return p\Mbstring::mb_strtoupper($string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_substitute_character')) {
|
||||
function mb_substitute_character($substitute_character = null) { return p\Mbstring::mb_substitute_character($substitute_character); }
|
||||
}
|
||||
if (!function_exists('mb_substr')) {
|
||||
function mb_substr($string, $start, $length = 2147483647, $encoding = null) { return p\Mbstring::mb_substr($string, $start, $length, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_stripos')) {
|
||||
function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_stripos($haystack, $needle, $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_stristr')) {
|
||||
function mb_stristr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_stristr($haystack, $needle, $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strrchr')) {
|
||||
function mb_strrchr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrchr($haystack, $needle, $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strrichr')) {
|
||||
function mb_strrichr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strrichr($haystack, $needle, $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strripos')) {
|
||||
function mb_strripos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strripos($haystack, $needle, $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strrpos')) {
|
||||
function mb_strrpos($haystack, $needle, $offset = 0, $encoding = null) { return p\Mbstring::mb_strrpos($haystack, $needle, $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strstr')) {
|
||||
function mb_strstr($haystack, $needle, $before_needle = false, $encoding = null) { return p\Mbstring::mb_strstr($haystack, $needle, $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_get_info')) {
|
||||
function mb_get_info($type = 'all') { return p\Mbstring::mb_get_info($type); }
|
||||
}
|
||||
if (!function_exists('mb_http_output')) {
|
||||
function mb_http_output($encoding = null) { return p\Mbstring::mb_http_output($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strwidth')) {
|
||||
function mb_strwidth($string, $encoding = null) { return p\Mbstring::mb_strwidth($string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_substr_count')) {
|
||||
function mb_substr_count($haystack, $needle, $encoding = null) { return p\Mbstring::mb_substr_count($haystack, $needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_output_handler')) {
|
||||
function mb_output_handler($string, $status) { return p\Mbstring::mb_output_handler($string, $status); }
|
||||
}
|
||||
if (!function_exists('mb_http_input')) {
|
||||
function mb_http_input($type = null) { return p\Mbstring::mb_http_input($type); }
|
||||
}
|
||||
|
||||
if (!function_exists('mb_convert_variables')) {
|
||||
function mb_convert_variables($to_encoding, $from_encoding, &...$vars) { return p\Mbstring::mb_convert_variables($to_encoding, $from_encoding, ...$vars); }
|
||||
}
|
||||
|
||||
if (!function_exists('mb_ord')) {
|
||||
function mb_ord($string, $encoding = null) { return p\Mbstring::mb_ord($string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_chr')) {
|
||||
function mb_chr($codepoint, $encoding = null) { return p\Mbstring::mb_chr($codepoint, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_scrub')) {
|
||||
function mb_scrub($string, $encoding = null) { $encoding = null === $encoding ? mb_internal_encoding() : $encoding; return mb_convert_encoding($string, $encoding, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_str_split')) {
|
||||
function mb_str_split($string, $length = 1, $encoding = null) { return p\Mbstring::mb_str_split($string, $length, $encoding); }
|
||||
}
|
||||
|
||||
if (!function_exists('mb_str_pad')) {
|
||||
function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); }
|
||||
}
|
||||
|
||||
if (extension_loaded('mbstring')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!defined('MB_CASE_UPPER')) {
|
||||
define('MB_CASE_UPPER', 0);
|
||||
}
|
||||
if (!defined('MB_CASE_LOWER')) {
|
||||
define('MB_CASE_LOWER', 1);
|
||||
}
|
||||
if (!defined('MB_CASE_TITLE')) {
|
||||
define('MB_CASE_TITLE', 2);
|
||||
}
|
@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use Symfony\Polyfill\Mbstring as p;
|
||||
|
||||
if (!function_exists('mb_convert_encoding')) {
|
||||
function mb_convert_encoding(array|string|null $string, ?string $to_encoding, array|string|null $from_encoding = null): array|string|false { return p\Mbstring::mb_convert_encoding($string ?? '', (string) $to_encoding, $from_encoding); }
|
||||
}
|
||||
if (!function_exists('mb_decode_mimeheader')) {
|
||||
function mb_decode_mimeheader(?string $string): string { return p\Mbstring::mb_decode_mimeheader((string) $string); }
|
||||
}
|
||||
if (!function_exists('mb_encode_mimeheader')) {
|
||||
function mb_encode_mimeheader(?string $string, ?string $charset = null, ?string $transfer_encoding = null, ?string $newline = "\r\n", ?int $indent = 0): string { return p\Mbstring::mb_encode_mimeheader((string) $string, $charset, $transfer_encoding, (string) $newline, (int) $indent); }
|
||||
}
|
||||
if (!function_exists('mb_decode_numericentity')) {
|
||||
function mb_decode_numericentity(?string $string, array $map, ?string $encoding = null): string { return p\Mbstring::mb_decode_numericentity((string) $string, $map, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_encode_numericentity')) {
|
||||
function mb_encode_numericentity(?string $string, array $map, ?string $encoding = null, ?bool $hex = false): string { return p\Mbstring::mb_encode_numericentity((string) $string, $map, $encoding, (bool) $hex); }
|
||||
}
|
||||
if (!function_exists('mb_convert_case')) {
|
||||
function mb_convert_case(?string $string, ?int $mode, ?string $encoding = null): string { return p\Mbstring::mb_convert_case((string) $string, (int) $mode, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_internal_encoding')) {
|
||||
function mb_internal_encoding(?string $encoding = null): string|bool { return p\Mbstring::mb_internal_encoding($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_language')) {
|
||||
function mb_language(?string $language = null): string|bool { return p\Mbstring::mb_language($language); }
|
||||
}
|
||||
if (!function_exists('mb_list_encodings')) {
|
||||
function mb_list_encodings(): array { return p\Mbstring::mb_list_encodings(); }
|
||||
}
|
||||
if (!function_exists('mb_encoding_aliases')) {
|
||||
function mb_encoding_aliases(?string $encoding): array { return p\Mbstring::mb_encoding_aliases((string) $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_check_encoding')) {
|
||||
function mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool { return p\Mbstring::mb_check_encoding($value, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_detect_encoding')) {
|
||||
function mb_detect_encoding(?string $string, array|string|null $encodings = null, ?bool $strict = false): string|false { return p\Mbstring::mb_detect_encoding((string) $string, $encodings, (bool) $strict); }
|
||||
}
|
||||
if (!function_exists('mb_detect_order')) {
|
||||
function mb_detect_order(array|string|null $encoding = null): array|bool { return p\Mbstring::mb_detect_order($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_parse_str')) {
|
||||
function mb_parse_str(?string $string, &$result = []): bool { parse_str((string) $string, $result); return (bool) $result; }
|
||||
}
|
||||
if (!function_exists('mb_strlen')) {
|
||||
function mb_strlen(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strlen((string) $string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strpos')) {
|
||||
function mb_strpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strpos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strtolower')) {
|
||||
function mb_strtolower(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtolower((string) $string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strtoupper')) {
|
||||
function mb_strtoupper(?string $string, ?string $encoding = null): string { return p\Mbstring::mb_strtoupper((string) $string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_substitute_character')) {
|
||||
function mb_substitute_character(string|int|null $substitute_character = null): string|int|bool { return p\Mbstring::mb_substitute_character($substitute_character); }
|
||||
}
|
||||
if (!function_exists('mb_substr')) {
|
||||
function mb_substr(?string $string, ?int $start, ?int $length = null, ?string $encoding = null): string { return p\Mbstring::mb_substr((string) $string, (int) $start, $length, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_stripos')) {
|
||||
function mb_stripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_stripos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_stristr')) {
|
||||
function mb_stristr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_stristr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strrchr')) {
|
||||
function mb_strrchr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrchr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strrichr')) {
|
||||
function mb_strrichr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strrichr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strripos')) {
|
||||
function mb_strripos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strripos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strrpos')) {
|
||||
function mb_strrpos(?string $haystack, ?string $needle, ?int $offset = 0, ?string $encoding = null): int|false { return p\Mbstring::mb_strrpos((string) $haystack, (string) $needle, (int) $offset, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strstr')) {
|
||||
function mb_strstr(?string $haystack, ?string $needle, ?bool $before_needle = false, ?string $encoding = null): string|false { return p\Mbstring::mb_strstr((string) $haystack, (string) $needle, (bool) $before_needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_get_info')) {
|
||||
function mb_get_info(?string $type = 'all'): array|string|int|false { return p\Mbstring::mb_get_info((string) $type); }
|
||||
}
|
||||
if (!function_exists('mb_http_output')) {
|
||||
function mb_http_output(?string $encoding = null): string|bool { return p\Mbstring::mb_http_output($encoding); }
|
||||
}
|
||||
if (!function_exists('mb_strwidth')) {
|
||||
function mb_strwidth(?string $string, ?string $encoding = null): int { return p\Mbstring::mb_strwidth((string) $string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_substr_count')) {
|
||||
function mb_substr_count(?string $haystack, ?string $needle, ?string $encoding = null): int { return p\Mbstring::mb_substr_count((string) $haystack, (string) $needle, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_output_handler')) {
|
||||
function mb_output_handler(?string $string, ?int $status): string { return p\Mbstring::mb_output_handler((string) $string, (int) $status); }
|
||||
}
|
||||
if (!function_exists('mb_http_input')) {
|
||||
function mb_http_input(?string $type = null): array|string|false { return p\Mbstring::mb_http_input($type); }
|
||||
}
|
||||
|
||||
if (!function_exists('mb_convert_variables')) {
|
||||
function mb_convert_variables(?string $to_encoding, array|string|null $from_encoding, mixed &$var, mixed &...$vars): string|false { return p\Mbstring::mb_convert_variables((string) $to_encoding, $from_encoding ?? '', $var, ...$vars); }
|
||||
}
|
||||
|
||||
if (!function_exists('mb_ord')) {
|
||||
function mb_ord(?string $string, ?string $encoding = null): int|false { return p\Mbstring::mb_ord((string) $string, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_chr')) {
|
||||
function mb_chr(?int $codepoint, ?string $encoding = null): string|false { return p\Mbstring::mb_chr((int) $codepoint, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_scrub')) {
|
||||
function mb_scrub(?string $string, ?string $encoding = null): string { $encoding ??= mb_internal_encoding(); return mb_convert_encoding((string) $string, $encoding, $encoding); }
|
||||
}
|
||||
if (!function_exists('mb_str_split')) {
|
||||
function mb_str_split(?string $string, ?int $length = 1, ?string $encoding = null): array { return p\Mbstring::mb_str_split((string) $string, (int) $length, $encoding); }
|
||||
}
|
||||
|
||||
if (!function_exists('mb_str_pad')) {
|
||||
function mb_str_pad(string $string, int $length, string $pad_string = ' ', int $pad_type = STR_PAD_RIGHT, ?string $encoding = null): string { return p\Mbstring::mb_str_pad($string, $length, $pad_string, $pad_type, $encoding); }
|
||||
}
|
||||
|
||||
if (extension_loaded('mbstring')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!defined('MB_CASE_UPPER')) {
|
||||
define('MB_CASE_UPPER', 0);
|
||||
}
|
||||
if (!defined('MB_CASE_LOWER')) {
|
||||
define('MB_CASE_LOWER', 1);
|
||||
}
|
||||
if (!defined('MB_CASE_TITLE')) {
|
||||
define('MB_CASE_TITLE', 2);
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "symfony/polyfill-mbstring",
|
||||
"type": "library",
|
||||
"description": "Symfony polyfill for the Mbstring extension",
|
||||
"keywords": ["polyfill", "shim", "compatibility", "portable", "mbstring"],
|
||||
"homepage": "https://symfony.com",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Nicolas Grekas",
|
||||
"email": "p@tchwork.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=7.1"
|
||||
},
|
||||
"provide": {
|
||||
"ext-mbstring": "*"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "Symfony\\Polyfill\\Mbstring\\": "" },
|
||||
"files": [ "bootstrap.php" ]
|
||||
},
|
||||
"suggest": {
|
||||
"ext-mbstring": "For best performance"
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.28-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
"url": "https://github.com/symfony/polyfill"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
Copyright (c) 2020-present Fabien Potencier
|
||||
|
||||
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.
|
@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Polyfill\Php80;
|
||||
|
||||
/**
|
||||
* @author Ion Bazan <ion.bazan@gmail.com>
|
||||
* @author Nico Oelgart <nicoswd@gmail.com>
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
final class Php80
|
||||
{
|
||||
public static function fdiv(float $dividend, float $divisor): float
|
||||
{
|
||||
return @($dividend / $divisor);
|
||||
}
|
||||
|
||||
public static function get_debug_type($value): string
|
||||
{
|
||||
switch (true) {
|
||||
case null === $value: return 'null';
|
||||
case \is_bool($value): return 'bool';
|
||||
case \is_string($value): return 'string';
|
||||
case \is_array($value): return 'array';
|
||||
case \is_int($value): return 'int';
|
||||
case \is_float($value): return 'float';
|
||||
case \is_object($value): break;
|
||||
case $value instanceof \__PHP_Incomplete_Class: return '__PHP_Incomplete_Class';
|
||||
default:
|
||||
if (null === $type = @get_resource_type($value)) {
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
if ('Unknown' === $type) {
|
||||
$type = 'closed';
|
||||
}
|
||||
|
||||
return "resource ($type)";
|
||||
}
|
||||
|
||||
$class = \get_class($value);
|
||||
|
||||
if (false === strpos($class, '@')) {
|
||||
return $class;
|
||||
}
|
||||
|
||||
return (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous';
|
||||
}
|
||||
|
||||
public static function get_resource_id($res): int
|
||||
{
|
||||
if (!\is_resource($res) && null === @get_resource_type($res)) {
|
||||
throw new \TypeError(sprintf('Argument 1 passed to get_resource_id() must be of the type resource, %s given', get_debug_type($res)));
|
||||
}
|
||||
|
||||
return (int) $res;
|
||||
}
|
||||
|
||||
public static function preg_last_error_msg(): string
|
||||
{
|
||||
switch (preg_last_error()) {
|
||||
case \PREG_INTERNAL_ERROR:
|
||||
return 'Internal error';
|
||||
case \PREG_BAD_UTF8_ERROR:
|
||||
return 'Malformed UTF-8 characters, possibly incorrectly encoded';
|
||||
case \PREG_BAD_UTF8_OFFSET_ERROR:
|
||||
return 'The offset did not correspond to the beginning of a valid UTF-8 code point';
|
||||
case \PREG_BACKTRACK_LIMIT_ERROR:
|
||||
return 'Backtrack limit exhausted';
|
||||
case \PREG_RECURSION_LIMIT_ERROR:
|
||||
return 'Recursion limit exhausted';
|
||||
case \PREG_JIT_STACKLIMIT_ERROR:
|
||||
return 'JIT stack limit exhausted';
|
||||
case \PREG_NO_ERROR:
|
||||
return 'No error';
|
||||
default:
|
||||
return 'Unknown error';
|
||||
}
|
||||
}
|
||||
|
||||
public static function str_contains(string $haystack, string $needle): bool
|
||||
{
|
||||
return '' === $needle || false !== strpos($haystack, $needle);
|
||||
}
|
||||
|
||||
public static function str_starts_with(string $haystack, string $needle): bool
|
||||
{
|
||||
return 0 === strncmp($haystack, $needle, \strlen($needle));
|
||||
}
|
||||
|
||||
public static function str_ends_with(string $haystack, string $needle): bool
|
||||
{
|
||||
if ('' === $needle || $needle === $haystack) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ('' === $haystack) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$needleLength = \strlen($needle);
|
||||
|
||||
return $needleLength <= \strlen($haystack) && 0 === substr_compare($haystack, $needle, -$needleLength);
|
||||
}
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Polyfill\Php80;
|
||||
|
||||
/**
|
||||
* @author Fedonyuk Anton <info@ensostudio.ru>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class PhpToken implements \Stringable
|
||||
{
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
public $id;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public $text;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
public $line;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
public $pos;
|
||||
|
||||
public function __construct(int $id, string $text, int $line = -1, int $position = -1)
|
||||
{
|
||||
$this->id = $id;
|
||||
$this->text = $text;
|
||||
$this->line = $line;
|
||||
$this->pos = $position;
|
||||
}
|
||||
|
||||
public function getTokenName(): ?string
|
||||
{
|
||||
if ('UNKNOWN' === $name = token_name($this->id)) {
|
||||
$name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text;
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|string|array $kind
|
||||
*/
|
||||
public function is($kind): bool
|
||||
{
|
||||
foreach ((array) $kind as $value) {
|
||||
if (\in_array($value, [$this->id, $this->text], true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function isIgnorable(): bool
|
||||
{
|
||||
return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true);
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return (string) $this->text;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return static[]
|
||||
*/
|
||||
public static function tokenize(string $code, int $flags = 0): array
|
||||
{
|
||||
$line = 1;
|
||||
$position = 0;
|
||||
$tokens = token_get_all($code, $flags);
|
||||
foreach ($tokens as $index => $token) {
|
||||
if (\is_string($token)) {
|
||||
$id = \ord($token);
|
||||
$text = $token;
|
||||
} else {
|
||||
[$id, $text, $line] = $token;
|
||||
}
|
||||
$tokens[$index] = new static($id, $text, $line, $position);
|
||||
$position += \strlen($text);
|
||||
}
|
||||
|
||||
return $tokens;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
Symfony Polyfill / Php80
|
||||
========================
|
||||
|
||||
This component provides features added to PHP 8.0 core:
|
||||
|
||||
- [`Stringable`](https://php.net/stringable) interface
|
||||
- [`fdiv`](https://php.net/fdiv)
|
||||
- [`ValueError`](https://php.net/valueerror) class
|
||||
- [`UnhandledMatchError`](https://php.net/unhandledmatcherror) class
|
||||
- `FILTER_VALIDATE_BOOL` constant
|
||||
- [`get_debug_type`](https://php.net/get_debug_type)
|
||||
- [`PhpToken`](https://php.net/phptoken) class
|
||||
- [`preg_last_error_msg`](https://php.net/preg_last_error_msg)
|
||||
- [`str_contains`](https://php.net/str_contains)
|
||||
- [`str_starts_with`](https://php.net/str_starts_with)
|
||||
- [`str_ends_with`](https://php.net/str_ends_with)
|
||||
- [`get_resource_id`](https://php.net/get_resource_id)
|
||||
|
||||
More information can be found in the
|
||||
[main Polyfill README](https://github.com/symfony/polyfill/blob/main/README.md).
|
||||
|
||||
License
|
||||
=======
|
||||
|
||||
This library is released under the [MIT license](LICENSE).
|
@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
#[Attribute(Attribute::TARGET_CLASS)]
|
||||
final class Attribute
|
||||
{
|
||||
public const TARGET_CLASS = 1;
|
||||
public const TARGET_FUNCTION = 2;
|
||||
public const TARGET_METHOD = 4;
|
||||
public const TARGET_PROPERTY = 8;
|
||||
public const TARGET_CLASS_CONSTANT = 16;
|
||||
public const TARGET_PARAMETER = 32;
|
||||
public const TARGET_ALL = 63;
|
||||
public const IS_REPEATABLE = 64;
|
||||
|
||||
/** @var int */
|
||||
public $flags;
|
||||
|
||||
public function __construct(int $flags = self::TARGET_ALL)
|
||||
{
|
||||
$this->flags = $flags;
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
if (\PHP_VERSION_ID < 80000 && extension_loaded('tokenizer')) {
|
||||
class PhpToken extends Symfony\Polyfill\Php80\PhpToken
|
||||
{
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
if (\PHP_VERSION_ID < 80000) {
|
||||
interface Stringable
|
||||
{
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function __toString();
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
if (\PHP_VERSION_ID < 80000) {
|
||||
class UnhandledMatchError extends Error
|
||||
{
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
if (\PHP_VERSION_ID < 80000) {
|
||||
class ValueError extends Error
|
||||
{
|
||||
}
|
||||
}
|
@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
use Symfony\Polyfill\Php80 as p;
|
||||
|
||||
if (\PHP_VERSION_ID >= 80000) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!defined('FILTER_VALIDATE_BOOL') && defined('FILTER_VALIDATE_BOOLEAN')) {
|
||||
define('FILTER_VALIDATE_BOOL', \FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
if (!function_exists('fdiv')) {
|
||||
function fdiv(float $num1, float $num2): float { return p\Php80::fdiv($num1, $num2); }
|
||||
}
|
||||
if (!function_exists('preg_last_error_msg')) {
|
||||
function preg_last_error_msg(): string { return p\Php80::preg_last_error_msg(); }
|
||||
}
|
||||
if (!function_exists('str_contains')) {
|
||||
function str_contains(?string $haystack, ?string $needle): bool { return p\Php80::str_contains($haystack ?? '', $needle ?? ''); }
|
||||
}
|
||||
if (!function_exists('str_starts_with')) {
|
||||
function str_starts_with(?string $haystack, ?string $needle): bool { return p\Php80::str_starts_with($haystack ?? '', $needle ?? ''); }
|
||||
}
|
||||
if (!function_exists('str_ends_with')) {
|
||||
function str_ends_with(?string $haystack, ?string $needle): bool { return p\Php80::str_ends_with($haystack ?? '', $needle ?? ''); }
|
||||
}
|
||||
if (!function_exists('get_debug_type')) {
|
||||
function get_debug_type($value): string { return p\Php80::get_debug_type($value); }
|
||||
}
|
||||
if (!function_exists('get_resource_id')) {
|
||||
function get_resource_id($resource): int { return p\Php80::get_resource_id($resource); }
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "symfony/polyfill-php80",
|
||||
"type": "library",
|
||||
"description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions",
|
||||
"keywords": ["polyfill", "shim", "compatibility", "portable"],
|
||||
"homepage": "https://symfony.com",
|
||||
"license": "MIT",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Ion Bazan",
|
||||
"email": "ion.bazan@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Nicolas Grekas",
|
||||
"email": "p@tchwork.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=7.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": { "Symfony\\Polyfill\\Php80\\": "" },
|
||||
"files": [ "bootstrap.php" ],
|
||||
"classmap": [ "Resources/stubs" ]
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-main": "1.28-dev"
|
||||
},
|
||||
"thanks": {
|
||||
"name": "symfony/polyfill",
|
||||
"url": "https://github.com/symfony/polyfill"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,195 @@
|
||||
# 3.8.0 (2023-11-21)
|
||||
|
||||
* Catch errors thrown during template rendering
|
||||
* Fix IntlExtension::formatDateTime use of date formatter prototype
|
||||
* Fix premature loop exit in Security Policy lookup of allowed methods/properties
|
||||
* Remove NumberFormatter::TYPE_CURRENCY (deprecated in PHP 8.3)
|
||||
* Restore return type annotations
|
||||
* Allow Symfony 7 packages to be installed
|
||||
* Deprecate `twig_test_iterable` function. Use the native `is_iterable` instead.
|
||||
|
||||
# 3.7.1 (2023-08-28)
|
||||
|
||||
* Fix some phpdocs
|
||||
|
||||
# 3.7.0 (2023-07-26)
|
||||
|
||||
* Add support for the ...spread operator on arrays and hashes
|
||||
|
||||
# 3.6.1 (2023-06-08)
|
||||
|
||||
* Suppress some native return type deprecation messages
|
||||
|
||||
# 3.6.0 (2023-05-03)
|
||||
|
||||
* Allow psr/container 2.0
|
||||
* Add the new PHP 8.0 IntlDateFormatter::RELATIVE_* constants for date formatting
|
||||
* Make the Lexer initialize itself lazily
|
||||
|
||||
# 3.5.1 (2023-02-08)
|
||||
|
||||
* Arrow functions passed to the "reduce" filter now accept the current key as a third argument
|
||||
* Restores the leniency of the matches twig comparison
|
||||
* Fix error messages in sandboxed mode for "has some" and "has every"
|
||||
|
||||
# 3.5.0 (2022-12-27)
|
||||
|
||||
* Make Twig\ExpressionParser non-internal
|
||||
* Add "has some" and "has every" operators
|
||||
* Add Compile::reset()
|
||||
* Throw a better runtime error when the "matches" regexp is not valid
|
||||
* Add "twig *_names" intl functions
|
||||
* Fix optimizing closures callbacks
|
||||
* Add a better exception when getting an undefined constant via `constant`
|
||||
* Fix `if` nodes when outside of a block and with an empty body
|
||||
|
||||
# 3.4.3 (2022-09-28)
|
||||
|
||||
* Fix a security issue on filesystem loader (possibility to load a template outside a configured directory)
|
||||
|
||||
# 3.4.2 (2022-08-12)
|
||||
|
||||
* Allow inherited magic method to still run with calling class
|
||||
* Fix CallExpression::reflectCallable() throwing TypeError
|
||||
* Fix typo in naming (currency_code)
|
||||
|
||||
# 3.4.1 (2022-05-17)
|
||||
|
||||
* Fix optimizing non-public named closures
|
||||
|
||||
# 3.4.0 (2022-05-22)
|
||||
|
||||
* Add support for named closures
|
||||
|
||||
# 3.3.10 (2022-04-06)
|
||||
|
||||
* Enable bytecode invalidation when auto_reload is enabled
|
||||
|
||||
# 3.3.9 (2022-03-25)
|
||||
|
||||
* Fix custom escapers when using multiple Twig environments
|
||||
* Add support for "constant('class', object)"
|
||||
* Do not reuse internally generated variable names during parsing
|
||||
|
||||
# 3.3.8 (2022-02-04)
|
||||
|
||||
* Fix a security issue when in a sandbox: the `sort` filter must require a Closure for the `arrow` parameter
|
||||
* Fix deprecation notice on `round`
|
||||
* Fix call to deprecated `convertToHtml` method
|
||||
|
||||
# 3.3.7 (2022-01-03)
|
||||
|
||||
* Allow more null support when Twig expects a string (for better 8.1 support)
|
||||
* Only use Commonmark extensions if markdown enabled
|
||||
|
||||
# 3.3.6 (2022-01-03)
|
||||
|
||||
* Only use Commonmark extensions if markdown enabled
|
||||
|
||||
# 3.3.5 (2022-01-03)
|
||||
|
||||
* Allow CommonMark extensions to easily be added
|
||||
* Allow null when Twig expects a string (for better 8.1 support)
|
||||
* Make some performance optimizations
|
||||
* Allow Symfony translation contract v3+
|
||||
|
||||
# 3.3.4 (2021-11-25)
|
||||
|
||||
* Bump minimum supported Symfony component versions
|
||||
* Fix a deprecated message
|
||||
|
||||
# 3.3.3 (2021-09-17)
|
||||
|
||||
* Allow Symfony 6
|
||||
* Improve compatibility with PHP 8.1
|
||||
* Explicitly specify the encoding for mb_ord in JS escaper
|
||||
|
||||
# 3.3.2 (2021-05-16)
|
||||
|
||||
* Revert "Throw a proper exception when a template name is an absolute path (as it has never been supported)"
|
||||
|
||||
# 3.3.1 (2021-05-12)
|
||||
|
||||
* Fix PHP 8.1 compatibility
|
||||
* Throw a proper exception when a template name is an absolute path (as it has never been supported)
|
||||
|
||||
# 3.3.0 (2021-02-08)
|
||||
|
||||
* Fix macro calls in a "cache" tag
|
||||
* Add the slug filter
|
||||
* Allow extra bundle to be compatible with Twig 2
|
||||
|
||||
# 3.2.1 (2021-01-05)
|
||||
|
||||
* Fix extra bundle compat with older versions of Symfony
|
||||
|
||||
# 3.2.0 (2021-01-05)
|
||||
|
||||
* Add the Cache extension in the "extra" repositories: "cache" tag
|
||||
* Add "registerUndefinedTokenParserCallback"
|
||||
* Mark built-in node visitors as @internal
|
||||
* Fix "odd" not working for negative numbers
|
||||
|
||||
# 3.1.1 (2020-10-27)
|
||||
|
||||
* Fix "include(template_from_string())"
|
||||
|
||||
# 3.1.0 (2020-10-21)
|
||||
|
||||
* Fix sandbox support when using "include(template_from_string())"
|
||||
* Make round brackets optional for one argument tests like "same as" or "divisible by"
|
||||
* Add support for ES2015 style object initialisation shortcut { a } is the same as { 'a': a }
|
||||
|
||||
# 3.0.5 (2020-08-05)
|
||||
|
||||
* Fix twig_compare w.r.t. whitespace trimming
|
||||
* Fix sandbox not disabled if syntax error occurs within {% sandbox %} tag
|
||||
* Fix a regression when not using a space before an operator
|
||||
* Restrict callables to closures in filters
|
||||
* Allow trailing commas in argument lists (in calls as well as definitions)
|
||||
|
||||
# 3.0.4 (2020-07-05)
|
||||
|
||||
* Fix comparison operators
|
||||
* Fix options not taken into account when using "Michelf\MarkdownExtra"
|
||||
* Fix "Twig\Extra\Intl\IntlExtension::getCountryName()" to accept "null" as a first argument
|
||||
* Throw exception in case non-Traversable data is passed to "filter"
|
||||
* Fix context optimization on PHP 7.4
|
||||
* Fix PHP 8 compatibility
|
||||
* Fix ambiguous syntax parsing
|
||||
|
||||
# 3.0.3 (2020-02-11)
|
||||
|
||||
* Add a check to ensure that iconv() is defined
|
||||
|
||||
# 3.0.2 (2020-02-11)
|
||||
|
||||
* Avoid exceptions when an intl resource is not found
|
||||
* Fix implementation of case-insensitivity for method names
|
||||
|
||||
# 3.0.1 (2019-12-28)
|
||||
|
||||
* fixed Symfony 5.0 support for the HTML extra extension
|
||||
|
||||
# 3.0.0 (2019-11-15)
|
||||
|
||||
* fixed number formatter in Intl extra extension when using a formatter prototype
|
||||
|
||||
# 3.0.0-BETA1 (2019-11-11)
|
||||
|
||||
* removed the "if" condition support on the "for" tag
|
||||
* made the in, <, >, <=, >=, ==, and != operators more strict when comparing strings and integers/floats
|
||||
* removed the "filter" tag
|
||||
* added type hints everywhere
|
||||
* changed Environment::resolveTemplate() to always return a TemplateWrapper instance
|
||||
* removed Template::__toString()
|
||||
* removed Parser::isReservedMacroName()
|
||||
* removed SanboxedPrintNode
|
||||
* removed Node::setTemplateName()
|
||||
* made classes maked as "@final" final
|
||||
* removed InitRuntimeInterface, ExistsLoaderInterface, and SourceContextLoaderInterface
|
||||
* removed the "spaceless" tag
|
||||
* removed Twig\Environment::getBaseTemplateClass() and Twig\Environment::setBaseTemplateClass()
|
||||
* removed the "base_template_class" option on Twig\Environment
|
||||
* bumped minimum PHP version to 7.2
|
||||
* removed PSR-0 classes
|
@ -0,0 +1,27 @@
|
||||
Copyright (c) 2009-present by the Twig Team.
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of Twig nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
@ -0,0 +1,23 @@
|
||||
Twig, the flexible, fast, and secure template language for PHP
|
||||
==============================================================
|
||||
|
||||
Twig is a template language for PHP.
|
||||
|
||||
Twig uses a syntax similar to the Django and Jinja template languages which
|
||||
inspired the Twig runtime environment.
|
||||
|
||||
Sponsors
|
||||
--------
|
||||
|
||||
.. raw:: html
|
||||
|
||||
<a href="https://blackfire.io/docs/introduction?utm_source=twig&utm_medium=github_readme&utm_campaign=logo">
|
||||
<img src="https://static.blackfire.io/assets/intemporals/logo/png/blackfire-io_secondary_horizontal_transparent.png?1" width="255px" alt="Blackfire.io">
|
||||
</a>
|
||||
|
||||
More Information
|
||||
----------------
|
||||
|
||||
Read the `documentation`_ for more information.
|
||||
|
||||
.. _documentation: https://twig.symfony.com/documentation
|
@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "twig/twig",
|
||||
"type": "library",
|
||||
"description": "Twig, the flexible, fast, and secure template language for PHP",
|
||||
"keywords": ["templating"],
|
||||
"homepage": "https://twig.symfony.com",
|
||||
"license": "BSD-3-Clause",
|
||||
"minimum-stability": "dev",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Fabien Potencier",
|
||||
"email": "fabien@symfony.com",
|
||||
"homepage": "http://fabien.potencier.org",
|
||||
"role": "Lead Developer"
|
||||
},
|
||||
{
|
||||
"name": "Twig Team",
|
||||
"role": "Contributors"
|
||||
},
|
||||
{
|
||||
"name": "Armin Ronacher",
|
||||
"email": "armin.ronacher@active-4.com",
|
||||
"role": "Project Founder"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=7.2.5",
|
||||
"symfony/polyfill-php80": "^1.22",
|
||||
"symfony/polyfill-mbstring": "^1.3",
|
||||
"symfony/polyfill-ctype": "^1.8"
|
||||
},
|
||||
"require-dev": {
|
||||
"symfony/phpunit-bridge": "^5.4.9|^6.3|^7.0",
|
||||
"psr/container": "^1.0|^2.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4" : {
|
||||
"Twig\\" : "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4" : {
|
||||
"Twig\\Tests\\" : "tests/"
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Cache;
|
||||
|
||||
/**
|
||||
* Interface implemented by cache classes.
|
||||
*
|
||||
* It is highly recommended to always store templates on the filesystem to
|
||||
* benefit from the PHP opcode cache. This interface is mostly useful if you
|
||||
* need to implement a custom strategy for storing templates on the filesystem.
|
||||
*
|
||||
* @author Andrew Tch <andrew@noop.lv>
|
||||
*/
|
||||
interface CacheInterface
|
||||
{
|
||||
/**
|
||||
* Generates a cache key for the given template class name.
|
||||
*/
|
||||
public function generateKey(string $name, string $className): string;
|
||||
|
||||
/**
|
||||
* Writes the compiled template to cache.
|
||||
*
|
||||
* @param string $content The template representation as a PHP class
|
||||
*/
|
||||
public function write(string $key, string $content): void;
|
||||
|
||||
/**
|
||||
* Loads a template from the cache.
|
||||
*/
|
||||
public function load(string $key): void;
|
||||
|
||||
/**
|
||||
* Returns the modification timestamp of a key.
|
||||
*/
|
||||
public function getTimestamp(string $key): int;
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Cache;
|
||||
|
||||
/**
|
||||
* Implements a cache on the filesystem.
|
||||
*
|
||||
* @author Andrew Tch <andrew@noop.lv>
|
||||
*/
|
||||
class FilesystemCache implements CacheInterface
|
||||
{
|
||||
public const FORCE_BYTECODE_INVALIDATION = 1;
|
||||
|
||||
private $directory;
|
||||
private $options;
|
||||
|
||||
public function __construct(string $directory, int $options = 0)
|
||||
{
|
||||
$this->directory = rtrim($directory, '\/').'/';
|
||||
$this->options = $options;
|
||||
}
|
||||
|
||||
public function generateKey(string $name, string $className): string
|
||||
{
|
||||
$hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $className);
|
||||
|
||||
return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php';
|
||||
}
|
||||
|
||||
public function load(string $key): void
|
||||
{
|
||||
if (is_file($key)) {
|
||||
@include_once $key;
|
||||
}
|
||||
}
|
||||
|
||||
public function write(string $key, string $content): void
|
||||
{
|
||||
$dir = \dirname($key);
|
||||
if (!is_dir($dir)) {
|
||||
if (false === @mkdir($dir, 0777, true)) {
|
||||
clearstatcache(true, $dir);
|
||||
if (!is_dir($dir)) {
|
||||
throw new \RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir));
|
||||
}
|
||||
}
|
||||
} elseif (!is_writable($dir)) {
|
||||
throw new \RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir));
|
||||
}
|
||||
|
||||
$tmpFile = tempnam($dir, basename($key));
|
||||
if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) {
|
||||
@chmod($key, 0666 & ~umask());
|
||||
|
||||
if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) {
|
||||
// Compile cached file into bytecode cache
|
||||
if (\function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN)) {
|
||||
@opcache_invalidate($key, true);
|
||||
} elseif (\function_exists('apc_compile_file')) {
|
||||
apc_compile_file($key);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $key));
|
||||
}
|
||||
|
||||
public function getTimestamp(string $key): int
|
||||
{
|
||||
if (!is_file($key)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (int) @filemtime($key);
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Cache;
|
||||
|
||||
/**
|
||||
* Implements a no-cache strategy.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
final class NullCache implements CacheInterface
|
||||
{
|
||||
public function generateKey(string $name, string $className): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function write(string $key, string $content): void
|
||||
{
|
||||
}
|
||||
|
||||
public function load(string $key): void
|
||||
{
|
||||
}
|
||||
|
||||
public function getTimestamp(string $key): int
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
* (c) Armin Ronacher
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig;
|
||||
|
||||
use Twig\Node\Node;
|
||||
|
||||
/**
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class Compiler
|
||||
{
|
||||
private $lastLine;
|
||||
private $source;
|
||||
private $indentation;
|
||||
private $env;
|
||||
private $debugInfo = [];
|
||||
private $sourceOffset;
|
||||
private $sourceLine;
|
||||
private $varNameSalt = 0;
|
||||
|
||||
public function __construct(Environment $env)
|
||||
{
|
||||
$this->env = $env;
|
||||
}
|
||||
|
||||
public function getEnvironment(): Environment
|
||||
{
|
||||
return $this->env;
|
||||
}
|
||||
|
||||
public function getSource(): string
|
||||
{
|
||||
return $this->source;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function reset(int $indentation = 0)
|
||||
{
|
||||
$this->lastLine = null;
|
||||
$this->source = '';
|
||||
$this->debugInfo = [];
|
||||
$this->sourceOffset = 0;
|
||||
// source code starts at 1 (as we then increment it when we encounter new lines)
|
||||
$this->sourceLine = 1;
|
||||
$this->indentation = $indentation;
|
||||
$this->varNameSalt = 0;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function compile(Node $node, int $indentation = 0)
|
||||
{
|
||||
$this->reset($indentation);
|
||||
$node->compile($this);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function subcompile(Node $node, bool $raw = true)
|
||||
{
|
||||
if (false === $raw) {
|
||||
$this->source .= str_repeat(' ', $this->indentation * 4);
|
||||
}
|
||||
|
||||
$node->compile($this);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a raw string to the compiled code.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function raw(string $string)
|
||||
{
|
||||
$this->source .= $string;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a string to the compiled code by adding indentation.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function write(...$strings)
|
||||
{
|
||||
foreach ($strings as $string) {
|
||||
$this->source .= str_repeat(' ', $this->indentation * 4).$string;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a quoted string to the compiled code.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function string(string $value)
|
||||
{
|
||||
$this->source .= sprintf('"%s"', addcslashes($value, "\0\t\"\$\\"));
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a PHP representation of a given value.
|
||||
*
|
||||
* @return $this
|
||||
*/
|
||||
public function repr($value)
|
||||
{
|
||||
if (\is_int($value) || \is_float($value)) {
|
||||
if (false !== $locale = setlocale(\LC_NUMERIC, '0')) {
|
||||
setlocale(\LC_NUMERIC, 'C');
|
||||
}
|
||||
|
||||
$this->raw(var_export($value, true));
|
||||
|
||||
if (false !== $locale) {
|
||||
setlocale(\LC_NUMERIC, $locale);
|
||||
}
|
||||
} elseif (null === $value) {
|
||||
$this->raw('null');
|
||||
} elseif (\is_bool($value)) {
|
||||
$this->raw($value ? 'true' : 'false');
|
||||
} elseif (\is_array($value)) {
|
||||
$this->raw('array(');
|
||||
$first = true;
|
||||
foreach ($value as $key => $v) {
|
||||
if (!$first) {
|
||||
$this->raw(', ');
|
||||
}
|
||||
$first = false;
|
||||
$this->repr($key);
|
||||
$this->raw(' => ');
|
||||
$this->repr($v);
|
||||
}
|
||||
$this->raw(')');
|
||||
} else {
|
||||
$this->string($value);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function addDebugInfo(Node $node)
|
||||
{
|
||||
if ($node->getTemplateLine() != $this->lastLine) {
|
||||
$this->write(sprintf("// line %d\n", $node->getTemplateLine()));
|
||||
|
||||
$this->sourceLine += substr_count($this->source, "\n", $this->sourceOffset);
|
||||
$this->sourceOffset = \strlen($this->source);
|
||||
$this->debugInfo[$this->sourceLine] = $node->getTemplateLine();
|
||||
|
||||
$this->lastLine = $node->getTemplateLine();
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDebugInfo(): array
|
||||
{
|
||||
ksort($this->debugInfo);
|
||||
|
||||
return $this->debugInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*/
|
||||
public function indent(int $step = 1)
|
||||
{
|
||||
$this->indentation += $step;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return $this
|
||||
*
|
||||
* @throws \LogicException When trying to outdent too much so the indentation would become negative
|
||||
*/
|
||||
public function outdent(int $step = 1)
|
||||
{
|
||||
// can't outdent by more steps than the current indentation level
|
||||
if ($this->indentation < $step) {
|
||||
throw new \LogicException('Unable to call outdent() as the indentation would become negative.');
|
||||
}
|
||||
|
||||
$this->indentation -= $step;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getVarName(): string
|
||||
{
|
||||
return sprintf('__internal_compile_%d', $this->varNameSalt++);
|
||||
}
|
||||
}
|
@ -0,0 +1,840 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig;
|
||||
|
||||
use Twig\Cache\CacheInterface;
|
||||
use Twig\Cache\FilesystemCache;
|
||||
use Twig\Cache\NullCache;
|
||||
use Twig\Error\Error;
|
||||
use Twig\Error\LoaderError;
|
||||
use Twig\Error\RuntimeError;
|
||||
use Twig\Error\SyntaxError;
|
||||
use Twig\Extension\CoreExtension;
|
||||
use Twig\Extension\EscaperExtension;
|
||||
use Twig\Extension\ExtensionInterface;
|
||||
use Twig\Extension\OptimizerExtension;
|
||||
use Twig\Loader\ArrayLoader;
|
||||
use Twig\Loader\ChainLoader;
|
||||
use Twig\Loader\LoaderInterface;
|
||||
use Twig\Node\Expression\Binary\AbstractBinary;
|
||||
use Twig\Node\Expression\Unary\AbstractUnary;
|
||||
use Twig\Node\ModuleNode;
|
||||
use Twig\Node\Node;
|
||||
use Twig\NodeVisitor\NodeVisitorInterface;
|
||||
use Twig\RuntimeLoader\RuntimeLoaderInterface;
|
||||
use Twig\TokenParser\TokenParserInterface;
|
||||
|
||||
/**
|
||||
* Stores the Twig configuration and renders templates.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class Environment
|
||||
{
|
||||
public const VERSION = '3.8.0';
|
||||
public const VERSION_ID = 30800;
|
||||
public const MAJOR_VERSION = 3;
|
||||
public const MINOR_VERSION = 8;
|
||||
public const RELEASE_VERSION = 0;
|
||||
public const EXTRA_VERSION = '';
|
||||
|
||||
private $charset;
|
||||
private $loader;
|
||||
private $debug;
|
||||
private $autoReload;
|
||||
private $cache;
|
||||
private $lexer;
|
||||
private $parser;
|
||||
private $compiler;
|
||||
/** @var array<string, mixed> */
|
||||
private $globals = [];
|
||||
private $resolvedGlobals;
|
||||
private $loadedTemplates;
|
||||
private $strictVariables;
|
||||
private $templateClassPrefix = '__TwigTemplate_';
|
||||
private $originalCache;
|
||||
private $extensionSet;
|
||||
private $runtimeLoaders = [];
|
||||
private $runtimes = [];
|
||||
private $optionsHash;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* Available options:
|
||||
*
|
||||
* * debug: When set to true, it automatically set "auto_reload" to true as
|
||||
* well (default to false).
|
||||
*
|
||||
* * charset: The charset used by the templates (default to UTF-8).
|
||||
*
|
||||
* * cache: An absolute path where to store the compiled templates,
|
||||
* a \Twig\Cache\CacheInterface implementation,
|
||||
* or false to disable compilation cache (default).
|
||||
*
|
||||
* * auto_reload: Whether to reload the template if the original source changed.
|
||||
* If you don't provide the auto_reload option, it will be
|
||||
* determined automatically based on the debug value.
|
||||
*
|
||||
* * strict_variables: Whether to ignore invalid variables in templates
|
||||
* (default to false).
|
||||
*
|
||||
* * autoescape: Whether to enable auto-escaping (default to html):
|
||||
* * false: disable auto-escaping
|
||||
* * html, js: set the autoescaping to one of the supported strategies
|
||||
* * name: set the autoescaping strategy based on the template name extension
|
||||
* * PHP callback: a PHP callback that returns an escaping strategy based on the template "name"
|
||||
*
|
||||
* * optimizations: A flag that indicates which optimizations to apply
|
||||
* (default to -1 which means that all optimizations are enabled;
|
||||
* set it to 0 to disable).
|
||||
*/
|
||||
public function __construct(LoaderInterface $loader, $options = [])
|
||||
{
|
||||
$this->setLoader($loader);
|
||||
|
||||
$options = array_merge([
|
||||
'debug' => false,
|
||||
'charset' => 'UTF-8',
|
||||
'strict_variables' => false,
|
||||
'autoescape' => 'html',
|
||||
'cache' => false,
|
||||
'auto_reload' => null,
|
||||
'optimizations' => -1,
|
||||
], $options);
|
||||
|
||||
$this->debug = (bool) $options['debug'];
|
||||
$this->setCharset($options['charset'] ?? 'UTF-8');
|
||||
$this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
|
||||
$this->strictVariables = (bool) $options['strict_variables'];
|
||||
$this->setCache($options['cache']);
|
||||
$this->extensionSet = new ExtensionSet();
|
||||
|
||||
$this->addExtension(new CoreExtension());
|
||||
$this->addExtension(new EscaperExtension($options['autoescape']));
|
||||
$this->addExtension(new OptimizerExtension($options['optimizations']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables debugging mode.
|
||||
*/
|
||||
public function enableDebug()
|
||||
{
|
||||
$this->debug = true;
|
||||
$this->updateOptionsHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables debugging mode.
|
||||
*/
|
||||
public function disableDebug()
|
||||
{
|
||||
$this->debug = false;
|
||||
$this->updateOptionsHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if debug mode is enabled.
|
||||
*
|
||||
* @return bool true if debug mode is enabled, false otherwise
|
||||
*/
|
||||
public function isDebug()
|
||||
{
|
||||
return $this->debug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the auto_reload option.
|
||||
*/
|
||||
public function enableAutoReload()
|
||||
{
|
||||
$this->autoReload = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables the auto_reload option.
|
||||
*/
|
||||
public function disableAutoReload()
|
||||
{
|
||||
$this->autoReload = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the auto_reload option is enabled.
|
||||
*
|
||||
* @return bool true if auto_reload is enabled, false otherwise
|
||||
*/
|
||||
public function isAutoReload()
|
||||
{
|
||||
return $this->autoReload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the strict_variables option.
|
||||
*/
|
||||
public function enableStrictVariables()
|
||||
{
|
||||
$this->strictVariables = true;
|
||||
$this->updateOptionsHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables the strict_variables option.
|
||||
*/
|
||||
public function disableStrictVariables()
|
||||
{
|
||||
$this->strictVariables = false;
|
||||
$this->updateOptionsHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the strict_variables option is enabled.
|
||||
*
|
||||
* @return bool true if strict_variables is enabled, false otherwise
|
||||
*/
|
||||
public function isStrictVariables()
|
||||
{
|
||||
return $this->strictVariables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current cache implementation.
|
||||
*
|
||||
* @param bool $original Whether to return the original cache option or the real cache instance
|
||||
*
|
||||
* @return CacheInterface|string|false A Twig\Cache\CacheInterface implementation,
|
||||
* an absolute path to the compiled templates,
|
||||
* or false to disable cache
|
||||
*/
|
||||
public function getCache($original = true)
|
||||
{
|
||||
return $original ? $this->originalCache : $this->cache;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current cache implementation.
|
||||
*
|
||||
* @param CacheInterface|string|false $cache A Twig\Cache\CacheInterface implementation,
|
||||
* an absolute path to the compiled templates,
|
||||
* or false to disable cache
|
||||
*/
|
||||
public function setCache($cache)
|
||||
{
|
||||
if (\is_string($cache)) {
|
||||
$this->originalCache = $cache;
|
||||
$this->cache = new FilesystemCache($cache, $this->autoReload ? FilesystemCache::FORCE_BYTECODE_INVALIDATION : 0);
|
||||
} elseif (false === $cache) {
|
||||
$this->originalCache = $cache;
|
||||
$this->cache = new NullCache();
|
||||
} elseif ($cache instanceof CacheInterface) {
|
||||
$this->originalCache = $this->cache = $cache;
|
||||
} else {
|
||||
throw new \LogicException('Cache can only be a string, false, or a \Twig\Cache\CacheInterface implementation.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the template class associated with the given string.
|
||||
*
|
||||
* The generated template class is based on the following parameters:
|
||||
*
|
||||
* * The cache key for the given template;
|
||||
* * The currently enabled extensions;
|
||||
* * Whether the Twig C extension is available or not;
|
||||
* * PHP version;
|
||||
* * Twig version;
|
||||
* * Options with what environment was created.
|
||||
*
|
||||
* @param string $name The name for which to calculate the template class name
|
||||
* @param int|null $index The index if it is an embedded template
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function getTemplateClass(string $name, int $index = null): string
|
||||
{
|
||||
$key = $this->getLoader()->getCacheKey($name).$this->optionsHash;
|
||||
|
||||
return $this->templateClassPrefix.hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $key).(null === $index ? '' : '___'.$index);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a template.
|
||||
*
|
||||
* @param string|TemplateWrapper $name The template name
|
||||
*
|
||||
* @throws LoaderError When the template cannot be found
|
||||
* @throws SyntaxError When an error occurred during compilation
|
||||
* @throws RuntimeError When an error occurred during rendering
|
||||
*/
|
||||
public function render($name, array $context = []): string
|
||||
{
|
||||
return $this->load($name)->render($context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a template.
|
||||
*
|
||||
* @param string|TemplateWrapper $name The template name
|
||||
*
|
||||
* @throws LoaderError When the template cannot be found
|
||||
* @throws SyntaxError When an error occurred during compilation
|
||||
* @throws RuntimeError When an error occurred during rendering
|
||||
*/
|
||||
public function display($name, array $context = []): void
|
||||
{
|
||||
$this->load($name)->display($context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a template.
|
||||
*
|
||||
* @param string|TemplateWrapper $name The template name
|
||||
*
|
||||
* @throws LoaderError When the template cannot be found
|
||||
* @throws RuntimeError When a previously generated cache is corrupted
|
||||
* @throws SyntaxError When an error occurred during compilation
|
||||
*/
|
||||
public function load($name): TemplateWrapper
|
||||
{
|
||||
if ($name instanceof TemplateWrapper) {
|
||||
return $name;
|
||||
}
|
||||
|
||||
return new TemplateWrapper($this, $this->loadTemplate($this->getTemplateClass($name), $name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a template internal representation.
|
||||
*
|
||||
* This method is for internal use only and should never be called
|
||||
* directly.
|
||||
*
|
||||
* @param string $name The template name
|
||||
* @param int $index The index if it is an embedded template
|
||||
*
|
||||
* @throws LoaderError When the template cannot be found
|
||||
* @throws RuntimeError When a previously generated cache is corrupted
|
||||
* @throws SyntaxError When an error occurred during compilation
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function loadTemplate(string $cls, string $name, int $index = null): Template
|
||||
{
|
||||
$mainCls = $cls;
|
||||
if (null !== $index) {
|
||||
$cls .= '___'.$index;
|
||||
}
|
||||
|
||||
if (isset($this->loadedTemplates[$cls])) {
|
||||
return $this->loadedTemplates[$cls];
|
||||
}
|
||||
|
||||
if (!class_exists($cls, false)) {
|
||||
$key = $this->cache->generateKey($name, $mainCls);
|
||||
|
||||
if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) {
|
||||
$this->cache->load($key);
|
||||
}
|
||||
|
||||
if (!class_exists($cls, false)) {
|
||||
$source = $this->getLoader()->getSourceContext($name);
|
||||
$content = $this->compileSource($source);
|
||||
$this->cache->write($key, $content);
|
||||
$this->cache->load($key);
|
||||
|
||||
if (!class_exists($mainCls, false)) {
|
||||
/* Last line of defense if either $this->bcWriteCacheFile was used,
|
||||
* $this->cache is implemented as a no-op or we have a race condition
|
||||
* where the cache was cleared between the above calls to write to and load from
|
||||
* the cache.
|
||||
*/
|
||||
eval('?>'.$content);
|
||||
}
|
||||
|
||||
if (!class_exists($cls, false)) {
|
||||
throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->extensionSet->initRuntime();
|
||||
|
||||
return $this->loadedTemplates[$cls] = new $cls($this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a template from source.
|
||||
*
|
||||
* This method should not be used as a generic way to load templates.
|
||||
*
|
||||
* @param string $template The template source
|
||||
* @param string $name An optional name of the template to be used in error messages
|
||||
*
|
||||
* @throws LoaderError When the template cannot be found
|
||||
* @throws SyntaxError When an error occurred during compilation
|
||||
*/
|
||||
public function createTemplate(string $template, string $name = null): TemplateWrapper
|
||||
{
|
||||
$hash = hash(\PHP_VERSION_ID < 80100 ? 'sha256' : 'xxh128', $template, false);
|
||||
if (null !== $name) {
|
||||
$name = sprintf('%s (string template %s)', $name, $hash);
|
||||
} else {
|
||||
$name = sprintf('__string_template__%s', $hash);
|
||||
}
|
||||
|
||||
$loader = new ChainLoader([
|
||||
new ArrayLoader([$name => $template]),
|
||||
$current = $this->getLoader(),
|
||||
]);
|
||||
|
||||
$this->setLoader($loader);
|
||||
try {
|
||||
return new TemplateWrapper($this, $this->loadTemplate($this->getTemplateClass($name), $name));
|
||||
} finally {
|
||||
$this->setLoader($current);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the template is still fresh.
|
||||
*
|
||||
* Besides checking the loader for freshness information,
|
||||
* this method also checks if the enabled extensions have
|
||||
* not changed.
|
||||
*
|
||||
* @param int $time The last modification time of the cached template
|
||||
*/
|
||||
public function isTemplateFresh(string $name, int $time): bool
|
||||
{
|
||||
return $this->extensionSet->getLastModified() <= $time && $this->getLoader()->isFresh($name, $time);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to load a template consecutively from an array.
|
||||
*
|
||||
* Similar to load() but it also accepts instances of \Twig\Template and
|
||||
* \Twig\TemplateWrapper, and an array of templates where each is tried to be loaded.
|
||||
*
|
||||
* @param string|TemplateWrapper|array $names A template or an array of templates to try consecutively
|
||||
*
|
||||
* @throws LoaderError When none of the templates can be found
|
||||
* @throws SyntaxError When an error occurred during compilation
|
||||
*/
|
||||
public function resolveTemplate($names): TemplateWrapper
|
||||
{
|
||||
if (!\is_array($names)) {
|
||||
return $this->load($names);
|
||||
}
|
||||
|
||||
$count = \count($names);
|
||||
foreach ($names as $name) {
|
||||
if ($name instanceof Template) {
|
||||
return $name;
|
||||
}
|
||||
if ($name instanceof TemplateWrapper) {
|
||||
return $name;
|
||||
}
|
||||
|
||||
if (1 !== $count && !$this->getLoader()->exists($name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return $this->load($name);
|
||||
}
|
||||
|
||||
throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names)));
|
||||
}
|
||||
|
||||
public function setLexer(Lexer $lexer)
|
||||
{
|
||||
$this->lexer = $lexer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws SyntaxError When the code is syntactically wrong
|
||||
*/
|
||||
public function tokenize(Source $source): TokenStream
|
||||
{
|
||||
if (null === $this->lexer) {
|
||||
$this->lexer = new Lexer($this);
|
||||
}
|
||||
|
||||
return $this->lexer->tokenize($source);
|
||||
}
|
||||
|
||||
public function setParser(Parser $parser)
|
||||
{
|
||||
$this->parser = $parser;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a token stream to a node tree.
|
||||
*
|
||||
* @throws SyntaxError When the token stream is syntactically or semantically wrong
|
||||
*/
|
||||
public function parse(TokenStream $stream): ModuleNode
|
||||
{
|
||||
if (null === $this->parser) {
|
||||
$this->parser = new Parser($this);
|
||||
}
|
||||
|
||||
return $this->parser->parse($stream);
|
||||
}
|
||||
|
||||
public function setCompiler(Compiler $compiler)
|
||||
{
|
||||
$this->compiler = $compiler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a node and returns the PHP code.
|
||||
*/
|
||||
public function compile(Node $node): string
|
||||
{
|
||||
if (null === $this->compiler) {
|
||||
$this->compiler = new Compiler($this);
|
||||
}
|
||||
|
||||
return $this->compiler->compile($node)->getSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles a template source code.
|
||||
*
|
||||
* @throws SyntaxError When there was an error during tokenizing, parsing or compiling
|
||||
*/
|
||||
public function compileSource(Source $source): string
|
||||
{
|
||||
try {
|
||||
return $this->compile($this->parse($this->tokenize($source)));
|
||||
} catch (Error $e) {
|
||||
$e->setSourceContext($source);
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
throw new SyntaxError(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e);
|
||||
}
|
||||
}
|
||||
|
||||
public function setLoader(LoaderInterface $loader)
|
||||
{
|
||||
$this->loader = $loader;
|
||||
}
|
||||
|
||||
public function getLoader(): LoaderInterface
|
||||
{
|
||||
return $this->loader;
|
||||
}
|
||||
|
||||
public function setCharset(string $charset)
|
||||
{
|
||||
if ('UTF8' === $charset = null === $charset ? null : strtoupper($charset)) {
|
||||
// iconv on Windows requires "UTF-8" instead of "UTF8"
|
||||
$charset = 'UTF-8';
|
||||
}
|
||||
|
||||
$this->charset = $charset;
|
||||
}
|
||||
|
||||
public function getCharset(): string
|
||||
{
|
||||
return $this->charset;
|
||||
}
|
||||
|
||||
public function hasExtension(string $class): bool
|
||||
{
|
||||
return $this->extensionSet->hasExtension($class);
|
||||
}
|
||||
|
||||
public function addRuntimeLoader(RuntimeLoaderInterface $loader)
|
||||
{
|
||||
$this->runtimeLoaders[] = $loader;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TExtension of ExtensionInterface
|
||||
*
|
||||
* @param class-string<TExtension> $class
|
||||
*
|
||||
* @return TExtension
|
||||
*/
|
||||
public function getExtension(string $class): ExtensionInterface
|
||||
{
|
||||
return $this->extensionSet->getExtension($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the runtime implementation of a Twig element (filter/function/tag/test).
|
||||
*
|
||||
* @template TRuntime of object
|
||||
*
|
||||
* @param class-string<TRuntime> $class A runtime class name
|
||||
*
|
||||
* @return TRuntime The runtime implementation
|
||||
*
|
||||
* @throws RuntimeError When the template cannot be found
|
||||
*/
|
||||
public function getRuntime(string $class)
|
||||
{
|
||||
if (isset($this->runtimes[$class])) {
|
||||
return $this->runtimes[$class];
|
||||
}
|
||||
|
||||
foreach ($this->runtimeLoaders as $loader) {
|
||||
if (null !== $runtime = $loader->load($class)) {
|
||||
return $this->runtimes[$class] = $runtime;
|
||||
}
|
||||
}
|
||||
|
||||
throw new RuntimeError(sprintf('Unable to load the "%s" runtime.', $class));
|
||||
}
|
||||
|
||||
public function addExtension(ExtensionInterface $extension)
|
||||
{
|
||||
$this->extensionSet->addExtension($extension);
|
||||
$this->updateOptionsHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ExtensionInterface[] $extensions An array of extensions
|
||||
*/
|
||||
public function setExtensions(array $extensions)
|
||||
{
|
||||
$this->extensionSet->setExtensions($extensions);
|
||||
$this->updateOptionsHash();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on)
|
||||
*/
|
||||
public function getExtensions(): array
|
||||
{
|
||||
return $this->extensionSet->getExtensions();
|
||||
}
|
||||
|
||||
public function addTokenParser(TokenParserInterface $parser)
|
||||
{
|
||||
$this->extensionSet->addTokenParser($parser);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return TokenParserInterface[]
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function getTokenParsers(): array
|
||||
{
|
||||
return $this->extensionSet->getTokenParsers();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function getTokenParser(string $name): ?TokenParserInterface
|
||||
{
|
||||
return $this->extensionSet->getTokenParser($name);
|
||||
}
|
||||
|
||||
public function registerUndefinedTokenParserCallback(callable $callable): void
|
||||
{
|
||||
$this->extensionSet->registerUndefinedTokenParserCallback($callable);
|
||||
}
|
||||
|
||||
public function addNodeVisitor(NodeVisitorInterface $visitor)
|
||||
{
|
||||
$this->extensionSet->addNodeVisitor($visitor);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return NodeVisitorInterface[]
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function getNodeVisitors(): array
|
||||
{
|
||||
return $this->extensionSet->getNodeVisitors();
|
||||
}
|
||||
|
||||
public function addFilter(TwigFilter $filter)
|
||||
{
|
||||
$this->extensionSet->addFilter($filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function getFilter(string $name): ?TwigFilter
|
||||
{
|
||||
return $this->extensionSet->getFilter($name);
|
||||
}
|
||||
|
||||
public function registerUndefinedFilterCallback(callable $callable): void
|
||||
{
|
||||
$this->extensionSet->registerUndefinedFilterCallback($callable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the registered Filters.
|
||||
*
|
||||
* Be warned that this method cannot return filters defined with registerUndefinedFilterCallback.
|
||||
*
|
||||
* @return TwigFilter[]
|
||||
*
|
||||
* @see registerUndefinedFilterCallback
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function getFilters(): array
|
||||
{
|
||||
return $this->extensionSet->getFilters();
|
||||
}
|
||||
|
||||
public function addTest(TwigTest $test)
|
||||
{
|
||||
$this->extensionSet->addTest($test);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return TwigTest[]
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function getTests(): array
|
||||
{
|
||||
return $this->extensionSet->getTests();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function getTest(string $name): ?TwigTest
|
||||
{
|
||||
return $this->extensionSet->getTest($name);
|
||||
}
|
||||
|
||||
public function addFunction(TwigFunction $function)
|
||||
{
|
||||
$this->extensionSet->addFunction($function);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public function getFunction(string $name): ?TwigFunction
|
||||
{
|
||||
return $this->extensionSet->getFunction($name);
|
||||
}
|
||||
|
||||
public function registerUndefinedFunctionCallback(callable $callable): void
|
||||
{
|
||||
$this->extensionSet->registerUndefinedFunctionCallback($callable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets registered functions.
|
||||
*
|
||||
* Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback.
|
||||
*
|
||||
* @return TwigFunction[]
|
||||
*
|
||||
* @see registerUndefinedFunctionCallback
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function getFunctions(): array
|
||||
{
|
||||
return $this->extensionSet->getFunctions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a Global.
|
||||
*
|
||||
* New globals can be added before compiling or rendering a template;
|
||||
* but after, you can only update existing globals.
|
||||
*
|
||||
* @param mixed $value The global value
|
||||
*/
|
||||
public function addGlobal(string $name, $value)
|
||||
{
|
||||
if ($this->extensionSet->isInitialized() && !\array_key_exists($name, $this->getGlobals())) {
|
||||
throw new \LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name));
|
||||
}
|
||||
|
||||
if (null !== $this->resolvedGlobals) {
|
||||
$this->resolvedGlobals[$name] = $value;
|
||||
} else {
|
||||
$this->globals[$name] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getGlobals(): array
|
||||
{
|
||||
if ($this->extensionSet->isInitialized()) {
|
||||
if (null === $this->resolvedGlobals) {
|
||||
$this->resolvedGlobals = array_merge($this->extensionSet->getGlobals(), $this->globals);
|
||||
}
|
||||
|
||||
return $this->resolvedGlobals;
|
||||
}
|
||||
|
||||
return array_merge($this->extensionSet->getGlobals(), $this->globals);
|
||||
}
|
||||
|
||||
public function mergeGlobals(array $context): array
|
||||
{
|
||||
// we don't use array_merge as the context being generally
|
||||
// bigger than globals, this code is faster.
|
||||
foreach ($this->getGlobals() as $key => $value) {
|
||||
if (!\array_key_exists($key, $context)) {
|
||||
$context[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* @return array<string, array{precedence: int, class: class-string<AbstractUnary>}>
|
||||
*/
|
||||
public function getUnaryOperators(): array
|
||||
{
|
||||
return $this->extensionSet->getUnaryOperators();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* @return array<string, array{precedence: int, class: class-string<AbstractBinary>, associativity: ExpressionParser::OPERATOR_*}>
|
||||
*/
|
||||
public function getBinaryOperators(): array
|
||||
{
|
||||
return $this->extensionSet->getBinaryOperators();
|
||||
}
|
||||
|
||||
private function updateOptionsHash(): void
|
||||
{
|
||||
$this->optionsHash = implode(':', [
|
||||
$this->extensionSet->getSignature(),
|
||||
\PHP_MAJOR_VERSION,
|
||||
\PHP_MINOR_VERSION,
|
||||
self::VERSION,
|
||||
(int) $this->debug,
|
||||
(int) $this->strictVariables,
|
||||
]);
|
||||
}
|
||||
}
|
@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Error;
|
||||
|
||||
use Twig\Source;
|
||||
use Twig\Template;
|
||||
|
||||
/**
|
||||
* Twig base exception.
|
||||
*
|
||||
* This exception class and its children must only be used when
|
||||
* an error occurs during the loading of a template, when a syntax error
|
||||
* is detected in a template, or when rendering a template. Other
|
||||
* errors must use regular PHP exception classes (like when the template
|
||||
* cache directory is not writable for instance).
|
||||
*
|
||||
* To help debugging template issues, this class tracks the original template
|
||||
* name and line where the error occurred.
|
||||
*
|
||||
* Whenever possible, you must set these information (original template name
|
||||
* and line number) yourself by passing them to the constructor. If some or all
|
||||
* these information are not available from where you throw the exception, then
|
||||
* this class will guess them automatically (when the line number is set to -1
|
||||
* and/or the name is set to null). As this is a costly operation, this
|
||||
* can be disabled by passing false for both the name and the line number
|
||||
* when creating a new instance of this class.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class Error extends \Exception
|
||||
{
|
||||
private $lineno;
|
||||
private $name;
|
||||
private $rawMessage;
|
||||
private $sourcePath;
|
||||
private $sourceCode;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* By default, automatic guessing is enabled.
|
||||
*
|
||||
* @param string $message The error message
|
||||
* @param int $lineno The template line where the error occurred
|
||||
* @param Source|null $source The source context where the error occurred
|
||||
*/
|
||||
public function __construct(string $message, int $lineno = -1, Source $source = null, \Throwable $previous = null)
|
||||
{
|
||||
parent::__construct('', 0, $previous);
|
||||
|
||||
if (null === $source) {
|
||||
$name = null;
|
||||
} else {
|
||||
$name = $source->getName();
|
||||
$this->sourceCode = $source->getCode();
|
||||
$this->sourcePath = $source->getPath();
|
||||
}
|
||||
|
||||
$this->lineno = $lineno;
|
||||
$this->name = $name;
|
||||
$this->rawMessage = $message;
|
||||
$this->updateRepr();
|
||||
}
|
||||
|
||||
public function getRawMessage(): string
|
||||
{
|
||||
return $this->rawMessage;
|
||||
}
|
||||
|
||||
public function getTemplateLine(): int
|
||||
{
|
||||
return $this->lineno;
|
||||
}
|
||||
|
||||
public function setTemplateLine(int $lineno): void
|
||||
{
|
||||
$this->lineno = $lineno;
|
||||
|
||||
$this->updateRepr();
|
||||
}
|
||||
|
||||
public function getSourceContext(): ?Source
|
||||
{
|
||||
return $this->name ? new Source($this->sourceCode, $this->name, $this->sourcePath) : null;
|
||||
}
|
||||
|
||||
public function setSourceContext(Source $source = null): void
|
||||
{
|
||||
if (null === $source) {
|
||||
$this->sourceCode = $this->name = $this->sourcePath = null;
|
||||
} else {
|
||||
$this->sourceCode = $source->getCode();
|
||||
$this->name = $source->getName();
|
||||
$this->sourcePath = $source->getPath();
|
||||
}
|
||||
|
||||
$this->updateRepr();
|
||||
}
|
||||
|
||||
public function guess(): void
|
||||
{
|
||||
$this->guessTemplateInfo();
|
||||
$this->updateRepr();
|
||||
}
|
||||
|
||||
public function appendMessage($rawMessage): void
|
||||
{
|
||||
$this->rawMessage .= $rawMessage;
|
||||
$this->updateRepr();
|
||||
}
|
||||
|
||||
private function updateRepr(): void
|
||||
{
|
||||
$this->message = $this->rawMessage;
|
||||
|
||||
if ($this->sourcePath && $this->lineno > 0) {
|
||||
$this->file = $this->sourcePath;
|
||||
$this->line = $this->lineno;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$dot = false;
|
||||
if (str_ends_with($this->message, '.')) {
|
||||
$this->message = substr($this->message, 0, -1);
|
||||
$dot = true;
|
||||
}
|
||||
|
||||
$questionMark = false;
|
||||
if (str_ends_with($this->message, '?')) {
|
||||
$this->message = substr($this->message, 0, -1);
|
||||
$questionMark = true;
|
||||
}
|
||||
|
||||
if ($this->name) {
|
||||
if (\is_string($this->name) || (\is_object($this->name) && method_exists($this->name, '__toString'))) {
|
||||
$name = sprintf('"%s"', $this->name);
|
||||
} else {
|
||||
$name = json_encode($this->name);
|
||||
}
|
||||
$this->message .= sprintf(' in %s', $name);
|
||||
}
|
||||
|
||||
if ($this->lineno && $this->lineno >= 0) {
|
||||
$this->message .= sprintf(' at line %d', $this->lineno);
|
||||
}
|
||||
|
||||
if ($dot) {
|
||||
$this->message .= '.';
|
||||
}
|
||||
|
||||
if ($questionMark) {
|
||||
$this->message .= '?';
|
||||
}
|
||||
}
|
||||
|
||||
private function guessTemplateInfo(): void
|
||||
{
|
||||
$template = null;
|
||||
$templateClass = null;
|
||||
|
||||
$backtrace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS | \DEBUG_BACKTRACE_PROVIDE_OBJECT);
|
||||
foreach ($backtrace as $trace) {
|
||||
if (isset($trace['object']) && $trace['object'] instanceof Template) {
|
||||
$currentClass = \get_class($trace['object']);
|
||||
$isEmbedContainer = null === $templateClass ? false : str_starts_with($templateClass, $currentClass);
|
||||
if (null === $this->name || ($this->name == $trace['object']->getTemplateName() && !$isEmbedContainer)) {
|
||||
$template = $trace['object'];
|
||||
$templateClass = \get_class($trace['object']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update template name
|
||||
if (null !== $template && null === $this->name) {
|
||||
$this->name = $template->getTemplateName();
|
||||
}
|
||||
|
||||
// update template path if any
|
||||
if (null !== $template && null === $this->sourcePath) {
|
||||
$src = $template->getSourceContext();
|
||||
$this->sourceCode = $src->getCode();
|
||||
$this->sourcePath = $src->getPath();
|
||||
}
|
||||
|
||||
if (null === $template || $this->lineno > -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
$r = new \ReflectionObject($template);
|
||||
$file = $r->getFileName();
|
||||
|
||||
$exceptions = [$e = $this];
|
||||
while ($e = $e->getPrevious()) {
|
||||
$exceptions[] = $e;
|
||||
}
|
||||
|
||||
while ($e = array_pop($exceptions)) {
|
||||
$traces = $e->getTrace();
|
||||
array_unshift($traces, ['file' => $e->getFile(), 'line' => $e->getLine()]);
|
||||
|
||||
while ($trace = array_shift($traces)) {
|
||||
if (!isset($trace['file']) || !isset($trace['line']) || $file != $trace['file']) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($template->getDebugInfo() as $codeLine => $templateLine) {
|
||||
if ($codeLine <= $trace['line']) {
|
||||
// update template line
|
||||
$this->lineno = $templateLine;
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Error;
|
||||
|
||||
/**
|
||||
* Exception thrown when an error occurs during template loading.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class LoaderError extends Error
|
||||
{
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
* (c) Armin Ronacher
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Error;
|
||||
|
||||
/**
|
||||
* Exception thrown when an error occurs at runtime.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class RuntimeError extends Error
|
||||
{
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
* (c) Armin Ronacher
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Error;
|
||||
|
||||
/**
|
||||
* \Exception thrown when a syntax error occurs during lexing or parsing of a template.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class SyntaxError extends Error
|
||||
{
|
||||
/**
|
||||
* Tweaks the error message to include suggestions.
|
||||
*
|
||||
* @param string $name The original name of the item that does not exist
|
||||
* @param array $items An array of possible items
|
||||
*/
|
||||
public function addSuggestions(string $name, array $items): void
|
||||
{
|
||||
$alternatives = [];
|
||||
foreach ($items as $item) {
|
||||
$lev = levenshtein($name, $item);
|
||||
if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
|
||||
$alternatives[$item] = $lev;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$alternatives) {
|
||||
return;
|
||||
}
|
||||
|
||||
asort($alternatives);
|
||||
|
||||
$this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', array_keys($alternatives))));
|
||||
}
|
||||
}
|
@ -0,0 +1,841 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
* (c) Armin Ronacher
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig;
|
||||
|
||||
use Twig\Error\SyntaxError;
|
||||
use Twig\Node\Expression\AbstractExpression;
|
||||
use Twig\Node\Expression\ArrayExpression;
|
||||
use Twig\Node\Expression\ArrowFunctionExpression;
|
||||
use Twig\Node\Expression\AssignNameExpression;
|
||||
use Twig\Node\Expression\Binary\AbstractBinary;
|
||||
use Twig\Node\Expression\Binary\ConcatBinary;
|
||||
use Twig\Node\Expression\BlockReferenceExpression;
|
||||
use Twig\Node\Expression\ConditionalExpression;
|
||||
use Twig\Node\Expression\ConstantExpression;
|
||||
use Twig\Node\Expression\GetAttrExpression;
|
||||
use Twig\Node\Expression\MethodCallExpression;
|
||||
use Twig\Node\Expression\NameExpression;
|
||||
use Twig\Node\Expression\ParentExpression;
|
||||
use Twig\Node\Expression\TestExpression;
|
||||
use Twig\Node\Expression\Unary\AbstractUnary;
|
||||
use Twig\Node\Expression\Unary\NegUnary;
|
||||
use Twig\Node\Expression\Unary\NotUnary;
|
||||
use Twig\Node\Expression\Unary\PosUnary;
|
||||
use Twig\Node\Node;
|
||||
|
||||
/**
|
||||
* Parses expressions.
|
||||
*
|
||||
* This parser implements a "Precedence climbing" algorithm.
|
||||
*
|
||||
* @see https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
|
||||
* @see https://en.wikipedia.org/wiki/Operator-precedence_parser
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class ExpressionParser
|
||||
{
|
||||
public const OPERATOR_LEFT = 1;
|
||||
public const OPERATOR_RIGHT = 2;
|
||||
|
||||
private $parser;
|
||||
private $env;
|
||||
/** @var array<string, array{precedence: int, class: class-string<AbstractUnary>}> */
|
||||
private $unaryOperators;
|
||||
/** @var array<string, array{precedence: int, class: class-string<AbstractBinary>, associativity: self::OPERATOR_*}> */
|
||||
private $binaryOperators;
|
||||
|
||||
public function __construct(Parser $parser, Environment $env)
|
||||
{
|
||||
$this->parser = $parser;
|
||||
$this->env = $env;
|
||||
$this->unaryOperators = $env->getUnaryOperators();
|
||||
$this->binaryOperators = $env->getBinaryOperators();
|
||||
}
|
||||
|
||||
public function parseExpression($precedence = 0, $allowArrow = false)
|
||||
{
|
||||
if ($allowArrow && $arrow = $this->parseArrow()) {
|
||||
return $arrow;
|
||||
}
|
||||
|
||||
$expr = $this->getPrimary();
|
||||
$token = $this->parser->getCurrentToken();
|
||||
while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) {
|
||||
$op = $this->binaryOperators[$token->getValue()];
|
||||
$this->parser->getStream()->next();
|
||||
|
||||
if ('is not' === $token->getValue()) {
|
||||
$expr = $this->parseNotTestExpression($expr);
|
||||
} elseif ('is' === $token->getValue()) {
|
||||
$expr = $this->parseTestExpression($expr);
|
||||
} elseif (isset($op['callable'])) {
|
||||
$expr = $op['callable']($this->parser, $expr);
|
||||
} else {
|
||||
$expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence'], true);
|
||||
$class = $op['class'];
|
||||
$expr = new $class($expr, $expr1, $token->getLine());
|
||||
}
|
||||
|
||||
$token = $this->parser->getCurrentToken();
|
||||
}
|
||||
|
||||
if (0 === $precedence) {
|
||||
return $this->parseConditionalExpression($expr);
|
||||
}
|
||||
|
||||
return $expr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ArrowFunctionExpression|null
|
||||
*/
|
||||
private function parseArrow()
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
|
||||
// short array syntax (one argument, no parentheses)?
|
||||
if ($stream->look(1)->test(/* Token::ARROW_TYPE */ 12)) {
|
||||
$line = $stream->getCurrent()->getLine();
|
||||
$token = $stream->expect(/* Token::NAME_TYPE */ 5);
|
||||
$names = [new AssignNameExpression($token->getValue(), $token->getLine())];
|
||||
$stream->expect(/* Token::ARROW_TYPE */ 12);
|
||||
|
||||
return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line);
|
||||
}
|
||||
|
||||
// first, determine if we are parsing an arrow function by finding => (long form)
|
||||
$i = 0;
|
||||
if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
|
||||
return null;
|
||||
}
|
||||
++$i;
|
||||
while (true) {
|
||||
// variable name
|
||||
++$i;
|
||||
if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
|
||||
break;
|
||||
}
|
||||
++$i;
|
||||
}
|
||||
if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) {
|
||||
return null;
|
||||
}
|
||||
++$i;
|
||||
if (!$stream->look($i)->test(/* Token::ARROW_TYPE */ 12)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// yes, let's parse it properly
|
||||
$token = $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '(');
|
||||
$line = $token->getLine();
|
||||
|
||||
$names = [];
|
||||
while (true) {
|
||||
$token = $stream->expect(/* Token::NAME_TYPE */ 5);
|
||||
$names[] = new AssignNameExpression($token->getValue(), $token->getLine());
|
||||
|
||||
if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')');
|
||||
$stream->expect(/* Token::ARROW_TYPE */ 12);
|
||||
|
||||
return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line);
|
||||
}
|
||||
|
||||
private function getPrimary(): AbstractExpression
|
||||
{
|
||||
$token = $this->parser->getCurrentToken();
|
||||
|
||||
if ($this->isUnary($token)) {
|
||||
$operator = $this->unaryOperators[$token->getValue()];
|
||||
$this->parser->getStream()->next();
|
||||
$expr = $this->parseExpression($operator['precedence']);
|
||||
$class = $operator['class'];
|
||||
|
||||
return $this->parsePostfixExpression(new $class($expr, $token->getLine()));
|
||||
} elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
|
||||
$this->parser->getStream()->next();
|
||||
$expr = $this->parseExpression();
|
||||
$this->parser->getStream()->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'An opened parenthesis is not properly closed');
|
||||
|
||||
return $this->parsePostfixExpression($expr);
|
||||
}
|
||||
|
||||
return $this->parsePrimaryExpression();
|
||||
}
|
||||
|
||||
private function parseConditionalExpression($expr): AbstractExpression
|
||||
{
|
||||
while ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, '?')) {
|
||||
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
||||
$expr2 = $this->parseExpression();
|
||||
if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
||||
// Ternary operator (expr ? expr2 : expr3)
|
||||
$expr3 = $this->parseExpression();
|
||||
} else {
|
||||
// Ternary without else (expr ? expr2)
|
||||
$expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine());
|
||||
}
|
||||
} else {
|
||||
// Ternary without then (expr ?: expr3)
|
||||
$expr2 = $expr;
|
||||
$expr3 = $this->parseExpression();
|
||||
}
|
||||
|
||||
$expr = new ConditionalExpression($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine());
|
||||
}
|
||||
|
||||
return $expr;
|
||||
}
|
||||
|
||||
private function isUnary(Token $token): bool
|
||||
{
|
||||
return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->unaryOperators[$token->getValue()]);
|
||||
}
|
||||
|
||||
private function isBinary(Token $token): bool
|
||||
{
|
||||
return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->binaryOperators[$token->getValue()]);
|
||||
}
|
||||
|
||||
public function parsePrimaryExpression()
|
||||
{
|
||||
$token = $this->parser->getCurrentToken();
|
||||
switch ($token->getType()) {
|
||||
case /* Token::NAME_TYPE */ 5:
|
||||
$this->parser->getStream()->next();
|
||||
switch ($token->getValue()) {
|
||||
case 'true':
|
||||
case 'TRUE':
|
||||
$node = new ConstantExpression(true, $token->getLine());
|
||||
break;
|
||||
|
||||
case 'false':
|
||||
case 'FALSE':
|
||||
$node = new ConstantExpression(false, $token->getLine());
|
||||
break;
|
||||
|
||||
case 'none':
|
||||
case 'NONE':
|
||||
case 'null':
|
||||
case 'NULL':
|
||||
$node = new ConstantExpression(null, $token->getLine());
|
||||
break;
|
||||
|
||||
default:
|
||||
if ('(' === $this->parser->getCurrentToken()->getValue()) {
|
||||
$node = $this->getFunctionNode($token->getValue(), $token->getLine());
|
||||
} else {
|
||||
$node = new NameExpression($token->getValue(), $token->getLine());
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case /* Token::NUMBER_TYPE */ 6:
|
||||
$this->parser->getStream()->next();
|
||||
$node = new ConstantExpression($token->getValue(), $token->getLine());
|
||||
break;
|
||||
|
||||
case /* Token::STRING_TYPE */ 7:
|
||||
case /* Token::INTERPOLATION_START_TYPE */ 10:
|
||||
$node = $this->parseStringExpression();
|
||||
break;
|
||||
|
||||
case /* Token::OPERATOR_TYPE */ 8:
|
||||
if (preg_match(Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) {
|
||||
// in this context, string operators are variable names
|
||||
$this->parser->getStream()->next();
|
||||
$node = new NameExpression($token->getValue(), $token->getLine());
|
||||
break;
|
||||
}
|
||||
|
||||
if (isset($this->unaryOperators[$token->getValue()])) {
|
||||
$class = $this->unaryOperators[$token->getValue()]['class'];
|
||||
if (!\in_array($class, [NegUnary::class, PosUnary::class])) {
|
||||
throw new SyntaxError(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
|
||||
}
|
||||
|
||||
$this->parser->getStream()->next();
|
||||
$expr = $this->parsePrimaryExpression();
|
||||
|
||||
$node = new $class($expr, $token->getLine());
|
||||
break;
|
||||
}
|
||||
|
||||
// no break
|
||||
default:
|
||||
if ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '[')) {
|
||||
$node = $this->parseArrayExpression();
|
||||
} elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '{')) {
|
||||
$node = $this->parseHashExpression();
|
||||
} elseif ($token->test(/* Token::OPERATOR_TYPE */ 8, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) {
|
||||
throw new SyntaxError(sprintf('Unexpected operator of value "%s". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
|
||||
} else {
|
||||
throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext());
|
||||
}
|
||||
}
|
||||
|
||||
return $this->parsePostfixExpression($node);
|
||||
}
|
||||
|
||||
public function parseStringExpression()
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
|
||||
$nodes = [];
|
||||
// a string cannot be followed by another string in a single expression
|
||||
$nextCanBeString = true;
|
||||
while (true) {
|
||||
if ($nextCanBeString && $token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) {
|
||||
$nodes[] = new ConstantExpression($token->getValue(), $token->getLine());
|
||||
$nextCanBeString = false;
|
||||
} elseif ($stream->nextIf(/* Token::INTERPOLATION_START_TYPE */ 10)) {
|
||||
$nodes[] = $this->parseExpression();
|
||||
$stream->expect(/* Token::INTERPOLATION_END_TYPE */ 11);
|
||||
$nextCanBeString = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$expr = array_shift($nodes);
|
||||
foreach ($nodes as $node) {
|
||||
$expr = new ConcatBinary($expr, $node, $node->getTemplateLine());
|
||||
}
|
||||
|
||||
return $expr;
|
||||
}
|
||||
|
||||
public function parseArrayExpression()
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '[', 'An array element was expected');
|
||||
|
||||
$node = new ArrayExpression([], $stream->getCurrent()->getLine());
|
||||
$first = true;
|
||||
while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) {
|
||||
if (!$first) {
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'An array element must be followed by a comma');
|
||||
|
||||
// trailing ,?
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$first = false;
|
||||
|
||||
if ($stream->test(/* Token::SPREAD_TYPE */ 13)) {
|
||||
$stream->next();
|
||||
$expr = $this->parseExpression();
|
||||
$expr->setAttribute('spread', true);
|
||||
$node->addElement($expr);
|
||||
} else {
|
||||
$node->addElement($this->parseExpression());
|
||||
}
|
||||
}
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']', 'An opened array is not properly closed');
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
public function parseHashExpression()
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '{', 'A hash element was expected');
|
||||
|
||||
$node = new ArrayExpression([], $stream->getCurrent()->getLine());
|
||||
$first = true;
|
||||
while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) {
|
||||
if (!$first) {
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'A hash value must be followed by a comma');
|
||||
|
||||
// trailing ,?
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$first = false;
|
||||
|
||||
if ($stream->test(/* Token::SPREAD_TYPE */ 13)) {
|
||||
$stream->next();
|
||||
$value = $this->parseExpression();
|
||||
$value->setAttribute('spread', true);
|
||||
$node->addElement($value);
|
||||
continue;
|
||||
}
|
||||
|
||||
// a hash key can be:
|
||||
//
|
||||
// * a number -- 12
|
||||
// * a string -- 'a'
|
||||
// * a name, which is equivalent to a string -- a
|
||||
// * an expression, which must be enclosed in parentheses -- (1 + 2)
|
||||
if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) {
|
||||
$key = new ConstantExpression($token->getValue(), $token->getLine());
|
||||
|
||||
// {a} is a shortcut for {a:a}
|
||||
if ($stream->test(Token::PUNCTUATION_TYPE, [',', '}'])) {
|
||||
$value = new NameExpression($key->getAttribute('value'), $key->getTemplateLine());
|
||||
$node->addElement($value, $key);
|
||||
continue;
|
||||
}
|
||||
} elseif (($token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) || $token = $stream->nextIf(/* Token::NUMBER_TYPE */ 6)) {
|
||||
$key = new ConstantExpression($token->getValue(), $token->getLine());
|
||||
} elseif ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
|
||||
$key = $this->parseExpression();
|
||||
} else {
|
||||
$current = $stream->getCurrent();
|
||||
|
||||
throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext());
|
||||
}
|
||||
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ':', 'A hash key must be followed by a colon (:)');
|
||||
$value = $this->parseExpression();
|
||||
|
||||
$node->addElement($value, $key);
|
||||
}
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '}', 'An opened hash is not properly closed');
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
public function parsePostfixExpression($node)
|
||||
{
|
||||
while (true) {
|
||||
$token = $this->parser->getCurrentToken();
|
||||
if (/* Token::PUNCTUATION_TYPE */ 9 == $token->getType()) {
|
||||
if ('.' == $token->getValue() || '[' == $token->getValue()) {
|
||||
$node = $this->parseSubscriptExpression($node);
|
||||
} elseif ('|' == $token->getValue()) {
|
||||
$node = $this->parseFilterExpression($node);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
public function getFunctionNode($name, $line)
|
||||
{
|
||||
switch ($name) {
|
||||
case 'parent':
|
||||
$this->parseArguments();
|
||||
if (!\count($this->parser->getBlockStack())) {
|
||||
throw new SyntaxError('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext());
|
||||
}
|
||||
|
||||
if (!$this->parser->getParent() && !$this->parser->hasTraits()) {
|
||||
throw new SyntaxError('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext());
|
||||
}
|
||||
|
||||
return new ParentExpression($this->parser->peekBlockStack(), $line);
|
||||
case 'block':
|
||||
$args = $this->parseArguments();
|
||||
if (\count($args) < 1) {
|
||||
throw new SyntaxError('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext());
|
||||
}
|
||||
|
||||
return new BlockReferenceExpression($args->getNode(0), \count($args) > 1 ? $args->getNode(1) : null, $line);
|
||||
case 'attribute':
|
||||
$args = $this->parseArguments();
|
||||
if (\count($args) < 2) {
|
||||
throw new SyntaxError('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext());
|
||||
}
|
||||
|
||||
return new GetAttrExpression($args->getNode(0), $args->getNode(1), \count($args) > 2 ? $args->getNode(2) : null, Template::ANY_CALL, $line);
|
||||
default:
|
||||
if (null !== $alias = $this->parser->getImportedSymbol('function', $name)) {
|
||||
$arguments = new ArrayExpression([], $line);
|
||||
foreach ($this->parseArguments() as $n) {
|
||||
$arguments->addElement($n);
|
||||
}
|
||||
|
||||
$node = new MethodCallExpression($alias['node'], $alias['name'], $arguments, $line);
|
||||
$node->setAttribute('safe', true);
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
$args = $this->parseArguments(true);
|
||||
$class = $this->getFunctionNodeClass($name, $line);
|
||||
|
||||
return new $class($name, $args, $line);
|
||||
}
|
||||
}
|
||||
|
||||
public function parseSubscriptExpression($node)
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
$token = $stream->next();
|
||||
$lineno = $token->getLine();
|
||||
$arguments = new ArrayExpression([], $lineno);
|
||||
$type = Template::ANY_CALL;
|
||||
if ('.' == $token->getValue()) {
|
||||
$token = $stream->next();
|
||||
if (
|
||||
/* Token::NAME_TYPE */ 5 == $token->getType()
|
||||
||
|
||||
/* Token::NUMBER_TYPE */ 6 == $token->getType()
|
||||
||
|
||||
(/* Token::OPERATOR_TYPE */ 8 == $token->getType() && preg_match(Lexer::REGEX_NAME, $token->getValue()))
|
||||
) {
|
||||
$arg = new ConstantExpression($token->getValue(), $lineno);
|
||||
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
|
||||
$type = Template::METHOD_CALL;
|
||||
foreach ($this->parseArguments() as $n) {
|
||||
$arguments->addElement($n);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new SyntaxError(sprintf('Expected name or number, got value "%s" of type %s.', $token->getValue(), Token::typeToEnglish($token->getType())), $lineno, $stream->getSourceContext());
|
||||
}
|
||||
|
||||
if ($node instanceof NameExpression && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) {
|
||||
$name = $arg->getAttribute('value');
|
||||
|
||||
$node = new MethodCallExpression($node, 'macro_'.$name, $arguments, $lineno);
|
||||
$node->setAttribute('safe', true);
|
||||
|
||||
return $node;
|
||||
}
|
||||
} else {
|
||||
$type = Template::ARRAY_CALL;
|
||||
|
||||
// slice?
|
||||
$slice = false;
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
||||
$slice = true;
|
||||
$arg = new ConstantExpression(0, $token->getLine());
|
||||
} else {
|
||||
$arg = $this->parseExpression();
|
||||
}
|
||||
|
||||
if ($stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) {
|
||||
$slice = true;
|
||||
}
|
||||
|
||||
if ($slice) {
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) {
|
||||
$length = new ConstantExpression(null, $token->getLine());
|
||||
} else {
|
||||
$length = $this->parseExpression();
|
||||
}
|
||||
|
||||
$class = $this->getFilterNodeClass('slice', $token->getLine());
|
||||
$arguments = new Node([$arg, $length]);
|
||||
$filter = new $class($node, new ConstantExpression('slice', $token->getLine()), $arguments, $token->getLine());
|
||||
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']');
|
||||
|
||||
return $filter;
|
||||
}
|
||||
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']');
|
||||
}
|
||||
|
||||
return new GetAttrExpression($node, $arg, $arguments, $type, $lineno);
|
||||
}
|
||||
|
||||
public function parseFilterExpression($node)
|
||||
{
|
||||
$this->parser->getStream()->next();
|
||||
|
||||
return $this->parseFilterExpressionRaw($node);
|
||||
}
|
||||
|
||||
public function parseFilterExpressionRaw($node, $tag = null)
|
||||
{
|
||||
while (true) {
|
||||
$token = $this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5);
|
||||
|
||||
$name = new ConstantExpression($token->getValue(), $token->getLine());
|
||||
if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
|
||||
$arguments = new Node();
|
||||
} else {
|
||||
$arguments = $this->parseArguments(true, false, true);
|
||||
}
|
||||
|
||||
$class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine());
|
||||
|
||||
$node = new $class($node, $name, $arguments, $token->getLine(), $tag);
|
||||
|
||||
if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '|')) {
|
||||
break;
|
||||
}
|
||||
|
||||
$this->parser->getStream()->next();
|
||||
}
|
||||
|
||||
return $node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses arguments.
|
||||
*
|
||||
* @param bool $namedArguments Whether to allow named arguments or not
|
||||
* @param bool $definition Whether we are parsing arguments for a function definition
|
||||
*
|
||||
* @return Node
|
||||
*
|
||||
* @throws SyntaxError
|
||||
*/
|
||||
public function parseArguments($namedArguments = false, $definition = false, $allowArrow = false)
|
||||
{
|
||||
$args = [];
|
||||
$stream = $this->parser->getStream();
|
||||
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '(', 'A list of arguments must begin with an opening parenthesis');
|
||||
while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) {
|
||||
if (!empty($args)) {
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'Arguments must be separated by a comma');
|
||||
|
||||
// if the comma above was a trailing comma, early exit the argument parse loop
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($definition) {
|
||||
$token = $stream->expect(/* Token::NAME_TYPE */ 5, null, 'An argument must be a name');
|
||||
$value = new NameExpression($token->getValue(), $this->parser->getCurrentToken()->getLine());
|
||||
} else {
|
||||
$value = $this->parseExpression(0, $allowArrow);
|
||||
}
|
||||
|
||||
$name = null;
|
||||
if ($namedArguments && $token = $stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) {
|
||||
if (!$value instanceof NameExpression) {
|
||||
throw new SyntaxError(sprintf('A parameter name must be a string, "%s" given.', \get_class($value)), $token->getLine(), $stream->getSourceContext());
|
||||
}
|
||||
$name = $value->getAttribute('name');
|
||||
|
||||
if ($definition) {
|
||||
$value = $this->parsePrimaryExpression();
|
||||
|
||||
if (!$this->checkConstantExpression($value)) {
|
||||
throw new SyntaxError('A default value for an argument must be a constant (a boolean, a string, a number, or an array).', $token->getLine(), $stream->getSourceContext());
|
||||
}
|
||||
} else {
|
||||
$value = $this->parseExpression(0, $allowArrow);
|
||||
}
|
||||
}
|
||||
|
||||
if ($definition) {
|
||||
if (null === $name) {
|
||||
$name = $value->getAttribute('name');
|
||||
$value = new ConstantExpression(null, $this->parser->getCurrentToken()->getLine());
|
||||
}
|
||||
$args[$name] = $value;
|
||||
} else {
|
||||
if (null === $name) {
|
||||
$args[] = $value;
|
||||
} else {
|
||||
$args[$name] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
$stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'A list of arguments must be closed by a parenthesis');
|
||||
|
||||
return new Node($args);
|
||||
}
|
||||
|
||||
public function parseAssignmentExpression()
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
$targets = [];
|
||||
while (true) {
|
||||
$token = $this->parser->getCurrentToken();
|
||||
if ($stream->test(/* Token::OPERATOR_TYPE */ 8) && preg_match(Lexer::REGEX_NAME, $token->getValue())) {
|
||||
// in this context, string operators are variable names
|
||||
$this->parser->getStream()->next();
|
||||
} else {
|
||||
$stream->expect(/* Token::NAME_TYPE */ 5, null, 'Only variables can be assigned to');
|
||||
}
|
||||
$value = $token->getValue();
|
||||
if (\in_array(strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ['true', 'false', 'none', 'null'])) {
|
||||
throw new SyntaxError(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext());
|
||||
}
|
||||
$targets[] = new AssignNameExpression($value, $token->getLine());
|
||||
|
||||
if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new Node($targets);
|
||||
}
|
||||
|
||||
public function parseMultitargetExpression()
|
||||
{
|
||||
$targets = [];
|
||||
while (true) {
|
||||
$targets[] = $this->parseExpression();
|
||||
if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new Node($targets);
|
||||
}
|
||||
|
||||
private function parseNotTestExpression(Node $node): NotUnary
|
||||
{
|
||||
return new NotUnary($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine());
|
||||
}
|
||||
|
||||
private function parseTestExpression(Node $node): TestExpression
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
list($name, $test) = $this->getTest($node->getTemplateLine());
|
||||
|
||||
$class = $this->getTestNodeClass($test);
|
||||
$arguments = null;
|
||||
if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) {
|
||||
$arguments = $this->parseArguments(true);
|
||||
} elseif ($test->hasOneMandatoryArgument()) {
|
||||
$arguments = new Node([0 => $this->parsePrimaryExpression()]);
|
||||
}
|
||||
|
||||
if ('defined' === $name && $node instanceof NameExpression && null !== $alias = $this->parser->getImportedSymbol('function', $node->getAttribute('name'))) {
|
||||
$node = new MethodCallExpression($alias['node'], $alias['name'], new ArrayExpression([], $node->getTemplateLine()), $node->getTemplateLine());
|
||||
$node->setAttribute('safe', true);
|
||||
}
|
||||
|
||||
return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine());
|
||||
}
|
||||
|
||||
private function getTest(int $line): array
|
||||
{
|
||||
$stream = $this->parser->getStream();
|
||||
$name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue();
|
||||
|
||||
if ($test = $this->env->getTest($name)) {
|
||||
return [$name, $test];
|
||||
}
|
||||
|
||||
if ($stream->test(/* Token::NAME_TYPE */ 5)) {
|
||||
// try 2-words tests
|
||||
$name = $name.' '.$this->parser->getCurrentToken()->getValue();
|
||||
|
||||
if ($test = $this->env->getTest($name)) {
|
||||
$stream->next();
|
||||
|
||||
return [$name, $test];
|
||||
}
|
||||
}
|
||||
|
||||
$e = new SyntaxError(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext());
|
||||
$e->addSuggestions($name, array_keys($this->env->getTests()));
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
private function getTestNodeClass(TwigTest $test): string
|
||||
{
|
||||
if ($test->isDeprecated()) {
|
||||
$stream = $this->parser->getStream();
|
||||
$message = sprintf('Twig Test "%s" is deprecated', $test->getName());
|
||||
|
||||
if ($test->getDeprecatedVersion()) {
|
||||
$message .= sprintf(' since version %s', $test->getDeprecatedVersion());
|
||||
}
|
||||
if ($test->getAlternative()) {
|
||||
$message .= sprintf('. Use "%s" instead', $test->getAlternative());
|
||||
}
|
||||
$src = $stream->getSourceContext();
|
||||
$message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $stream->getCurrent()->getLine());
|
||||
|
||||
@trigger_error($message, \E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
return $test->getNodeClass();
|
||||
}
|
||||
|
||||
private function getFunctionNodeClass(string $name, int $line): string
|
||||
{
|
||||
if (!$function = $this->env->getFunction($name)) {
|
||||
$e = new SyntaxError(sprintf('Unknown "%s" function.', $name), $line, $this->parser->getStream()->getSourceContext());
|
||||
$e->addSuggestions($name, array_keys($this->env->getFunctions()));
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($function->isDeprecated()) {
|
||||
$message = sprintf('Twig Function "%s" is deprecated', $function->getName());
|
||||
if ($function->getDeprecatedVersion()) {
|
||||
$message .= sprintf(' since version %s', $function->getDeprecatedVersion());
|
||||
}
|
||||
if ($function->getAlternative()) {
|
||||
$message .= sprintf('. Use "%s" instead', $function->getAlternative());
|
||||
}
|
||||
$src = $this->parser->getStream()->getSourceContext();
|
||||
$message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line);
|
||||
|
||||
@trigger_error($message, \E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
return $function->getNodeClass();
|
||||
}
|
||||
|
||||
private function getFilterNodeClass(string $name, int $line): string
|
||||
{
|
||||
if (!$filter = $this->env->getFilter($name)) {
|
||||
$e = new SyntaxError(sprintf('Unknown "%s" filter.', $name), $line, $this->parser->getStream()->getSourceContext());
|
||||
$e->addSuggestions($name, array_keys($this->env->getFilters()));
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
if ($filter->isDeprecated()) {
|
||||
$message = sprintf('Twig Filter "%s" is deprecated', $filter->getName());
|
||||
if ($filter->getDeprecatedVersion()) {
|
||||
$message .= sprintf(' since version %s', $filter->getDeprecatedVersion());
|
||||
}
|
||||
if ($filter->getAlternative()) {
|
||||
$message .= sprintf('. Use "%s" instead', $filter->getAlternative());
|
||||
}
|
||||
$src = $this->parser->getStream()->getSourceContext();
|
||||
$message .= sprintf(' in %s at line %d.', $src->getPath() ?: $src->getName(), $line);
|
||||
|
||||
@trigger_error($message, \E_USER_DEPRECATED);
|
||||
}
|
||||
|
||||
return $filter->getNodeClass();
|
||||
}
|
||||
|
||||
// checks that the node only contains "constant" elements
|
||||
private function checkConstantExpression(Node $node): bool
|
||||
{
|
||||
if (!($node instanceof ConstantExpression || $node instanceof ArrayExpression
|
||||
|| $node instanceof NegUnary || $node instanceof PosUnary
|
||||
)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($node as $n) {
|
||||
if (!$this->checkConstantExpression($n)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
abstract class AbstractExtension implements ExtensionInterface
|
||||
{
|
||||
public function getTokenParsers()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function getNodeVisitors()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function getFilters()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function getTests()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function getFunctions()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
public function getOperators()
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension {
|
||||
use Twig\TwigFunction;
|
||||
|
||||
final class DebugExtension extends AbstractExtension
|
||||
{
|
||||
public function getFunctions(): array
|
||||
{
|
||||
// dump is safe if var_dump is overridden by xdebug
|
||||
$isDumpOutputHtmlSafe = \extension_loaded('xdebug')
|
||||
// false means that it was not set (and the default is on) or it explicitly enabled
|
||||
&& (false === \ini_get('xdebug.overload_var_dump') || \ini_get('xdebug.overload_var_dump'))
|
||||
// false means that it was not set (and the default is on) or it explicitly enabled
|
||||
// xdebug.overload_var_dump produces HTML only when html_errors is also enabled
|
||||
&& (false === \ini_get('html_errors') || \ini_get('html_errors'))
|
||||
|| 'cli' === \PHP_SAPI
|
||||
;
|
||||
|
||||
return [
|
||||
new TwigFunction('dump', 'twig_var_dump', ['is_safe' => $isDumpOutputHtmlSafe ? ['html'] : [], 'needs_context' => true, 'needs_environment' => true, 'is_variadic' => true]),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
use Twig\Environment;
|
||||
use Twig\Template;
|
||||
use Twig\TemplateWrapper;
|
||||
|
||||
function twig_var_dump(Environment $env, $context, ...$vars)
|
||||
{
|
||||
if (!$env->isDebug()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ob_start();
|
||||
|
||||
if (!$vars) {
|
||||
$vars = [];
|
||||
foreach ($context as $key => $value) {
|
||||
if (!$value instanceof Template && !$value instanceof TemplateWrapper) {
|
||||
$vars[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
var_dump($vars);
|
||||
} else {
|
||||
var_dump(...$vars);
|
||||
}
|
||||
|
||||
return ob_get_clean();
|
||||
}
|
||||
}
|
@ -0,0 +1,416 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension {
|
||||
use Twig\FileExtensionEscapingStrategy;
|
||||
use Twig\NodeVisitor\EscaperNodeVisitor;
|
||||
use Twig\TokenParser\AutoEscapeTokenParser;
|
||||
use Twig\TwigFilter;
|
||||
|
||||
final class EscaperExtension extends AbstractExtension
|
||||
{
|
||||
private $defaultStrategy;
|
||||
private $escapers = [];
|
||||
|
||||
/** @internal */
|
||||
public $safeClasses = [];
|
||||
|
||||
/** @internal */
|
||||
public $safeLookup = [];
|
||||
|
||||
/**
|
||||
* @param string|false|callable $defaultStrategy An escaping strategy
|
||||
*
|
||||
* @see setDefaultStrategy()
|
||||
*/
|
||||
public function __construct($defaultStrategy = 'html')
|
||||
{
|
||||
$this->setDefaultStrategy($defaultStrategy);
|
||||
}
|
||||
|
||||
public function getTokenParsers(): array
|
||||
{
|
||||
return [new AutoEscapeTokenParser()];
|
||||
}
|
||||
|
||||
public function getNodeVisitors(): array
|
||||
{
|
||||
return [new EscaperNodeVisitor()];
|
||||
}
|
||||
|
||||
public function getFilters(): array
|
||||
{
|
||||
return [
|
||||
new TwigFilter('escape', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']),
|
||||
new TwigFilter('e', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']),
|
||||
new TwigFilter('raw', 'twig_raw_filter', ['is_safe' => ['all']]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default strategy to use when not defined by the user.
|
||||
*
|
||||
* The strategy can be a valid PHP callback that takes the template
|
||||
* name as an argument and returns the strategy to use.
|
||||
*
|
||||
* @param string|false|callable $defaultStrategy An escaping strategy
|
||||
*/
|
||||
public function setDefaultStrategy($defaultStrategy): void
|
||||
{
|
||||
if ('name' === $defaultStrategy) {
|
||||
$defaultStrategy = [FileExtensionEscapingStrategy::class, 'guess'];
|
||||
}
|
||||
|
||||
$this->defaultStrategy = $defaultStrategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the default strategy to use when not defined by the user.
|
||||
*
|
||||
* @param string $name The template name
|
||||
*
|
||||
* @return string|false The default strategy to use for the template
|
||||
*/
|
||||
public function getDefaultStrategy(string $name)
|
||||
{
|
||||
// disable string callables to avoid calling a function named html or js,
|
||||
// or any other upcoming escaping strategy
|
||||
if (!\is_string($this->defaultStrategy) && false !== $this->defaultStrategy) {
|
||||
return \call_user_func($this->defaultStrategy, $name);
|
||||
}
|
||||
|
||||
return $this->defaultStrategy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines a new escaper to be used via the escape filter.
|
||||
*
|
||||
* @param string $strategy The strategy name that should be used as a strategy in the escape call
|
||||
* @param callable $callable A valid PHP callable
|
||||
*/
|
||||
public function setEscaper($strategy, callable $callable)
|
||||
{
|
||||
$this->escapers[$strategy] = $callable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all defined escapers.
|
||||
*
|
||||
* @return callable[] An array of escapers
|
||||
*/
|
||||
public function getEscapers()
|
||||
{
|
||||
return $this->escapers;
|
||||
}
|
||||
|
||||
public function setSafeClasses(array $safeClasses = [])
|
||||
{
|
||||
$this->safeClasses = [];
|
||||
$this->safeLookup = [];
|
||||
foreach ($safeClasses as $class => $strategies) {
|
||||
$this->addSafeClass($class, $strategies);
|
||||
}
|
||||
}
|
||||
|
||||
public function addSafeClass(string $class, array $strategies)
|
||||
{
|
||||
$class = ltrim($class, '\\');
|
||||
if (!isset($this->safeClasses[$class])) {
|
||||
$this->safeClasses[$class] = [];
|
||||
}
|
||||
$this->safeClasses[$class] = array_merge($this->safeClasses[$class], $strategies);
|
||||
|
||||
foreach ($strategies as $strategy) {
|
||||
$this->safeLookup[$strategy][$class] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
use Twig\Environment;
|
||||
use Twig\Error\RuntimeError;
|
||||
use Twig\Extension\EscaperExtension;
|
||||
use Twig\Markup;
|
||||
use Twig\Node\Expression\ConstantExpression;
|
||||
use Twig\Node\Node;
|
||||
|
||||
/**
|
||||
* Marks a variable as being safe.
|
||||
*
|
||||
* @param string $string A PHP variable
|
||||
*/
|
||||
function twig_raw_filter($string)
|
||||
{
|
||||
return $string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a string.
|
||||
*
|
||||
* @param mixed $string The value to be escaped
|
||||
* @param string $strategy The escaping strategy
|
||||
* @param string $charset The charset
|
||||
* @param bool $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false)
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
function twig_escape_filter(Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false)
|
||||
{
|
||||
if ($autoescape && $string instanceof Markup) {
|
||||
return $string;
|
||||
}
|
||||
|
||||
if (!\is_string($string)) {
|
||||
if (\is_object($string) && method_exists($string, '__toString')) {
|
||||
if ($autoescape) {
|
||||
$c = \get_class($string);
|
||||
$ext = $env->getExtension(EscaperExtension::class);
|
||||
if (!isset($ext->safeClasses[$c])) {
|
||||
$ext->safeClasses[$c] = [];
|
||||
foreach (class_parents($string) + class_implements($string) as $class) {
|
||||
if (isset($ext->safeClasses[$class])) {
|
||||
$ext->safeClasses[$c] = array_unique(array_merge($ext->safeClasses[$c], $ext->safeClasses[$class]));
|
||||
foreach ($ext->safeClasses[$class] as $s) {
|
||||
$ext->safeLookup[$s][$c] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($ext->safeLookup[$strategy][$c]) || isset($ext->safeLookup['all'][$c])) {
|
||||
return (string) $string;
|
||||
}
|
||||
}
|
||||
|
||||
$string = (string) $string;
|
||||
} elseif (\in_array($strategy, ['html', 'js', 'css', 'html_attr', 'url'])) {
|
||||
return $string;
|
||||
}
|
||||
}
|
||||
|
||||
if ('' === $string) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (null === $charset) {
|
||||
$charset = $env->getCharset();
|
||||
}
|
||||
|
||||
switch ($strategy) {
|
||||
case 'html':
|
||||
// see https://www.php.net/htmlspecialchars
|
||||
|
||||
// Using a static variable to avoid initializing the array
|
||||
// each time the function is called. Moving the declaration on the
|
||||
// top of the function slow downs other escaping strategies.
|
||||
static $htmlspecialcharsCharsets = [
|
||||
'ISO-8859-1' => true, 'ISO8859-1' => true,
|
||||
'ISO-8859-15' => true, 'ISO8859-15' => true,
|
||||
'utf-8' => true, 'UTF-8' => true,
|
||||
'CP866' => true, 'IBM866' => true, '866' => true,
|
||||
'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true,
|
||||
'1251' => true,
|
||||
'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true,
|
||||
'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true,
|
||||
'BIG5' => true, '950' => true,
|
||||
'GB2312' => true, '936' => true,
|
||||
'BIG5-HKSCS' => true,
|
||||
'SHIFT_JIS' => true, 'SJIS' => true, '932' => true,
|
||||
'EUC-JP' => true, 'EUCJP' => true,
|
||||
'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true,
|
||||
];
|
||||
|
||||
if (isset($htmlspecialcharsCharsets[$charset])) {
|
||||
return htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, $charset);
|
||||
}
|
||||
|
||||
if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) {
|
||||
// cache the lowercase variant for future iterations
|
||||
$htmlspecialcharsCharsets[$charset] = true;
|
||||
|
||||
return htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, $charset);
|
||||
}
|
||||
|
||||
$string = twig_convert_encoding($string, 'UTF-8', $charset);
|
||||
$string = htmlspecialchars($string, \ENT_QUOTES | \ENT_SUBSTITUTE, 'UTF-8');
|
||||
|
||||
return iconv('UTF-8', $charset, $string);
|
||||
|
||||
case 'js':
|
||||
// escape all non-alphanumeric characters
|
||||
// into their \x or \uHHHH representations
|
||||
if ('UTF-8' !== $charset) {
|
||||
$string = twig_convert_encoding($string, 'UTF-8', $charset);
|
||||
}
|
||||
|
||||
if (!preg_match('//u', $string)) {
|
||||
throw new RuntimeError('The string to escape is not a valid UTF-8 string.');
|
||||
}
|
||||
|
||||
$string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) {
|
||||
$char = $matches[0];
|
||||
|
||||
/*
|
||||
* A few characters have short escape sequences in JSON and JavaScript.
|
||||
* Escape sequences supported only by JavaScript, not JSON, are omitted.
|
||||
* \" is also supported but omitted, because the resulting string is not HTML safe.
|
||||
*/
|
||||
static $shortMap = [
|
||||
'\\' => '\\\\',
|
||||
'/' => '\\/',
|
||||
"\x08" => '\b',
|
||||
"\x0C" => '\f',
|
||||
"\x0A" => '\n',
|
||||
"\x0D" => '\r',
|
||||
"\x09" => '\t',
|
||||
];
|
||||
|
||||
if (isset($shortMap[$char])) {
|
||||
return $shortMap[$char];
|
||||
}
|
||||
|
||||
$codepoint = mb_ord($char, 'UTF-8');
|
||||
if (0x10000 > $codepoint) {
|
||||
return sprintf('\u%04X', $codepoint);
|
||||
}
|
||||
|
||||
// Split characters outside the BMP into surrogate pairs
|
||||
// https://tools.ietf.org/html/rfc2781.html#section-2.1
|
||||
$u = $codepoint - 0x10000;
|
||||
$high = 0xD800 | ($u >> 10);
|
||||
$low = 0xDC00 | ($u & 0x3FF);
|
||||
|
||||
return sprintf('\u%04X\u%04X', $high, $low);
|
||||
}, $string);
|
||||
|
||||
if ('UTF-8' !== $charset) {
|
||||
$string = iconv('UTF-8', $charset, $string);
|
||||
}
|
||||
|
||||
return $string;
|
||||
|
||||
case 'css':
|
||||
if ('UTF-8' !== $charset) {
|
||||
$string = twig_convert_encoding($string, 'UTF-8', $charset);
|
||||
}
|
||||
|
||||
if (!preg_match('//u', $string)) {
|
||||
throw new RuntimeError('The string to escape is not a valid UTF-8 string.');
|
||||
}
|
||||
|
||||
$string = preg_replace_callback('#[^a-zA-Z0-9]#Su', function ($matches) {
|
||||
$char = $matches[0];
|
||||
|
||||
return sprintf('\\%X ', 1 === \strlen($char) ? \ord($char) : mb_ord($char, 'UTF-8'));
|
||||
}, $string);
|
||||
|
||||
if ('UTF-8' !== $charset) {
|
||||
$string = iconv('UTF-8', $charset, $string);
|
||||
}
|
||||
|
||||
return $string;
|
||||
|
||||
case 'html_attr':
|
||||
if ('UTF-8' !== $charset) {
|
||||
$string = twig_convert_encoding($string, 'UTF-8', $charset);
|
||||
}
|
||||
|
||||
if (!preg_match('//u', $string)) {
|
||||
throw new RuntimeError('The string to escape is not a valid UTF-8 string.');
|
||||
}
|
||||
|
||||
$string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', function ($matches) {
|
||||
/**
|
||||
* This function is adapted from code coming from Zend Framework.
|
||||
*
|
||||
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (https://www.zend.com)
|
||||
* @license https://framework.zend.com/license/new-bsd New BSD License
|
||||
*/
|
||||
$chr = $matches[0];
|
||||
$ord = \ord($chr);
|
||||
|
||||
/*
|
||||
* The following replaces characters undefined in HTML with the
|
||||
* hex entity for the Unicode replacement character.
|
||||
*/
|
||||
if (($ord <= 0x1F && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7F && $ord <= 0x9F)) {
|
||||
return '�';
|
||||
}
|
||||
|
||||
/*
|
||||
* Check if the current character to escape has a name entity we should
|
||||
* replace it with while grabbing the hex value of the character.
|
||||
*/
|
||||
if (1 === \strlen($chr)) {
|
||||
/*
|
||||
* While HTML supports far more named entities, the lowest common denominator
|
||||
* has become HTML5's XML Serialisation which is restricted to the those named
|
||||
* entities that XML supports. Using HTML entities would result in this error:
|
||||
* XML Parsing Error: undefined entity
|
||||
*/
|
||||
static $entityMap = [
|
||||
34 => '"', /* quotation mark */
|
||||
38 => '&', /* ampersand */
|
||||
60 => '<', /* less-than sign */
|
||||
62 => '>', /* greater-than sign */
|
||||
];
|
||||
|
||||
if (isset($entityMap[$ord])) {
|
||||
return $entityMap[$ord];
|
||||
}
|
||||
|
||||
return sprintf('&#x%02X;', $ord);
|
||||
}
|
||||
|
||||
/*
|
||||
* Per OWASP recommendations, we'll use hex entities for any other
|
||||
* characters where a named entity does not exist.
|
||||
*/
|
||||
return sprintf('&#x%04X;', mb_ord($chr, 'UTF-8'));
|
||||
}, $string);
|
||||
|
||||
if ('UTF-8' !== $charset) {
|
||||
$string = iconv('UTF-8', $charset, $string);
|
||||
}
|
||||
|
||||
return $string;
|
||||
|
||||
case 'url':
|
||||
return rawurlencode($string);
|
||||
|
||||
default:
|
||||
$escapers = $env->getExtension(EscaperExtension::class)->getEscapers();
|
||||
if (\array_key_exists($strategy, $escapers)) {
|
||||
return $escapers[$strategy]($env, $string, $charset);
|
||||
}
|
||||
|
||||
$validStrategies = implode(', ', array_merge(['html', 'js', 'url', 'css', 'html_attr'], array_keys($escapers)));
|
||||
|
||||
throw new RuntimeError(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
function twig_escape_filter_is_safe(Node $filterArgs)
|
||||
{
|
||||
foreach ($filterArgs as $arg) {
|
||||
if ($arg instanceof ConstantExpression) {
|
||||
return [$arg->getAttribute('value')];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return ['html'];
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
use Twig\ExpressionParser;
|
||||
use Twig\Node\Expression\Binary\AbstractBinary;
|
||||
use Twig\Node\Expression\Unary\AbstractUnary;
|
||||
use Twig\NodeVisitor\NodeVisitorInterface;
|
||||
use Twig\TokenParser\TokenParserInterface;
|
||||
use Twig\TwigFilter;
|
||||
use Twig\TwigFunction;
|
||||
use Twig\TwigTest;
|
||||
|
||||
/**
|
||||
* Interface implemented by extension classes.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
interface ExtensionInterface
|
||||
{
|
||||
/**
|
||||
* Returns the token parser instances to add to the existing list.
|
||||
*
|
||||
* @return TokenParserInterface[]
|
||||
*/
|
||||
public function getTokenParsers();
|
||||
|
||||
/**
|
||||
* Returns the node visitor instances to add to the existing list.
|
||||
*
|
||||
* @return NodeVisitorInterface[]
|
||||
*/
|
||||
public function getNodeVisitors();
|
||||
|
||||
/**
|
||||
* Returns a list of filters to add to the existing list.
|
||||
*
|
||||
* @return TwigFilter[]
|
||||
*/
|
||||
public function getFilters();
|
||||
|
||||
/**
|
||||
* Returns a list of tests to add to the existing list.
|
||||
*
|
||||
* @return TwigTest[]
|
||||
*/
|
||||
public function getTests();
|
||||
|
||||
/**
|
||||
* Returns a list of functions to add to the existing list.
|
||||
*
|
||||
* @return TwigFunction[]
|
||||
*/
|
||||
public function getFunctions();
|
||||
|
||||
/**
|
||||
* Returns a list of operators to add to the existing list.
|
||||
*
|
||||
* @return array<array> First array of unary operators, second array of binary operators
|
||||
*
|
||||
* @psalm-return array{
|
||||
* array<string, array{precedence: int, class: class-string<AbstractUnary>}>,
|
||||
* array<string, array{precedence: int, class: class-string<AbstractBinary>, associativity: ExpressionParser::OPERATOR_*}>
|
||||
* }
|
||||
*/
|
||||
public function getOperators();
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
/**
|
||||
* Enables usage of the deprecated Twig\Extension\AbstractExtension::getGlobals() method.
|
||||
*
|
||||
* Explicitly implement this interface if you really need to implement the
|
||||
* deprecated getGlobals() method in your extensions.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
interface GlobalsInterface
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function getGlobals(): array;
|
||||
}
|
@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
use Twig\NodeVisitor\OptimizerNodeVisitor;
|
||||
|
||||
final class OptimizerExtension extends AbstractExtension
|
||||
{
|
||||
private $optimizers;
|
||||
|
||||
public function __construct(int $optimizers = -1)
|
||||
{
|
||||
$this->optimizers = $optimizers;
|
||||
}
|
||||
|
||||
public function getNodeVisitors(): array
|
||||
{
|
||||
return [new OptimizerNodeVisitor($this->optimizers)];
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
use Twig\Profiler\NodeVisitor\ProfilerNodeVisitor;
|
||||
use Twig\Profiler\Profile;
|
||||
|
||||
class ProfilerExtension extends AbstractExtension
|
||||
{
|
||||
private $actives = [];
|
||||
|
||||
public function __construct(Profile $profile)
|
||||
{
|
||||
$this->actives[] = $profile;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function enter(Profile $profile)
|
||||
{
|
||||
$this->actives[0]->addProfile($profile);
|
||||
array_unshift($this->actives, $profile);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return void
|
||||
*/
|
||||
public function leave(Profile $profile)
|
||||
{
|
||||
$profile->leave();
|
||||
array_shift($this->actives);
|
||||
|
||||
if (1 === \count($this->actives)) {
|
||||
$this->actives[0]->leave();
|
||||
}
|
||||
}
|
||||
|
||||
public function getNodeVisitors(): array
|
||||
{
|
||||
return [new ProfilerNodeVisitor(static::class)];
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
/**
|
||||
* @author Grégoire Pineau <lyrixx@lyrixx.info>
|
||||
*/
|
||||
interface RuntimeExtensionInterface
|
||||
{
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of Twig.
|
||||
*
|
||||
* (c) Fabien Potencier
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Twig\Extension;
|
||||
|
||||
use Twig\NodeVisitor\SandboxNodeVisitor;
|
||||
use Twig\Sandbox\SecurityNotAllowedMethodError;
|
||||
use Twig\Sandbox\SecurityNotAllowedPropertyError;
|
||||
use Twig\Sandbox\SecurityPolicyInterface;
|
||||
use Twig\Source;
|
||||
use Twig\TokenParser\SandboxTokenParser;
|
||||
|
||||
final class SandboxExtension extends AbstractExtension
|
||||
{
|
||||
private $sandboxedGlobally;
|
||||
private $sandboxed;
|
||||
private $policy;
|
||||
|
||||
public function __construct(SecurityPolicyInterface $policy, $sandboxed = false)
|
||||
{
|
||||
$this->policy = $policy;
|
||||
$this->sandboxedGlobally = $sandboxed;
|
||||
}
|
||||
|
||||
public function getTokenParsers(): array
|
||||
{
|
||||
return [new SandboxTokenParser()];
|
||||
}
|
||||
|
||||
public function getNodeVisitors(): array
|
||||
{
|
||||
return [new SandboxNodeVisitor()];
|
||||
}
|
||||
|
||||
public function enableSandbox(): void
|
||||
{
|
||||
$this->sandboxed = true;
|
||||
}
|
||||
|
||||
public function disableSandbox(): void
|
||||
{
|
||||
$this->sandboxed = false;
|
||||
}
|
||||
|
||||
public function isSandboxed(): bool
|
||||
{
|
||||
return $this->sandboxedGlobally || $this->sandboxed;
|
||||
}
|
||||
|
||||
public function isSandboxedGlobally(): bool
|
||||
{
|
||||
return $this->sandboxedGlobally;
|
||||
}
|
||||
|
||||
public function setSecurityPolicy(SecurityPolicyInterface $policy)
|
||||
{
|
||||
$this->policy = $policy;
|
||||
}
|
||||
|
||||
public function getSecurityPolicy(): SecurityPolicyInterface
|
||||
{
|
||||
return $this->policy;
|
||||
}
|
||||
|
||||
public function checkSecurity($tags, $filters, $functions): void
|
||||
{
|
||||
if ($this->isSandboxed()) {
|
||||
$this->policy->checkSecurity($tags, $filters, $functions);
|
||||
}
|
||||
}
|
||||
|
||||
public function checkMethodAllowed($obj, $method, int $lineno = -1, Source $source = null): void
|
||||
{
|
||||
if ($this->isSandboxed()) {
|
||||
try {
|
||||
$this->policy->checkMethodAllowed($obj, $method);
|
||||
} catch (SecurityNotAllowedMethodError $e) {
|
||||
$e->setSourceContext($source);
|
||||
$e->setTemplateLine($lineno);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function checkPropertyAllowed($obj, $property, int $lineno = -1, Source $source = null): void
|
||||
{
|
||||
if ($this->isSandboxed()) {
|
||||
try {
|
||||
$this->policy->checkPropertyAllowed($obj, $property);
|
||||
} catch (SecurityNotAllowedPropertyError $e) {
|
||||
$e->setSourceContext($source);
|
||||
$e->setTemplateLine($lineno);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function ensureToStringAllowed($obj, int $lineno = -1, Source $source = null)
|
||||
{
|
||||
if ($this->isSandboxed() && \is_object($obj) && method_exists($obj, '__toString')) {
|
||||
try {
|
||||
$this->policy->checkMethodAllowed($obj, '__toString');
|
||||
} catch (SecurityNotAllowedMethodError $e) {
|
||||
$e->setSourceContext($source);
|
||||
$e->setTemplateLine($lineno);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
return $obj;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue