Valentin Castellanos scored two goals and set up two penalty kicks. (Photo courtesy of NYCFC)

BRONX — New York City FC twice battled back from one-goal deficits before exploding for three goals during a 23-minute span in the second half to upend the first-place Philadelphia Union, 4-2, at Yankee Stadium Saturday.

Midfielder Maxi Moralez converted penalty kicks on either side of halftime before he assisted on goals by Valentin Castellanos before a crowd of 24,451.

City (26 points), which sits in sixth place in the Eastern Conference, improved to 6-1-8, while Philly (32) dropped to 9-5-5.

“Maybe we are in the best form in the moment,” NYCFC head coach Dome Torrent said. “It was not easy because everybody knows we lost just one game. It’s very important in MLS because it’s a league where every game matters. It’s very important for the confidence. Especially today, it’s important when you play [with confidence against] the top of our conference.

“We were able to come back with the result. It’s very important because if you’re able to come back in this kind of game, you’re able for the future to win another game.”

Fabrice-Jean Picault gave the visitors a 1-0 lead in the seventh minute, but City battled back.

Castellanos was tripped up in the box, giving Moralez an opportunity to knot things up with his first penalty kick past goalkeeper Matt Freese in the 21st minute.

Against, Philly grabbed the lead at 2-1 in the 28th minute as Kacper Przybylko beat keeper Brad Stuver.

It was all NYCFC in the second half.

“There were many opportunities we created but unfortunately we didnt have the right timing,” Moralez said. “We didn’t play right and I believe that why we went to first half losing. Second half we were better and played better.”

Torrent had a talk with his team.

“I say in the first half, calm down, don’t lose control,” he said. “They were able to come back, not me. And the reason why is because they play with confidence and we are in a good moment right now. That doesn’t mean we will win next game. But we will play hard and we will try to win. And that is why I’m very happy for our supporters, because we haven’t played at home for 20 days, 21 days, so this is for them.”

Castellanos again was fouled in the area and again Moralez converted for a 2-2 deadlock.

Then the striker took center stage, putting home Moralez feeds in the 71st and 78th minute to boost City to victory.

This was the first time in his professional career that Castellanos was involved in four goals in a game.

“I know I also had several chances to create opportunities with penalties and to score,” he said. “Honestly I am very happy because it helped the team and I felt very comfortable in that position.”