This problem is distilled from an environment that needs to use its body either wrapped in a minipage or not. Furthermore, this environment is to be automatically wrapped around all uses of another environment (e.g. flushleft in the following).
Explicitly wrapping myEnv around another environment works:
\documentclass{article}
\usepackage{xparse}
\usepackage{amsmath}
\NewDocumentEnvironment{myEnv}{O{}+b}
{B {#2}}
{{#2} E}
\begin{document}
\begin{myEnv}
\begin{flushleft}
flushleft
\end{flushleft}
\end{myEnv}
\end{document}
However, if I try to use environment hooks like this:
\documentclass{article}
\usepackage{xparse}
\usepackage{amsmath}
\NewDocumentEnvironment{myEnv}{O{}+b}
{B {#2}}
{{#2} E}
\BeforeBeginEnvironment{flushleft}{\begin{myEnv}}
\AfterEndEnvironment{flushleft}{\end{myEnv}}
\begin{document}
\begin{flushleft}
body
\end{flushleft}
\end{document}
then I get this error:
Extra }, or forgotten \endgroup.
\environment myEnv code #1#2->B {#2}
l.17 \end
{flushleft}
To reiterate, I'd like to have all uses of the flushleft environment to be modified as if they were explicitly wrapped in myEnv.
What's wrong with the above? Maybe the myEnv hooks are invoked for more times than I expect them to?