Symfony 4 и пользовательский пакет fos не работает - PullRequest
0 голосов
/ 21 марта 2020

Я новичок в Symfony. Я установил версию 4 и пользовательский комплект 2.0. Я хочу переопределить тип регистрации по умолчанию, и я добавил свои собственные проверки полей, но они не рассматриваются. Я пытался использовать проверку сущности, и она не работает.

Вот мой json здесь:

{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "cayetanosoriano/hashids-bundle": "^1.1",
        "friendsofsymfony/user-bundle": "~2.0",
        "gregwar/image-bundle": "^3.0",
        "hashids/hashids": "~1.0",
        "nexmo/client": "^2.0",
        "odolbeau/phone-number-bundle": "^1.3",
        "passwordlib/passwordlib": "^1.0@beta",
        "sensio/framework-extra-bundle": "^5.5",
        "symfony/asset": "4.4.*",
        "symfony/console": "4.4.*",
        "symfony/dotenv": "4.4.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "4.4.*",
        "symfony/framework-bundle": "4.4.*",
        "symfony/intl": "4.4.*",
        "symfony/mailer": "4.4.*",
        "symfony/messenger": "4.4.*",
        "symfony/monolog-bundle": "^3.5",
        "symfony/options-resolver": "4.4.*",
        "symfony/security-bundle": "4.4.*",
        "symfony/security-core": "4.4.*",
        "symfony/security-csrf": "4.4.*",
        "symfony/security-guard": "4.4.*",
        "symfony/security-http": "4.4.*",
        "symfony/translation": "4.4.*",
        "symfony/twig-bundle": "4.4.*",
        "symfony/twig-pack": "^1.0",
        "symfony/yaml": "4.4.*",
        "twig/cssinliner-extra": "^3.0",
        "twig/extensions": "^1.5",
        "twig/inky-extra": "^3.0"
    },
    "require-dev": {
        "symfony/phpunit-bridge": "^5.0",
        "symfony/profiler-pack": "^1.0"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "paragonie/random_compat": "2.*",
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "4.4.*"
        }
    }
}

Мой конфигурационный файл

fos_user:
    db_driver: orm # other valid values are 'mongodb' and 'couchdb'
    firewall_name: main
    user_class: App\Entity\User\User
    from_email:
        address: "contact@flyout0.com"
        sender_name: "Josaphat Imani"
    service:
        mailer: fos_user.mailer.twig_swift
        # user_manager: custom_user_manager
            # class:  App\Repository\User\UserRepository
            # arguments: ['@fos_user.util.password_updater', '@fos_user.util.canonical_fields_updater', '@doctrine.orm.entity_manager', sApp\Entity\User\User]

    registration:
        # confirmation:
        #     enabled: true
        #     from_email:
        #         address: "contact@flyout0.com"
        #         sender_name: "Josaphat Imani"

        form:
            type: App\Form\Type\User\RegistrationType
            name: app_user_registration

Моя регистрационная форма

class RegistrationType extends AbstractType
{
    protected $countryRepository;
    protected $realCountry;
    protected $currentCountry;

    public function __construct(CountryRepository $m, SessionInterface $session)
    {
        $this->countryRepository = $m;
        $this->realCountry = $session->get('realCity')->getCountry();
        $this->currentCountry = $session->get('city')->getCountry();
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('names', TextType::class,  [
                'constraints' => [
                    new Assert\Length([
                        'min' => 3,
                        'max' => 255,
                        'minMessage' => 'invalid.names',
                        'maxMessage' => 'invalid.names'
                    ]),
                    new ValidName(),
                ],
                'invalid_message' => 'invalid.value',
            ])
            ->remove('email')
            ->add('username', TextType::class, array(
                'invalid_message' => 'invalid.username',
                'constraints' => [
                    new Assert\NotBlank(),
                    new ValidNewUsername()
                ],
            ))
            ->add('plainPassword', PasswordType::class, array(
                'invalid_message' => 'invalid.value',
                'constraints' => [
                    new Assert\Length([
                        'min' => 6,
                        'minMessage' => 'password.too.low',
                        'max' => 72,
                        'maxMessage' => 'password.too.long',
                    ]),
                ]
            ))

            ->addEventSubscriber(new RegistrationSubscriber());
    }

    public function getParent()
    {
        return RegistrationFormType::class;
    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }
}    

Моя сущность

<?php

namespace App\Entity\User;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Home\Image;
use Doctrine\ORM\Mapping\AttributeOverrides;
use Doctrine\ORM\Mapping\AttributeOverride;
use libphonenumber\PhoneNumber;
use Misd\PhoneNumberBundle\Validator\Constraints\PhoneNumber as AssertPhoneNumber;
use App\Validator\Constraints\User\ValidName;
use App\Validator\Constraints\User\ValidNewUsername;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Constraints as Assert;
use App\Validator\Constraints\User as UserAssert;


/**
 * @ORM\Entity(repositoryClass="App\Repository\User\UserRepository")
 * @ORM\Table(name="Fos_User")
 * @AttributeOverrides({
 *     @AttributeOverride(name="username",
 *         column=@ORM\Column(
 *             name="username",
 *             type="string",
 *             length=255,
 *             unique=false,
 *             nullable=true
 *         )
 *     )
 * })
 * @UniqueEntity(fields="email", message="email.used")
 * @UniqueEntity(fields="telNumber", message="tel.number.used")
 * @Assert\Callback(methods={"validateNames"})
 */
class User extends BaseUser
{
    /**
     * @var int
     * 
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * 
     * @ORM\Column(name="names", type="string", length=255)
     * @UserAssert\ValidName
     * @Assert\Length({"in"="50"})
     * @Assert\Choice(
     *     choices = { "male", "female" },
     *     message = "Choose a valid gender."
     * )
     */
    protected $names;

    /**
     * @var string
     * 
     * @ORM\Column(name="birthday", type="date", nullable=true) 
     */
    protected $birthday;

    public function __construct()
    {
        parent::__construct();

        // your own logic
        $this->roles = array('ROLE_USER');
    }

    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

}

И я получаю ошибки после регистрации в этом хранилище

<?php

namespace App\Repository\User;

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository
{

    public function findUserByUsernameOrEmail($usernameOrEmail)
    {
        if (filter_var($usernameOrEmail, FILTER_VALIDATE_EMAIL)) {
            return $this->findUserBy(array(
                'emailCanonical' => $this->canonicalizeEmail($usernameOrEmail)
            ));
        }

        return $this->createQueryBuilder('user_manager')
            ->where('user_m.phone_number = :phone_number')
            ->setParameter(':phone_number', $usernameOrEmail)
            ->getQuery()
            ->getOneOrNullResult();
    }
}

Мне нужна ваша помощь, пожалуйста, потому что я Вы прочитали документацию symfony и другие ответы на этом сайте, но ничего не помогло.

...