суббота, 26 ноября 2022 г.

Composer upgrade not working fix

When you want do single package upgrade like `composer update willdurand/hateoas --with-all-dependencies` and you have errors like this:

Your requirements could not be resolved to an installable set of packages:


  Problem 1

    - Root composer.json requires willdurand/hateoas ^3.8, found willdurand/hateoas[3.8.0] but these were not loaded, likely because it conflicts with another require.

  Problem 2

    - willdurand/hateoas-bundle 1.4.0 requires willdurand/hateoas ^2.10.0 -> found willdurand/hateoas[2.10.0, 2.11.0, 2.12.0] but it conflicts with your root composer.json require (^3.8).

    - sylius/resource-bundle v1.6.4 requires willdurand/hateoas-bundle ^1.2 -> satisfiable by willdurand/hateoas-bundle[1.4.0].

    - sylius/resource-bundle is locked to version v1.6.4 and an update of this package was not requested.


It means you need to go up by dependency tree and do `upgrade` manually. In my case I need to set "sylius/resource-bundle" to "^1.8", then run "composer update sylius/resource-bundle --with-all-dependencies" and finally run first command 

четверг, 20 октября 2022 г.

[NelmioApiDocBundle] how to register models without annotations or attributes?

config/packages/nelmio_api_doc.yaml:

```

nelmio_api_doc:

    models:

        use_jms: true

        names:

            - { alias: ExamType, type: StudentBundle\Form\ExamType }

            - { alias: User, type: App\Entity\User }

            - { alias: Pager, type: ApiBundle\Model\Pager }

``` 

суббота, 30 апреля 2022 г.

Почему правительство вкладывается в Airbaltic?

 в случае AirBaltic- это не траты, а инвестиции. 

Да, во время пандемии или войны, государство дает в займ или субсидирует какие затраты компании, но за период 2010 - 2019, государство дивидендами получила от эирбалтика порядка 100 миллионов. 

Вообще сам факт гос-корпораций он с точки зрения экономики плохой, так как на этом рынке сразу умерает конкуренция следовательно и качество. Но авиоиндустрия должна быть все же сильно регулируемая, так как это важный драйвер роста. Не будь у нас в стране аирбалтика, было бы в разы меньше прямых рейсов, было бы в разы меньше и туристов и конференеций и т.д.

Ты знал, например, что когда глобальный игрок типо сведбанка решает в какой стране открыть бекофис, он в числе прочих рассматривает сколько в эту страну лететь из разных частей света, Аирбалтик в этом случае дает преимущество.

Подитожив: 

- все инвестиции государства в аирбалтик так или иначе возвращаются в государство

- по-хорошему аирбалтик нужно продать частными инвесторам через IPO, обеспечив займ облигациями всей индустрии, а не одному игроку (но это сложный процесс)

- наличие своей авиакомпании является важным драйвером роста экономики страны. 

Есть еще один факт, который будет честно с моей стороны упоминуть. Чем больше объем закупок у одного контр-агента, тем больше возможный откат, и я думаю, это очевидно, тенедеры на самалеты в разы больше чем условные тендеры на детские площадки, поэтому и коррупционный механизм, я думаю, присутсвует (но за руку никого не поймал) (

среда, 2 марта 2022 г.

[php] code changes does not applied, how to fix?

If you make changes in php code and don't see that they work, like code remains the same, do this

 be sure your php.ini configuration `opcache.validate_timestamps=0` ,  not 1. It can be in dev mode when you try to optimize Symfony project workflow.

суббота, 12 февраля 2022 г.

[SyliusResourceBundle] how to pass model into controller?

 Sometimes you don't need to use model instead of entity, and then save some data into entity and persist it. It means you cannot use it in Sylius ResourceControllers, because your model must implement ResourceInterface, create dedicated ResourceController, Repository, Manager, and model cannot do it.

If you want it, this means you doing it wrong, because it violated CRUD principles. The best solution is to use Symfony Data Transformers https://symfony.com/doc/current/form/data_transformers.html , add it to your form, implement transform() method, where it will create your model/DTO object from entity, and reverseTransform(), where DTO will be converted into Entity object.

вторник, 1 февраля 2022 г.

[Doctrine] how to replace Many-To-Many to three entities

When you need to put new field/database columns into Many-To-Many, relationship, you will need to switch to intermediate entity. In my case it is StudentKlass.

Imagine three entities: Team - StudentTeam - Student

use Doctrine\ORM\Mapping as ORM;

class Team {
/**
* @ORM\OneToMany(targetEntity=StudentTeam::class, mappedBy="team", cascade={"persist"})
*/
private $studentTeams;

public function __construct() {
$this->studentTeams = new ArrayCollection();
}
...
}

class StudentTeam {
/**
* @ORM\ManyToOne(targetEntity=Student::class, inversedBy="teams")
* @ORM\JoinColumn(name="student_id", referencedColumnName="id")
*/
private $student;

/**
* @ORM\ManyToOne(targetEntity=Team::class, inversedBy="studentTeams")
*/
private $team;
...
}

class Student {
/**
* @ORM\OneToMany(targetEntity=StudentTeam::class, mappedBy="student")
*/
private $teams;
private $name;
private $email;
...

} 

Also don't forget to create getters, adders & removers!

You can use example how to use it in Symfony forms, which has example how to use nested forms:

class TeamType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('studentTeams', CollectionType::class, [
'entry_type' => TeamStudentType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
]);
...
}

class TeamStudentType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add(
$builder
->create('student', FormType::class, [
'data_class' => Student::class,
])
->add('email', TextType::class)
->add('name', TextType::class)
)
;
}
}
}

пятница, 28 января 2022 г.

[Symfony] "FormType too few arguments passed 0, 1 argument needed" fix

It can be not only FormType, also can be any your custom form type. 

It can be when you moved your form into new namespace/bundle, but did not registered services in it. 

  1. don't forget that your form should extend Symfony\Component\Form\AbstractType;
  2. add new bundle namespace in composer.json
  3. Create bundle extension file in ./DependencyInjection/FooExtenstion like this https://symfony.com/doc/current/bundles/extension.html
  4. add this into your bundle services.yaml:
services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true

    FooBundle\:
        resource: '../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'
        5. run php bin/console cache:clear