Environment with comma separated optional arguments

Using xparse, how does one get something like this to work?

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn

\NewDocumentEnvironment{ anenvironment }{ >{\SplitArgument{1}{,}}o }{
\begin{ auxanenvironment }[#1]
}{
\end{ auxanenvironment }
}

\NewDocumentEnvironment{ auxanenvironment }{ O{}o }{
Do~something~with~#1\IfValueTF{ #2 }{ ,~and~something~else~with~#2. }{ . }
}{}

\ExplSyntaxOff
\begin{document}
\begin{anenvironment}[this argument, this other argument]
\end{anenvironment}

\begin{anenvironment}[this argument]
\end{anenvironment}
\end{document}


While it's possible to do it with an auxiliary environment, I don't think it's the best way to do it.

You should also deal with the case when the optional argument doesn't appear: it's optional, isn't it?

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentEnvironment{anenvironment}{ >{\SplitArgument{1}{,}}o }
{
\IfValueT{#1}{ \noibe_anenvironment_arg:nn #1 }
%<initial code for the environment>
\par Start\par
}
{
%<final code for the environment>
End\par
}

\cs_new_protected:Nn \noibe_anenvironment_arg:nn
{
\tl_if_novalue:nF { #1 }
{
Do~something~with~#1
\tl_if_novalue:nTF { #2 }
{.}
{
,~and~something~else~with~#2.
}
}
}

\ExplSyntaxOff

\begin{document}

\begin{anenvironment}[this argument, this other argument]
\end{anenvironment}

\medskip

\begin{anenvironment}[this argument]
\end{anenvironment}

\medskip

\begin{anenvironment}
\end{anenvironment}

\end{document}


Without knowing your real use case, it's difficult to be less generic. I suggest you to consider a key-value interface, if the argument is for setting options.

A different approach altogether.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listofitems}
\newenvironment{anenvironment}[1][\relax]{%
\ifx\relax#1\relax\else
\foreachitem\x\in\arglist[]{%
Doing something with \detokenize\expandafter{\x}.\x\par
}%
\fi\par
}{%
\par Done doing something.\par\medskip
}
\begin{document}
\begin{anenvironment}
This is a test.
\end{anenvironment}
\begin{anenvironment}[\itshape]
This is a test.
\end{anenvironment}
\begin{anenvironment}[\itshape,\bfseries, \tiny]
This is a test.
\end{anenvironment}
\end{document}


I'm not sure that this is the right way to do it, but I just found out that removing the square braces around the argument on line 6, and changing auxanenvironment's arguments to mandatory solves the problem:

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn

\NewDocumentEnvironment{ anenvironment }{ >{\SplitArgument{1}{,}}o }{
\begin{ auxanenvironment }#1
}{
\end{ auxanenvironment }
}

\NewDocumentEnvironment{ auxanenvironment }{ mm }{
Do~something~with~#1\IfValueTF{ #2 }{ ,~and~something~else~with~#2. }{ . }
}{}

\ExplSyntaxOff
\begin{document}
\begin{anenvironment}[this argument, this other argument]
\end{anenvironment}

\begin{anenvironment}[this argument]
\end{anenvironment}
\end{document}