From e515ab254b55d69ae26ee05aa22791e16e058ed2 Mon Sep 17 00:00:00 2001
From: Cerdic <cedric@yterium.com>
Date: Fri, 24 Mar 2023 15:40:54 +0100
Subject: [PATCH] =?UTF-8?q?feat:=20`extraire=5Fbalises()`=20prend=20une=20?=
 =?UTF-8?q?option=20`nb=5Fmax`=20pour=20limiter=20la=20recherche=20en=20no?=
 =?UTF-8?q?mbre=20d'occurences,=20utilis=C3=A9e=20par=20`extraire=5Fbalise?=
 =?UTF-8?q?()`?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 ecrire/inc/filtres.php                  | 8 +++++---
 ecrire/src/Texte/Collecteur/HtmlTag.php | 6 +++++-
 2 files changed, 10 insertions(+), 4 deletions(-)

diff --git a/ecrire/inc/filtres.php b/ecrire/inc/filtres.php
index 39cfa12dfb..1c7136cfc3 100644
--- a/ecrire/inc/filtres.php
+++ b/ecrire/inc/filtres.php
@@ -2450,7 +2450,7 @@ function tags2dcsubject($tags) {
  *     - Tableau de résultats, si tableau en entrée.
  **/
 function extraire_balise($texte, $tag = 'a') {
-	$balises = extraire_balises($texte, $tag);
+	$balises = extraire_balises($texte, $tag, ['nb_max' => 1]);
 	if (is_array($texte)) {
 		return array_map(function(array $a) {return (empty($a) ? '' : reset($a));}, $balises);
 	}
@@ -2478,11 +2478,13 @@ function extraire_balise($texte, $tag = 'a') {
  *     texte(s) dont on souhaite extraire une balise html
  * @param string $tag
  *     Nom de la balise html à extraire
+ * @param array $options
+ *     int @nb_max : nombre d'occurence maxi à extraire
  * @return array
  *     - Liste des codes html des occurrences de la balise, sinon tableau vide
  *     - Tableau de résultats, si tableau en entrée.
  **/
-function extraire_balises($texte, $tag = 'a') {
+function extraire_balises($texte, $tag = 'a', $options = []) {
 	if (is_array($texte)) {
 		array_walk(
 			$texte,
@@ -2496,7 +2498,7 @@ function extraire_balises($texte, $tag = 'a') {
 	}
 
 	$htmlTagCollecteur = new \Spip\Texte\Collecteur\HtmlTag($tag);
-	$collection = $htmlTagCollecteur->collecter($texte);
+	$collection = $htmlTagCollecteur->collecter($texte, $options);
 	if (!empty($collection)) {
 		return array_column($collection, 'raw');
 	}
diff --git a/ecrire/src/Texte/Collecteur/HtmlTag.php b/ecrire/src/Texte/Collecteur/HtmlTag.php
index a7004c0e38..8d8206a103 100644
--- a/ecrire/src/Texte/Collecteur/HtmlTag.php
+++ b/ecrire/src/Texte/Collecteur/HtmlTag.php
@@ -49,6 +49,7 @@ class HtmlTag extends AbstractCollecteur {
 	 * @param string $texte
 	 * @param array $options
 	 *   bool $detecter_presence
+	 *   bool $nb_max
 	 * @return array
 	 */
 	public function collecter(string $texte, array $options = []): array {
@@ -130,7 +131,10 @@ class HtmlTag extends AbstractCollecteur {
 					$tags[] = $tag;
 				}
 			}
-			if (!empty($options['detecter_presence']) and count($tags)) {
+			if (
+				   (!empty($options['detecter_presence']) and count($tags))
+				or (!empty($options['nb_max'])  and count($tags) >= $options['nb_max'])
+			) {
 				return $tags;
 			}
 		}
-- 
GitLab