diff --git a/config/module.config.php b/config/module.config.php index 1be4c7b7..6e328a8b 100755 --- a/config/module.config.php +++ b/config/module.config.php @@ -310,7 +310,7 @@ 'controller' => PipeSpec::class, 'middleware' => new PipeSpec( AnrValidationMiddleware::class, - Controller\ApiAnrMeasuresMeasuresController::class, + Controller\ApiAnrMeasuresLinksController::class, ), ], ], @@ -1346,7 +1346,7 @@ Controller\ApiDuplicateAnrController::class => AutowireFactory::class, Controller\ApiAnrReferentialsController::class => AutowireFactory::class, Controller\ApiAnrMeasuresController::class => AutowireFactory::class, - Controller\ApiAnrMeasuresMeasuresController::class => AutowireFactory::class, + Controller\ApiAnrMeasuresLinksController::class => AutowireFactory::class, Controller\ApiAnrQuestionsController::class => AutowireFactory::class, Controller\ApiAnrQuestionsChoicesController::class => AutowireFactory::class, Controller\ApiAnrRolfTagsController::class => AutowireFactory::class, @@ -1479,7 +1479,6 @@ Table\ClientTable::class => ClientEntityManagerFactory::class, Table\MonarcObjectTable::class => ClientEntityManagerFactory::class, Table\MeasureTable::class => ClientEntityManagerFactory::class, - Table\MeasureMeasureTable::class => ClientEntityManagerFactory::class, Table\ObjectCategoryTable::class => ClientEntityManagerFactory::class, Table\ObjectObjectTable::class => ClientEntityManagerFactory::class, Table\OperationalRiskScaleTable::class => ClientEntityManagerFactory::class, @@ -1532,7 +1531,7 @@ Service\AnrQuestionService::class => Service\AnrQuestionServiceFactory::class, Service\AnrQuestionChoiceService::class => Service\AnrQuestionChoiceServiceFactory::class, Service\AnrMeasureService::class => AutowireFactory::class, - Service\AnrMeasureMeasureService::class => AutowireFactory::class, + Service\AnrMeasureLinkService::class => AutowireFactory::class, Service\AnrReferentialService::class => AutowireFactory::class, Service\SoaCategoryService::class => AutowireFactory::class, Service\AnrRolfTagService::class => AutowireFactory::class, @@ -1622,10 +1621,24 @@ InputValidator\Anr\CreateAnrDataInputValidator::class => ReflectionBasedAbstractFactory::class, InputValidator\Object\PostObjectDataInputValidator::class => ReflectionBasedAbstractFactory::class, InputValidator\Object\DuplicateObjectDataInputValidator::class => ReflectionBasedAbstractFactory::class, - InputValidator\Recommendation\PostRecommendationDataInputValidator::class => - ReflectionBasedAbstractFactory::class, - InputValidator\Recommendation\PatchRecommendationDataInputValidator::class => - ReflectionBasedAbstractFactory::class, + InputValidator\Recommendation\PostRecommendationDataInputValidator::class => static function ( + Containerinterface $container + ) { + return new InputValidator\Recommendation\PostRecommendationDataInputValidator( + $container->get('config'), + $container->get(CoreInputValidator\InputValidationTranslator::class), + $container->get(Table\RecommendationTable::class) + ); + }, + InputValidator\Recommendation\PatchRecommendationDataInputValidator::class => static function ( + Containerinterface $container + ) { + return new InputValidator\Recommendation\PatchRecommendationDataInputValidator( + $container->get('config'), + $container->get(CoreInputValidator\InputValidationTranslator::class), + $container->get(Table\RecommendationTable::class) + ); + }, InputValidator\RecommendationSet\PostRecommendationSetDataInputValidator::class => ReflectionBasedAbstractFactory::class, InputValidator\RecommendationRisk\ValidateRecommendationRiskDataInputValidator::class => diff --git a/migrations/db/20230901112005_fix_positions_cleanup_db.php b/migrations/db/20230901112005_fix_positions_cleanup_db.php index a6700fd4..fafaed30 100644 --- a/migrations/db/20230901112005_fix_positions_cleanup_db.php +++ b/migrations/db/20230901112005_fix_positions_cleanup_db.php @@ -114,6 +114,8 @@ public function change() $previousParentObjectId = $compositionObjectsData['father_id']; $previousAnrId = $compositionObjectsData['anr_id']; } + /* Add a unique key for the object composition. */ + $this->table('objects_objects')->addIndex(['father_id', 'child_id', 'anr_id'], ['unique' => true])->update(); /* Fix the objects categories positions. */ $objectsCategoriesQuery = $this->query( @@ -207,12 +209,21 @@ public function change() $this->execute('UPDATE measures SET soacategory_id = ' . $soaCategoryIds[$anrId] . ' WHERE uuid = "' . $measureData['uuid'] . '" and anr_id = ' . $anrId); } + + /* Replace UUID identifier in measures table to ID. */ + $this->table('measures') + ->addColumn('id', 'integer', ['signed' => false, 'after' => MysqlAdapter::FIRST]) + ->update(); + $this->execute('SET @a = 0; UPDATE measures SET id = @a := @a + 1 ORDER BY anr_id;'); + $this->table('measures')->changePrimaryKey(['id'])->addIndex(['uuid', 'anr_id'], ['unique' => true])->update(); + $this->table('measures')->changeColumn('id', 'integer', ['identity' => true, 'signed' => false])->update(); + /* Correct MeasuresMeasures table structure. */ $this->table('measures_measures') ->addColumn('id', 'integer', ['signed' => false, 'after' => MysqlAdapter::FIRST]) - ->renameColumn('father_id', 'master_measure_id') - ->renameColumn('child_id', 'linked_measure_id') - ->dropForeignKey(['master_measure_id', 'linked_measure_id', 'anr_id']) + ->addColumn('master_measure_id', 'integer', ['signed' => false, 'after' => 'id']) + ->addColumn('linked_measure_id', 'integer', ['signed' => false, 'after' => 'master_measure_id']) + ->dropForeignKey(['father_id', 'child_id', 'anr_id']) ->removeColumn('creator') ->removeColumn('created_at') ->removeColumn('updater') @@ -221,37 +232,76 @@ public function change() $this->execute('SET @a = 0; UPDATE measures_measures SET id = @a := @a + 1 ORDER BY anr_id;'); $this->table('measures_measures') ->changePrimaryKey(['id']) - ->addIndex(['master_measure_id', 'linked_measure_id', 'anr_id'], ['unique' => true]) ->update(); $this->table('measures_measures') ->changeColumn('id', 'integer', ['identity' => true, 'signed' => false]) ->update(); - /* Remove unlinked measures links to measures. */ - $this->execute('DELETE FROM measures_measures WHERE anr_id NOT IN (SELECT id FROM anrs);'); - $voidMeasuresQuery = $this->query(' - SELECT id FROM measures_measures WHERE CONCAT(master_measure_id, anr_id) NOT IN - (SELECT CONCAT(uuid, anr_id) FROM measures) OR CONCAT(linked_measure_id, anr_id) - NOT IN (SELECT CONCAT(uuid, anr_id) FROM measures) - '); - $voidMeasuresIds = []; - foreach ($voidMeasuresQuery->fetchAll() as $voidMeasureData) { - $voidMeasuresIds[] = $voidMeasureData['id']; - } - $this->execute('DELETE FROM measures_measures WHERE id IN (' . implode(',', $voidMeasuresIds) . ');'); + /* Remove unlinked measures links with measures and update the new relation field. */ + $this->execute('UPDATE measures_measures mm INNER JOIN measures m ' + . 'ON mm.father_id = m.`uuid` AND mm.anr_id = m.anr_id SET master_measure_id = m.id;'); + $this->execute('UPDATE measures_measures mm INNER JOIN measures m ' + . 'ON mm.child_id = m.`uuid` AND mm.anr_id = m.anr_id SET linked_measure_id = m.id;'); + $this->execute('DELETE FROM measures_measures WHERE master_measure_id IS NULL OR linked_measure_id IS NULL;'); $this->table('measures_measures') - ->addForeignKey(['anr_id'], 'anrs', ['id'], ['delete' => 'CASCADE']) - ->addForeignKey( - ['master_measure_id', 'anr_id'], - 'measures', - ['uuid', 'anr_id'], - ['delete' => 'CASCADE', 'update' => 'RESTRICT'] - )->addForeignKey( - ['linked_measure_id', 'anr_id'], - 'measures', - ['uuid', 'anr_id'], - ['delete' => 'CASCADE', 'update' => 'RESTRICT'] - )->update(); - $this->table('measures')->addForeignKey(['anr_id'], 'anrs', ['id'], ['delete' => 'CASCADE'])->update(); + ->removeColumn('anr_id') + ->removeColumn('father_id') + ->removeColumn('child_id') + ->addForeignKey('master_measure_id', 'measures', 'id', ['delete' => 'CASCADE', 'update' => 'RESTRICT']) + ->addForeignKey('linked_measure_id', 'measures', 'id', ['delete' => 'CASCADE', 'update' => 'RESTRICT']) + ->addIndex(['master_measure_id', 'linked_measure_id'], ['unique' => true]) + ->update(); + /* Apply measures relation to soa. */ + $this->table('soa') + ->renameColumn('measure_id', 'measure_uuid') + ->dropForeignKey(['measure_uuid', 'anr_id']) + ->update(); + $this->table('soa') + ->addColumn('measure_id', 'integer', ['signed' => false, 'after' => MysqlAdapter::FIRST]) + ->update(); + $this->execute('UPDATE soa s INNER JOIN measures m ' + . 'ON s.measure_uuid = m.`uuid` AND s.anr_id = m.anr_id SET s.measure_id = m.id;'); + $this->table('soa') + ->addForeignKey('measure_id', 'measures', 'id', ['delete' => 'CASCADE', 'update' => 'RESTRICT']) + ->removeColumn('measure_uuid') + ->update(); + /* Apply measures relation to measures_amvs. */ + $this->table('measures_amvs') + ->removeColumn('anr_id2') + ->removeColumn('creator') + ->removeColumn('created_at') + ->removeColumn('updater') + ->removeColumn('updated_at') + ->renameColumn('measure_id', 'measure_uuid') + ->dropForeignKey(['measure_uuid', 'anr_id']) + ->update(); + $this->table('measures_amvs') + ->addColumn('measure_id', 'integer', ['signed' => false, 'after' => MysqlAdapter::FIRST]) + ->update(); + $this->execute('UPDATE measures_amvs ma INNER JOIN measures m ' + . 'ON ma.measure_uuid = m.`uuid` AND ma.anr_id = m.anr_id SET ma.measure_id = m.id;'); + $this->table('measures_amvs') + ->changePrimaryKey(['measure_id', 'amv_id', 'anr_id']) + ->addForeignKey('measure_id', 'measures', 'id', ['delete' => 'CASCADE', 'update' => 'RESTRICT']) + ->update(); + $this->table('measures_amvs')->removeColumn('measure_uuid')->update(); + /* Apply measures relation to measures_rolf_risks. */ + $this->table('measures_rolf_risks') + ->removeColumn('creator') + ->removeColumn('created_at') + ->removeColumn('updater') + ->removeColumn('updated_at') + ->renameColumn('measure_id', 'measure_uuid') + ->dropForeignKey(['measure_uuid', 'anr_id']) + ->update(); + $this->table('measures_rolf_risks') + ->addColumn('measure_id', 'integer', ['signed' => false, 'after' => 'id']) + ->update(); + $this->execute('UPDATE measures_rolf_risks mr INNER JOIN measures m ' + . 'ON mr.measure_uuid = m.`uuid` AND mr.anr_id = m.anr_id SET mr.measure_id = m.id;'); + $this->table('measures_rolf_risks') + ->addForeignKey('measure_id', 'measures', 'id', ['delete' => 'CASCADE', 'update' => 'RESTRICT']) + ->removeColumn('measure_uuid') + ->update(); /* Rename column of owner_id to risk_owner_id. */ $this->table('instances_risks')->renameColumn('owner_id', 'risk_owner_id')->update(); @@ -385,7 +435,7 @@ public function change() ' WHERE uuid = "' . $recSetData['uuid'] . '" AND anr_id = ' . (int)$recSetData['anr_id']); } /* Make anr_id and label unique. */ - $this->table('recommandations_sets')->addIndex(['anr_id', 'label'], ['unique' => true]); + $this->table('recommandations_sets')->addIndex(['anr_id', 'label'], ['unique' => true])->update(); $this->table('recommandations') ->removeColumn('token_import') @@ -401,10 +451,10 @@ public function change() ->update(); $this->table('objects_categories') - ->changeColumn('label1', 'string', ['null' => false, 'default' => '', 'limit' => 2048]) - ->changeColumn('label2', 'string', ['null' => false, 'default' => '', 'limit' => 2048]) - ->changeColumn('label3', 'string', ['null' => false, 'default' => '', 'limit' => 2048]) - ->changeColumn('label4', 'string', ['null' => false, 'default' => '', 'limit' => 2048]) + ->changeColumn('label1', 'string', ['default' => '', 'limit' => 2048]) + ->changeColumn('label2', 'string', ['default' => '', 'limit' => 2048]) + ->changeColumn('label3', 'string', ['default' => '', 'limit' => 2048]) + ->changeColumn('label4', 'string', ['default' => '', 'limit' => 2048]) ->update(); /* The unique relation is not correct as it should be possible to instantiate the same operational risk. */ @@ -445,7 +495,12 @@ public function change() ->removeColumn('description3') ->removeColumn('description4') ->update(); - + $this->table('recommandations_sets') + ->removeColumn('label1') + ->removeColumn('label2') + ->removeColumn('label3') + ->removeColumn('label4') + ->update(); $this->table('translations')->drop(); */ } diff --git a/src/Controller/ApiAnrMeasuresController.php b/src/Controller/ApiAnrMeasuresController.php index ab89451c..e7228e75 100755 --- a/src/Controller/ApiAnrMeasuresController.php +++ b/src/Controller/ApiAnrMeasuresController.php @@ -1,131 +1,110 @@ -params()->fromQuery('page'); - $limit = $this->params()->fromQuery('limit'); - $order = $this->params()->fromQuery('order'); - $filter = $this->params()->fromQuery('filter'); - $status = $this->params()->fromQuery('status'); - $referential = $this->params()->fromQuery('referential'); - $category = $this->params()->fromQuery('category'); - $anrId = (int)$this->params()->fromRoute('anrid'); - - if (empty($anrId)) { - throw new Exception('Anr id missing', 412); - } - - //make a join because composite key is not supported - $filterJoin[] = [ - 'as' => 'r', - 'rel' => 'referential', - ]; - - if (\is_null($status)) { - $status = 1; - } - $filterAnd = ($status === "all") ? null : ['status' => (int)$status]; - - $filterAnd['anr'] = $anrId; - - if ($referential) { - $filterAnd['r.anr'] = $anrId; - $filterAnd['r.uuid'] = $referential; - } - if ($category) { - $filterAnd['category'] = (int)$category; - } - - $service = $this->getService(); - - $entities = $service->getList($page, $limit, $order, $filter, $filterAnd); - if (\count($this->dependencies)) { - foreach ($entities as $key => $entity) { - $this->formatDependencies($entities[$key], $this->dependencies); - } - } + $formattedParams = $this->getFormattedInputParams($this->getMeasuresInputFormatter); return $this->getPreparedJsonResponse([ - 'count' => $service->getFilteredCount($filter, $filterAnd, $filterJoin), - $this->name => $entities, + 'count' => $this->anrMeasureService->getCount($formattedParams), + 'measures' => $this->anrMeasureService->getList($formattedParams), ]); } - public function update($id, $data) - { - unset($data['rolfRisks']); // not managed for the moement - $anrId = (int)$this->params()->fromRoute('anrid'); - $ids = ['anr' => $anrId, 'uuid' => $data['uuid']]; - $data['anr'] = $anrId; - $data ['referential'] = [ - 'anr' => $anrId, - 'uuid' => $data['referential'], - ]; //all the objects is send but we just need the uuid - $data['category'] ['referential'] = $data ['referential']; - unset($data['linkedMeasures']); - unset($data['amvs']); - - return parent::update($ids, $data); - } - - public function patch($id, $data) + /** + * @param string $id + */ + public function get($id) { - unset($data['measures']); + /** @var Anr $anr */ + $anr = $this->getRequest()->getAttribute('anr'); - return parent::patch($id, $data); + return $this->getPreparedJsonResponse($this->anrMeasureService->getMeasureData($anr, $id)); } public function create($data) { - unset($data['rolfRisks'], $data['linkedMeasures'], $data['amvs']); + $isBatchData = $this->isBatchData($data); + $this->validatePostParams($this->postMeasureDataInputValidator, $data, $isBatchData); + + /** @var Anr $anr */ + $anr = $this->getRequest()->getAttribute('anr'); - return parent::create($data); + if ($this->isBatchData($data)) { + return $this->getSuccessfulJsonResponse([ + 'id' => $this->anrMeasureService + ->createList($anr, $this->postMeasureDataInputValidator->getValidDataSets()), + ]); + } + + return $this->getSuccessfulJsonResponse([ + 'id' => $this->anrMeasureService + ->create($anr, $this->postMeasureDataInputValidator->getValidData())->getUuid(), + ]); } - public function get($id) + /** + * @param string $id + * @param array $data + */ + public function update($id, $data) { - $anrId = (int)$this->params()->fromRoute('anrid'); - $ids = ['uuid' => $id, 'anr' => $anrId]; + $this->validatePostParams($this->updateMeasureDataInputValidator->setExcludeFilter(['uuid' => $id]), $data); + + /** @var Anr $anr */ + $anr = $this->getRequest()->getAttribute('anr'); + + $this->anrMeasureService->update($anr, $id, $this->updateMeasureDataInputValidator->getValidData()); - return parent::get($ids); + return $this->getSuccessfulJsonResponse(); } + /** + * @param string $id + */ public function delete($id) { - $anrId = (int)$this->params()->fromRoute('anrid'); - $ids = ['uuid' => $id, 'anr' => $anrId]; + /** @var Anr $anr */ + $anr = $this->getRequest()->getAttribute('anr'); - return parent::delete($ids); + $this->anrMeasureService->delete($anr, $id); + + return $this->getSuccessfulJsonResponse(); } public function deleteList($data) { - $new_data = []; - $anrId = (int)$this->params()->fromRoute('anrid'); - foreach ($data as $uuid) { - $new_data[] = ['uuid' => $uuid, 'anr' => $anrId]; - } + /** @var Anr $anr */ + $anr = $this->getRequest()->getAttribute('anr'); + + $this->anrMeasureService->deleteList($anr, $data); - return parent::deleteList($new_data); + return $this->getSuccessfulJsonResponse(); } } diff --git a/src/Controller/ApiAnrMeasuresMeasuresController.php b/src/Controller/ApiAnrMeasuresLinksController.php similarity index 63% rename from src/Controller/ApiAnrMeasuresMeasuresController.php rename to src/Controller/ApiAnrMeasuresLinksController.php index 68d7321a..8bad158a 100644 --- a/src/Controller/ApiAnrMeasuresMeasuresController.php +++ b/src/Controller/ApiAnrMeasuresLinksController.php @@ -9,17 +9,17 @@ use Monarc\Core\Controller\Handler\AbstractRestfulControllerRequestHandler; use Monarc\Core\Controller\Handler\ControllerRequestResponseHandlerTrait; -use Monarc\Core\Validator\InputValidator\MeasureMeasure\PostMeasureMeasureDataInputValidator; +use Monarc\Core\Validator\InputValidator\MeasureLink\PostMeasureLinkDataInputValidator; use Monarc\FrontOffice\Entity\Anr; -use Monarc\FrontOffice\Service\AnrMeasureMeasureService; +use Monarc\FrontOffice\Service\AnrMeasureLinkService; -class ApiAnrMeasuresMeasuresController extends AbstractRestfulControllerRequestHandler +class ApiAnrMeasuresLinksController extends AbstractRestfulControllerRequestHandler { use ControllerRequestResponseHandlerTrait; public function __construct( - private AnrMeasureMeasureService $anrMeasureMeasureService, - private PostMeasureMeasureDataInputValidator $postMeasureMeasureDataInputValidator + private AnrMeasureLinkService $anrMeasureLinkService, + private PostMeasureLinkDataInputValidator $postMeasureLinkDataInputValidator ) { } @@ -27,7 +27,7 @@ public function getList() { /** @var Anr $anr */ $anr = $this->getRequest()->getAttribute('anr'); - $measuresLinksData = $this->anrMeasureMeasureService->getList($anr); + $measuresLinksData = $this->anrMeasureLinkService->getList($anr); return $this->getPreparedJsonResponse([ 'count' => \count($measuresLinksData), @@ -38,17 +38,17 @@ public function getList() public function create($data) { $isBatchData = $this->isBatchData($data); - $this->validatePostParams($this->postMeasureMeasureDataInputValidator, $data, $isBatchData); + $this->validatePostParams($this->postMeasureLinkDataInputValidator, $data, $isBatchData); /** @var Anr $anr */ $anr = $this->getRequest()->getAttribute('anr'); if ($this->isBatchData($data)) { - $this->anrMeasureMeasureService->createList( + $this->anrMeasureLinkService->createList( $anr, - $this->postMeasureMeasureDataInputValidator->getValidDataSets() + $this->postMeasureLinkDataInputValidator->getValidDataSets() ); } else { - $this->anrMeasureMeasureService->create($anr, $this->postMeasureMeasureDataInputValidator->getValidData()); + $this->anrMeasureLinkService->create($anr, $this->postMeasureLinkDataInputValidator->getValidData()); } return $this->getSuccessfulJsonResponse(); @@ -59,13 +59,13 @@ public function deleteList($data) $masterMeasureUuid = $this->params()->fromQuery('masterMeasureUuid'); $linkedMeasureUuid = $this->params()->fromQuery('linkedMeasureUuid'); $this->validatePostParams( - $this->postMeasureMeasureDataInputValidator, + $this->postMeasureLinkDataInputValidator, compact('masterMeasureUuid', 'linkedMeasureUuid') ); /** @var Anr $anr */ $anr = $this->getRequest()->getAttribute('anr'); - $this->anrMeasureMeasureService->delete($anr, $masterMeasureUuid, $linkedMeasureUuid); + $this->anrMeasureLinkService->delete($anr, $masterMeasureUuid, $linkedMeasureUuid); return $this->getSuccessfulJsonResponse(); } diff --git a/src/Controller/ApiCoreReferentialsController.php b/src/Controller/ApiCoreReferentialsController.php index 187e711f..3db0f2f8 100644 --- a/src/Controller/ApiCoreReferentialsController.php +++ b/src/Controller/ApiCoreReferentialsController.php @@ -9,11 +9,14 @@ use Laminas\Mvc\Controller\AbstractRestfulController; use Laminas\View\Model\JsonModel; +use Monarc\Core\Controller\Handler\ControllerRequestResponseHandlerTrait; use Monarc\Core\InputFormatter\Referential\GetReferentialInputFormatter; use Monarc\Core\Service\ReferentialService; class ApiCoreReferentialsController extends AbstractRestfulController { + use ControllerRequestResponseHandlerTrait; + public function __construct( private ReferentialService $referentialService, private GetReferentialInputFormatter $getReferentialInputFormatter diff --git a/src/Entity/Anr.php b/src/Entity/Anr.php index b9761f3e..2b046d08 100755 --- a/src/Entity/Anr.php +++ b/src/Entity/Anr.php @@ -59,14 +59,14 @@ class Anr extends AnrSuperClass /** * @var ArrayCollection|Snapshot[] * - * @ORM\OneToMany(targetEntity="Snapshot", mappedBy="anrReference", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="Snapshot", mappedBy="anrReference", cascade={"remove"}) */ protected $referencedSnapshots; /** * @var ArrayCollection|RecommendationSet[] * - * @ORM\OneToMany(targetEntity="RecommendationSet", mappedBy="anr", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="RecommendationSet", mappedBy="anr", cascade={"remove"}) */ protected $recommendationSets; @@ -129,14 +129,14 @@ class Anr extends AnrSuperClass /** * @var Referential[]|ArrayCollection * - * @ORM\OneToMany(targetEntity="Referential", mappedBy="anr", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="Referential", mappedBy="anr", cascade={"remove"}) */ protected $referentials; /** * @var UserAnr[]|ArrayCollection * - * @ORM\OneToMany(targetEntity="UserAnr", mappedBy="anr", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="UserAnr", mappedBy="anr", cascade={"remove"}) */ protected $usersAnrsPermissions; @@ -158,31 +158,31 @@ public function __construct() * * @return Anr */ - public static function constructFromObjectAndData(AnrSuperClass $anr, array $data): AnrSuperClass + public static function constructFromObjectAndData(AnrSuperClass $sourceAnr, array $data): AnrSuperClass { /** @var Anr $newAnr */ - $newAnr = parent::constructFromObject($anr); + $newAnr = parent::constructFromObject($sourceAnr); - if ($anr instanceof self) { + if ($sourceAnr instanceof self) { /* Duplication of a FrontOffice analysis, creation of a snapshot or restoring it. * For snapshots we use tha same label and description (label [SNAP] prefix will be added later). */ - $newAnr->setLabel($data['label' . $anr->getLanguage()] ?? $anr->getLabel()) - ->setDescription($data['description' . $anr->getLanguage()] ?? $anr->getDescription()) - ->setLanguage($anr->getLanguage()) - ->setLanguageCode($anr->getLanguageCode()) - ->setIsVisibleOnDashboard((int)$anr->isVisibleOnDashboard()) - ->setIsStatsCollected((int)$anr->isStatsCollected()) - ->setModelId($anr->getModelId()); - } elseif ($anr instanceof AnrCore) { + $newAnr->setLabel($data['label'] ?? $sourceAnr->getLabel()) + ->setDescription($data['description'] ?? $sourceAnr->getDescription()) + ->setLanguage($sourceAnr->getLanguage()) + ->setLanguageCode($sourceAnr->getLanguageCode()) + ->setIsVisibleOnDashboard((int)$sourceAnr->isVisibleOnDashboard()) + ->setIsStatsCollected((int)$sourceAnr->isStatsCollected()) + ->setModelId($sourceAnr->getModelId()); + } elseif ($sourceAnr instanceof AnrCore) { /* Creation of an analysis based on a model. */ $languageIndex = (int)($data['language'] ?? 1); - $newAnr->setLabel((string)$data['label' . $languageIndex]) - ->setDescription((string)$data['description' . $languageIndex]) + $newAnr->setLabel((string)$data['label']) + ->setDescription((string)$data['description']) ->setLanguage($languageIndex) ->setLanguageCode($data['languageCode'] ?? 'fr') - ->setModelId($anr->getModel()->getId()) - ->setCacheModelShowRolfBrut($anr->getModel()->showRolfBrut()) - ->setCacheModelAreScalesUpdatable($anr->getModel()->areScalesUpdatable()); + ->setModelId($sourceAnr->getModel()->getId()) + ->setCacheModelShowRolfBrut($sourceAnr->getModel()->showRolfBrut()) + ->setCacheModelAreScalesUpdatable($sourceAnr->getModel()->areScalesUpdatable()); } else { throw new \LogicException('The analysis can not be created due to the logic error.'); } diff --git a/src/Entity/Delivery.php b/src/Entity/Delivery.php index 535c9c44..0030adff 100755 --- a/src/Entity/Delivery.php +++ b/src/Entity/Delivery.php @@ -43,7 +43,7 @@ class Delivery /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/Instance.php b/src/Entity/Instance.php index bf5e8ae0..d6a4c439 100755 --- a/src/Entity/Instance.php +++ b/src/Entity/Instance.php @@ -26,7 +26,7 @@ class Instance extends InstanceSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false) * }) @@ -36,10 +36,10 @@ class Instance extends InstanceSuperClass /** * @var Asset * - * @ORM\ManyToOne(targetEntity="Asset", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Asset") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="asset_id", referencedColumnName="uuid", nullable=true), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) + * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) * }) */ protected $asset; @@ -47,7 +47,7 @@ class Instance extends InstanceSuperClass /** * @var MonarcObject * - * @ORM\ManyToOne(targetEntity="MonarcObject", cascade={"persist"}, fetch="EAGER") + * @ORM\ManyToOne(targetEntity="MonarcObject", fetch="EAGER") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="object_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) diff --git a/src/Entity/InstanceMetadata.php b/src/Entity/InstanceMetadata.php index 1a691048..29251678 100644 --- a/src/Entity/InstanceMetadata.php +++ b/src/Entity/InstanceMetadata.php @@ -35,7 +35,7 @@ class InstanceMetadata /** * @var Instance * - * @ORM\ManyToOne(targetEntity="Instance", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Instance") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="instance_id", referencedColumnName="id", nullable=false) * }) @@ -45,7 +45,7 @@ class InstanceMetadata /** * @var AnrInstanceMetadataField * - * @ORM\ManyToOne(targetEntity="AnrInstanceMetadataField", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="AnrInstanceMetadataField") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="metadata_id", referencedColumnName="id", nullable=false) * }) diff --git a/src/Entity/InstanceRisk.php b/src/Entity/InstanceRisk.php index ddde3d33..e10e22dc 100755 --- a/src/Entity/InstanceRisk.php +++ b/src/Entity/InstanceRisk.php @@ -28,7 +28,7 @@ class InstanceRisk extends InstanceRiskSuperClass /** * @var Amv * - * @ORM\ManyToOne(targetEntity="Amv", inversedBy="instanceRisks", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Amv", inversedBy="instanceRisks") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="amv_id", referencedColumnName="uuid", nullable=true, onDelete="SET NULL"), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -39,7 +39,7 @@ class InstanceRisk extends InstanceRiskSuperClass /** * @var Asset * - * @ORM\ManyToOne(targetEntity="Asset", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Asset") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="asset_id", referencedColumnName="uuid"), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") @@ -50,7 +50,7 @@ class InstanceRisk extends InstanceRiskSuperClass /** * @var Threat * - * @ORM\ManyToOne(targetEntity="Threat", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Threat") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="threat_id", referencedColumnName="uuid"), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") @@ -61,7 +61,7 @@ class InstanceRisk extends InstanceRiskSuperClass /** * @var Vulnerability * - * @ORM\ManyToOne(targetEntity="Vulnerability", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Vulnerability") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="vulnerability_id", referencedColumnName="uuid"), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") @@ -72,14 +72,14 @@ class InstanceRisk extends InstanceRiskSuperClass /** * @var ArrayCollection|RecommendationRisk[] * - * @ORM\OneToMany(targetEntity="RecommendationRisk", mappedBy="instanceRisk", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="RecommendationRisk", mappedBy="instanceRisk", cascade={"remove"}) */ protected $recommendationRisks; /** * @var InstanceRiskOwner|null * - * @ORM\ManyToOne(targetEntity="InstanceRiskOwner", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="InstanceRiskOwner") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="risk_owner_id", referencedColumnName="id", nullable=true) * }) @@ -98,12 +98,16 @@ public function __construct() $this->recommendationRisks = new ArrayCollection(); } - public static function constructFromObject(InstanceRiskSuperClass $instanceRisk): InstanceRiskSuperClass + public static function constructFromObject(InstanceRiskSuperClass $sourceInstanceRisk): InstanceRiskSuperClass { /** @var InstanceRisk $instanceRisk */ - $instanceRisk = parent::constructFromObject($instanceRisk); + $instanceRisk = parent::constructFromObject($sourceInstanceRisk); - return $instanceRisk->setContext($instanceRisk->getContext()); + if ($sourceInstanceRisk instanceof self) { + $instanceRisk->setContext($sourceInstanceRisk->getContext()); + } + + return $instanceRisk; } public static function constructFromObjectOfTheSameAnr(InstanceRisk $instanceRisk): static diff --git a/src/Entity/InstanceRiskOp.php b/src/Entity/InstanceRiskOp.php index afbeca6a..8e9bb8e4 100755 --- a/src/Entity/InstanceRiskOp.php +++ b/src/Entity/InstanceRiskOp.php @@ -22,20 +22,10 @@ */ class InstanceRiskOp extends InstanceRiskOpSuperClass { - /** - * @var Anr - * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) - * @ORM\JoinColumns({ - * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false) - * }) - */ - protected $anr; - /** * @var Object * - * @ORM\ManyToOne(targetEntity="MonarcObject", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="MonarcObject") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="object_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -46,7 +36,7 @@ class InstanceRiskOp extends InstanceRiskOpSuperClass /** * @var RolfRisk * - * @ORM\ManyToOne(targetEntity="RolfRisk", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="RolfRisk") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="rolf_risk_id", referencedColumnName="id", nullable=true) * }) @@ -56,14 +46,14 @@ class InstanceRiskOp extends InstanceRiskOpSuperClass /** * @var ArrayCollection|RecommendationRisk[] * - * @ORM\OneToMany(targetEntity="RecommendationRisk", mappedBy="instanceRiskOp", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="RecommendationRisk", mappedBy="instanceRiskOp", cascade={"remove"}) */ protected $recommendationRisks; /** * @var InstanceRiskOwner|null * - * @ORM\ManyToOne(targetEntity="InstanceRiskOwner", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="InstanceRiskOwner") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="risk_owner_id", referencedColumnName="id", nullable=true) * }) @@ -84,14 +74,17 @@ public function __construct() $this->recommendationRisks = new ArrayCollection(); } - /** - * @param InstanceRiskOp $operationalInstanceRisk - */ public static function constructFromObject( - InstanceRiskOpSuperClass $operationalInstanceRisk + InstanceRiskOpSuperClass $sourceOperationalInstanceRisk ): InstanceRiskOpSuperClass { - return parent::constructFromObject($operationalInstanceRisk) - ->setContext($operationalInstanceRisk->getContext()); + /** @var InstanceRiskOp $operationalInstanceRisk */ + $operationalInstanceRisk = parent::constructFromObject($sourceOperationalInstanceRisk); + + if ($sourceOperationalInstanceRisk instanceof self) { + $operationalInstanceRisk->setContext($sourceOperationalInstanceRisk->getContext()); + } + + return $operationalInstanceRisk; } public function getRecommendationRisks() diff --git a/src/Entity/InstanceRiskOwner.php b/src/Entity/InstanceRiskOwner.php index aca4bc63..606f2280 100644 --- a/src/Entity/InstanceRiskOwner.php +++ b/src/Entity/InstanceRiskOwner.php @@ -38,7 +38,7 @@ class InstanceRiskOwner /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", onDelete="CASCADE") * }) diff --git a/src/Entity/Interview.php b/src/Entity/Interview.php index 12a658e9..4e4df68a 100755 --- a/src/Entity/Interview.php +++ b/src/Entity/Interview.php @@ -34,7 +34,7 @@ class Interview extends AbstractEntity /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true, onDelete="CASCADE") * }) diff --git a/src/Entity/Measure.php b/src/Entity/Measure.php index 1d25c377..4d41bb51 100755 --- a/src/Entity/Measure.php +++ b/src/Entity/Measure.php @@ -14,18 +14,26 @@ /** * @ORM\Table(name="measures", indexes={ - * @ORM\Index(name="anr", columns={"anr_id"}), + * @ORM\Index(name="uuid_anr_id", columns={"uuid", "anr_id"}), * @ORM\Index(name="category", columns={"soacategory_id"}), * @ORM\Index(name="referential", columns={"referential_uuid"}) -* }) + * }) * @ORM\Entity */ class Measure extends MeasureSuperClass { /** - * @var UuidInterface|string + * @var int * + * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id + * @ORM\GeneratedValue(strategy="IDENTITY") + */ + protected $id; + + /** + * @var UuidInterface|string + * * @ORM\Column(name="uuid", type="uuid", nullable=false) */ protected $uuid; @@ -33,7 +41,6 @@ class Measure extends MeasureSuperClass /** * @var Anr * - * @ORM\Id * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({@ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false)}) */ @@ -44,12 +51,10 @@ class Measure extends MeasureSuperClass * * @ORM\ManyToMany(targetEntity="Amv", inversedBy="measures", fetch="EAGER") * @ORM\JoinTable(name="measures_amvs", - * joinColumns={@ORM\JoinColumn(name="measure_id", referencedColumnName="uuid"), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") - * }, + * joinColumns={@ORM\JoinColumn(name="measure_id", referencedColumnName="id")}, * inverseJoinColumns={ * @ORM\JoinColumn(name="amv_id", referencedColumnName="uuid"), - * @ORM\JoinColumn(name="anr_id2", referencedColumnName="anr_id") + * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") * }, * ) */ @@ -58,13 +63,10 @@ class Measure extends MeasureSuperClass /** * @var ArrayCollection|RolfRisk[] * - * @ORM\ManyToMany(targetEntity="RolfRisk", inversedBy="measures", cascade={"persist"}) + * @ORM\ManyToMany(targetEntity="RolfRisk", inversedBy="measures") * @ORM\JoinTable(name="measures_rolf_risks", * inverseJoinColumns={@ORM\JoinColumn(name="rolf_risk_id", referencedColumnName="id")}, - * joinColumns={ - * @ORM\JoinColumn(name="measure_id", referencedColumnName="uuid"), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") - * } + * joinColumns={@ORM\JoinColumn(name="measure_id", referencedColumnName="id")} * ) */ protected $rolfRisks; @@ -72,7 +74,7 @@ class Measure extends MeasureSuperClass /** * @var Referential * - * @ORM\ManyToOne(targetEntity="Referential", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Referential") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="referential_uuid", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -85,18 +87,17 @@ class Measure extends MeasureSuperClass * * @ORM\ManyToMany(targetEntity="Measure", inversedBy="measures", cascade={"persist"}) * @ORM\JoinTable(name="measures_measures", - * joinColumns={ - * @ORM\JoinColumn(name="master_measure_id", referencedColumnName="uuid"), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") - * }, - * inverseJoinColumns={ - * @ORM\JoinColumn(name="linked_measure_id", referencedColumnName="uuid"), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id") - * } + * joinColumns={@ORM\JoinColumn(name="master_measure_id", referencedColumnName="id")}, + * inverseJoinColumns={@ORM\JoinColumn(name="linked_measure_id", referencedColumnName="id")} * ) */ protected $linkedMeasures; + public function getId() + { + return $this->id; + } + public function getAnr(): Anr { return $this->anr; diff --git a/src/Entity/MeasureMeasure.php b/src/Entity/MeasureMeasure.php deleted file mode 100644 index 83138858..00000000 --- a/src/Entity/MeasureMeasure.php +++ /dev/null @@ -1,62 +0,0 @@ -anr; - } - - public function setAnr(Anr $anr): self - { - $this->anr = $anr; - - return $this; - } -} diff --git a/src/Entity/MonarcObject.php b/src/Entity/MonarcObject.php index d9704512..ccca584f 100644 --- a/src/Entity/MonarcObject.php +++ b/src/Entity/MonarcObject.php @@ -10,6 +10,7 @@ use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; use Monarc\Core\Entity\ObjectSuperClass; +use Ramsey\Uuid\UuidInterface; /** * @ORM\Table(name="objects", indexes={ @@ -22,6 +23,14 @@ */ class MonarcObject extends ObjectSuperClass { + /** + * @var UuidInterface|string + * + * @ORM\Column(name="uuid", type="uuid", nullable=false) + * @ORM\Id + */ + protected $uuid; + /** * @var Anr * @@ -36,7 +45,7 @@ class MonarcObject extends ObjectSuperClass /** * @var Asset * - * @ORM\ManyToOne(targetEntity="Asset", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Asset") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="asset_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) diff --git a/src/Entity/ObjectCategory.php b/src/Entity/ObjectCategory.php index 2e815e8d..87bee7a2 100755 --- a/src/Entity/ObjectCategory.php +++ b/src/Entity/ObjectCategory.php @@ -24,7 +24,7 @@ class ObjectCategory extends ObjectCategorySuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/ObjectObject.php b/src/Entity/ObjectObject.php index 56032eac..901a1126 100755 --- a/src/Entity/ObjectObject.php +++ b/src/Entity/ObjectObject.php @@ -23,7 +23,7 @@ class ObjectObject extends ObjectObjectSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/Question.php b/src/Entity/Question.php index 4160f90d..7dd1e363 100755 --- a/src/Entity/Question.php +++ b/src/Entity/Question.php @@ -19,7 +19,7 @@ class Question extends QuestionSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/QuestionChoice.php b/src/Entity/QuestionChoice.php index 30550cdc..7b54b47a 100755 --- a/src/Entity/QuestionChoice.php +++ b/src/Entity/QuestionChoice.php @@ -22,7 +22,7 @@ class QuestionChoice extends QuestionChoiceSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/Recommendation.php b/src/Entity/Recommendation.php index ef6cc7bf..4716221c 100755 --- a/src/Entity/Recommendation.php +++ b/src/Entity/Recommendation.php @@ -78,7 +78,7 @@ class Recommendation implements PositionedEntityInterface, PropertyStateEntityIn /** * @var ArrayCollection|RecommendationRisk[] * - * @ORM\OneToMany(targetEntity="RecommendationRisk", mappedBy="recommendation", cascade={"persist", "remove"}) + * @ORM\OneToMany(targetEntity="RecommendationRisk", mappedBy="recommendation", cascade={"remove"}) */ protected $recommendationRisks; diff --git a/src/Entity/RecommendationHistory.php b/src/Entity/RecommendationHistory.php index a91a166f..b0d153ce 100755 --- a/src/Entity/RecommendationHistory.php +++ b/src/Entity/RecommendationHistory.php @@ -34,7 +34,7 @@ class RecommendationHistory /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=False) * }) @@ -44,7 +44,7 @@ class RecommendationHistory /** * @var InstanceRisk * - * @ORM\ManyToOne(targetEntity="InstanceRisk", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="InstanceRisk") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="instance_risk_id", referencedColumnName="id", nullable=true) * }) @@ -54,7 +54,7 @@ class RecommendationHistory /** * @var InstanceRiskOp * - * @ORM\ManyToOne(targetEntity="InstanceRiskOp", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="InstanceRiskOp") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="instance_risk_op_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/RecommendationRisk.php b/src/Entity/RecommendationRisk.php index 32653065..cd6bd7ac 100755 --- a/src/Entity/RecommendationRisk.php +++ b/src/Entity/RecommendationRisk.php @@ -33,7 +33,7 @@ class RecommendationRisk /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false) * }) @@ -43,7 +43,7 @@ class RecommendationRisk /** * @var Recommendation * - * @ORM\ManyToOne(targetEntity="Recommendation", cascade={"persist"}, fetch="EAGER") + * @ORM\ManyToOne(targetEntity="Recommendation", fetch="EAGER") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="recommandation_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -54,7 +54,7 @@ class RecommendationRisk /** * @var InstanceRisk * - * @ORM\ManyToOne(targetEntity="InstanceRisk", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="InstanceRisk") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="instance_risk_id", referencedColumnName="id", nullable=true) * }) @@ -64,7 +64,7 @@ class RecommendationRisk /** * @var InstanceRiskOp * - * @ORM\ManyToOne(targetEntity="InstanceRiskOp", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="InstanceRiskOp") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="instance_risk_op_id", referencedColumnName="id", nullable=true) * }) @@ -74,7 +74,7 @@ class RecommendationRisk /** * @var Instance * - * @ORM\ManyToOne(targetEntity="Instance", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Instance") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="instance_id", referencedColumnName="id", nullable=true) * }) @@ -84,7 +84,7 @@ class RecommendationRisk /** * @var MonarcObject * - * @ORM\ManyToOne(targetEntity="MonarcObject", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="MonarcObject") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="object_global_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -95,7 +95,7 @@ class RecommendationRisk /** * @var Asset * - * @ORM\ManyToOne(targetEntity="Asset", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Asset") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="asset_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -106,7 +106,7 @@ class RecommendationRisk /** * @var Threat * - * @ORM\ManyToOne(targetEntity="Threat", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Threat") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="threat_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) @@ -117,7 +117,7 @@ class RecommendationRisk /** * @var Vulnerability * - * @ORM\ManyToOne(targetEntity="Vulnerability", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Vulnerability") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="vulnerability_id", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) diff --git a/src/Entity/RecommendationSet.php b/src/Entity/RecommendationSet.php index 81ae52e4..2cec6952 100644 --- a/src/Entity/RecommendationSet.php +++ b/src/Entity/RecommendationSet.php @@ -39,7 +39,7 @@ class RecommendationSet /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}, fetch="EAGER") + * @ORM\ManyToOne(targetEntity="Anr", fetch="EAGER") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false) * }) @@ -57,7 +57,7 @@ class RecommendationSet /** * @var Recommendation[]|ArrayCollection * - * @ORM\OneToMany(targetEntity="Recommendation", mappedBy="recommendationSet", cascade={"persist"}) + * @ORM\OneToMany(targetEntity="Recommendation", mappedBy="recommendationSet") */ protected $recommendations; diff --git a/src/Entity/Record.php b/src/Entity/Record.php index 50e0d079..bf9250f6 100644 --- a/src/Entity/Record.php +++ b/src/Entity/Record.php @@ -40,7 +40,7 @@ class Record extends AbstractEntity /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") * }) diff --git a/src/Entity/Referential.php b/src/Entity/Referential.php index dcc6f33f..298722ac 100644 --- a/src/Entity/Referential.php +++ b/src/Entity/Referential.php @@ -9,6 +9,7 @@ use Doctrine\ORM\Mapping as ORM; use Monarc\Core\Entity\ReferentialSuperClass; +use Ramsey\Uuid\UuidInterface; /** * @ORM\Table(name="referentials", indexes={@ORM\Index(name="anr", columns={"anr_id"})}) @@ -16,6 +17,14 @@ */ class Referential extends ReferentialSuperClass { + /** + * @var UuidInterface|string + * + * @ORM\Column(name="uuid", type="uuid", nullable=false) + * @ORM\Id + */ + protected $uuid; + /** * @var Anr * diff --git a/src/Entity/RolfRisk.php b/src/Entity/RolfRisk.php index ef658bcc..93b04655 100755 --- a/src/Entity/RolfRisk.php +++ b/src/Entity/RolfRisk.php @@ -23,7 +23,7 @@ class RolfRisk extends RolfRiskSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) @@ -33,13 +33,10 @@ class RolfRisk extends RolfRiskSuperClass /** * @var Measure[]|ArrayCollection * - * @ORM\ManyToMany(targetEntity="Measure", mappedBy="rolfRisks", cascade={"persist"}) + * @ORM\ManyToMany(targetEntity="Measure", mappedBy="rolfRisks") * @ORM\JoinTable(name="measures_rolf_risks", * joinColumns={@ORM\JoinColumn(name="rolf_risk_id", referencedColumnName="id")}, - * inverseJoinColumns={ - * @ORM\JoinColumn(name="measure_id", referencedColumnName="uuid"), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id"), - * } + * inverseJoinColumns={@ORM\JoinColumn(name="measure_id", referencedColumnName="id")} * ) */ protected $measures; diff --git a/src/Entity/RolfTag.php b/src/Entity/RolfTag.php index 939aa14a..bca3340c 100755 --- a/src/Entity/RolfTag.php +++ b/src/Entity/RolfTag.php @@ -22,7 +22,7 @@ class RolfTag extends RolfTagSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/Soa.php b/src/Entity/Soa.php index 529bccc5..90de08ed 100755 --- a/src/Entity/Soa.php +++ b/src/Entity/Soa.php @@ -31,7 +31,7 @@ class Soa extends AbstractEntity /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false) * }) @@ -41,11 +41,8 @@ class Soa extends AbstractEntity /** * @var Measure * - * @ORM\OneToOne(targetEntity="Measure", cascade={"persist"}) - * @ORM\JoinColumns({ - * @ORM\JoinColumn(name="measure_id", referencedColumnName="uuid", nullable=true), - * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true), - * }) + * @ORM\OneToOne(targetEntity="Measure") + * @ORM\JoinColumns({@ORM\JoinColumn(name="measure_id", referencedColumnName="id", nullable=true)}) */ protected $measure; @@ -122,7 +119,7 @@ class Soa extends AbstractEntity /** * @var SoaScaleComment * - * @ORM\ManyToOne(targetEntity="SoaScaleComment", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="SoaScaleComment") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="soa_scale_comment_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/SoaCategory.php b/src/Entity/SoaCategory.php index 9c8a45bd..6629e535 100755 --- a/src/Entity/SoaCategory.php +++ b/src/Entity/SoaCategory.php @@ -22,7 +22,7 @@ class SoaCategory extends SoaCategorySuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({@ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false)}) */ protected $anr; @@ -30,7 +30,7 @@ class SoaCategory extends SoaCategorySuperClass /** * @var Referential * - * @ORM\ManyToOne(targetEntity="Referential", inversedBy="categories", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Referential", inversedBy="categories") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="referential_uuid", referencedColumnName="uuid", nullable=true), * @ORM\JoinColumn(name="anr_id", referencedColumnName="anr_id", nullable=true) diff --git a/src/Entity/Theme.php b/src/Entity/Theme.php index dcb5cabb..5276d27f 100755 --- a/src/Entity/Theme.php +++ b/src/Entity/Theme.php @@ -21,7 +21,7 @@ class Theme extends ThemeSuperClass /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false) * }) diff --git a/src/Entity/User.php b/src/Entity/User.php index 9e3ea25f..b359637a 100755 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -21,7 +21,7 @@ class User extends UserSuperClass /** * @var Anr|null * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="current_anr_id", referencedColumnName="id", nullable=true) * }) diff --git a/src/Entity/UserAnr.php b/src/Entity/UserAnr.php index d58e9328..4cce32ee 100755 --- a/src/Entity/UserAnr.php +++ b/src/Entity/UserAnr.php @@ -34,7 +34,7 @@ class UserAnr /** * @var User * - * @ORM\ManyToOne(targetEntity="User", cascade={"persist"}, inversedBy="userAnrs") + * @ORM\ManyToOne(targetEntity="User", inversedBy="userAnrs") * @ORM\JoinColumn(nullable=false) */ protected $user; @@ -42,7 +42,7 @@ class UserAnr /** * @var Anr * - * @ORM\ManyToOne(targetEntity="Anr", cascade={"persist"}) + * @ORM\ManyToOne(targetEntity="Anr") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="anr_id", referencedColumnName="id", nullable=false, onDelete="CASCADE") * }) diff --git a/src/Export/Service/AnrExportService.php b/src/Export/Service/AnrExportService.php index 0f26b065..2be3aedf 100644 --- a/src/Export/Service/AnrExportService.php +++ b/src/Export/Service/AnrExportService.php @@ -77,29 +77,36 @@ public function export(Entity\Anr $anr, array $exportParams): array private function prepareExportData(Entity\Anr $anr, array $exportParams): array { $withEval = !empty($exportParams['assessments']); - $withControls = !empty($exportParams['controls']); - $withRecommendations = !empty($exportParams['recommendations']); - $withMethodSteps = !empty($exportParams['methodSteps']); - $withInterviews = !empty($exportParams['interviews']); - $withSoas = !empty($exportParams['soas']); - $withRecords = !empty($exportParams['records']); + $withControls = $withEval && !empty($exportParams['controls']); + $withRecommendations = $withEval && !empty($exportParams['recommendations']); + $withMethodSteps = $withEval && !empty($exportParams['methodSteps']); + $withInterviews = $withEval && !empty($exportParams['interviews']); + $withSoas = $withEval && !empty($exportParams['soas']); + $withRecords = $withEval && !empty($exportParams['records']); $withLibrary = !empty($exportParams['assetsLibrary']); + $withKnowledgeBase = !empty($exportParams['knowledgeBase']); return [ 'type' => 'anr', 'monarc_version' => $this->configService->getAppVersion()['appVersion'], - 'export_datetime' => (new \DateTime())->format('Y-m-d H:i:s'), - 'with_eval' => $withEval, - 'with_controls' => $withControls, - 'with_recommendations' => $withRecommendations, - 'with_library' => $withLibrary, - 'with_method_steps' => $withMethodSteps, - 'with_interviews' => $withInterviews, - 'with_soas' => $withSoas, - 'with_records' => $withRecords, - 'knowledgeBase' => $this->prepareKnowledgeBaseData($anr, $withEval, $withControls, $withRecommendations), - 'instances' => $this->prepareInstancesData($anr, !$withLibrary, $withEval, $withControls, $withRecommendations), + 'exportDatetime' => (new \DateTime())->format('Y-m-d H:i:s'), + 'withEval' => $withEval, + 'withControls' => $withControls, + 'withRecommendations' => $withRecommendations, + 'withMethodSteps' => $withMethodSteps, + 'withInterviews' => $withInterviews, + 'withSoas' => $withSoas, + 'withRecords' => $withRecords, + 'withLibrary' => $withLibrary, + 'withKnowledge' => $withKnowledgeBase, + 'languageCode' => $anr->getLanguageCode(), + 'languageIndex' => $anr->getLanguage(), + 'knowledgeBase' => $withKnowledgeBase + ? $this->prepareKnowledgeBaseData($anr, $withEval, $withControls, $withRecommendations) + : [], 'library' => $withLibrary ? $this->prepareLibraryData($anr) : [], + 'instances' => $this + ->prepareInstancesData($anr, !$withLibrary, $withEval, $withControls, $withRecommendations), 'anrInstanceMetadataFields' => $this->prepareAnrInstanceMetadataFieldsData($anr), 'scales' => $withEval ? $this->prepareScalesData($anr) : [], 'operationalRiskScales' => $withEval ? $this->prepareOperationalRiskScalesData($anr) : [], @@ -117,7 +124,7 @@ private function prepareAnrInstanceMetadataFieldsData(Entity\Anr $anr): array $result = []; /** @var Entity\AnrInstanceMetadataField $anrInstanceMetadata */ foreach ($this->anrInstanceMetadataFieldTable->findByAnr($anr) as $anrInstanceMetadata) { - $result[$anrInstanceMetadata->getId()] = ['label' => $anrInstanceMetadata->getLabel()]; + $result[] = ['label' => $anrInstanceMetadata->getLabel()]; } return $result; @@ -133,8 +140,8 @@ private function prepareKnowledgeBaseData( 'assets' => $this->prepareAssetsData($anr), 'threats' => $this->prepareThreatsData($anr, $withEval), 'vulnerabilities' => $this->prepareVulnerabilitiesData($anr), - 'informationRisks' => $this->prepareInformationRisksData($anr, $withEval), 'referentials' => $withControls ? $this->prepareReferentialsData($anr) : [], + 'informationRisks' => $this->prepareInformationRisksData($anr, $withEval), 'tags' => $this->prepareTagsData($anr), 'operationalRisks' => $this->prepareOperationalRisksData($anr), 'recommendationSets' => $withRecommendations ? $this->prepareRecommendationSetsData($anr) : [], @@ -147,7 +154,7 @@ private function prepareAssetsData(Entity\Anr $anr): array $languageIndex = $anr->getLanguage(); /** @var Entity\Asset $asset */ foreach ($this->assetTable->findByAnr($anr) as $asset) { - $result[$asset->getUuid()] = $this->prepareAssetData($asset, $languageIndex, false); + $result[] = $this->prepareAssetData($asset, $languageIndex); } return $result; @@ -159,7 +166,7 @@ private function prepareThreatsData(Entity\Anr $anr, bool $withEval): array $languageIndex = $anr->getLanguage(); /** @var Entity\Threat $threat */ foreach ($this->threatTable->findByAnr($anr) as $threat) { - $result[$threat->getUuid()] = $this->prepareThreatData($threat, $languageIndex, $withEval); + $result[] = $this->prepareThreatData($threat, $languageIndex, $withEval); } return $result; @@ -171,7 +178,7 @@ private function prepareVulnerabilitiesData(Entity\Anr $anr): array $languageIndex = $anr->getLanguage(); /** @var Entity\Vulnerability $vulnerability */ foreach ($this->vulnerabilityTable->findByAnr($anr) as $vulnerability) { - $result[$vulnerability->getUuid()] = $this->prepareVulnerabilityData($vulnerability, $languageIndex); + $result[] = $this->prepareVulnerabilityData($vulnerability, $languageIndex); } return $result; @@ -182,7 +189,7 @@ private function prepareInformationRisksData(Entity\Anr $anr, bool $withEval): a $result = []; /** @var Entity\Amv $amv */ foreach ($this->amvTable->findByAnr($anr) as $amv) { - $result[$amv->getUuid()] = $this->prepareInformationRiskData($amv); + $result[] = $this->prepareInformationRiskData($amv); } return $result; @@ -194,8 +201,8 @@ private function prepareTagsData(Entity\Anr $anr): array $languageIndex = $anr->getLanguage(); /** @var Entity\RolfTag $rolfTag */ foreach ($this->rolfTagTable->findByAnr($anr) as $rolfTag) { - $rolfTagId = $rolfTag->getId(); - $result[$rolfTagId] = [ + $result[] = [ + 'id' => $rolfTag->getId(), 'code' => $rolfTag->getCode(), 'label' => $rolfTag->getLabel($languageIndex), ]; @@ -210,7 +217,7 @@ private function prepareOperationalRisksData(Entity\Anr $anr): array $languageIndex = $anr->getLanguage(); /** @var Entity\RolfRisk $rolfRisk */ foreach ($this->rolfRiskTable->findByAnr($anr) as $rolfRisk) { - $result[$rolfRisk->getId()] = $this->prepareOperationalRiskData($rolfRisk, $languageIndex); + $result[] = $this->prepareOperationalRiskData($rolfRisk, $languageIndex); } return $result; @@ -225,12 +232,11 @@ private function prepareReferentialsData(Entity\Anr $anr): array $measuresData = []; foreach ($referential->getMeasures() as $measure) { /* Include linked measures to the prepared result. */ - $measuresData[$measure->getUuid()] = $this->prepareMeasureData($measure, $languageIndex, true); + $measuresData[] = $this->prepareMeasureData($measure, $languageIndex, true); } - $referentialUuid = $referential->getUuid(); - $result[$referentialUuid] = [ - 'uuid' => $referentialUuid, + $result[] = [ + 'uuid' => $referential->getUuid(), 'label' => $referential->getLabel($languageIndex), 'measures' => $measuresData, ]; @@ -246,10 +252,11 @@ private function prepareRecommendationSetsData(Entity\Anr $anr): array foreach ($this->recommendationSetTable->findByAnr($anr) as $recommendationSet) { $recommendationsData = []; foreach ($recommendationSet->getRecommendations() as $recommendation) { - $recommendationsData[$recommendation->getUuid()] = $this->prepareRecommendationData($recommendation); + $recommendationsData[] = $this->prepareRecommendationData($recommendation, false); } if (!empty($recommendationsData)) { - $result[$recommendationSet->getUuid()] = [ + $result[] = [ + 'uuid' => $recommendationSet->getUuid(), 'label' => $recommendationSet->getLabel(), 'recommendations' => $recommendationsData, ]; @@ -271,7 +278,7 @@ private function prepareCategoriesAndObjects(Entity\Anr $anr): array $result = []; $languageIndex = $anr->getLanguage(); foreach ($this->objectCategoryTable->findRootCategoriesByAnrOrderedByPosition($anr) as $objectCategory) { - $result[$objectCategory->getId()] = $this->prepareCategoryData($objectCategory, $languageIndex, true); + $result[] = $this->prepareCategoryData($objectCategory, $languageIndex, true); } return $result; @@ -281,7 +288,7 @@ private function prepareChildrenCategoriesData(Entity\ObjectCategory $objectCate { $result = []; foreach ($objectCategory->getChildren() as $childObjectCategory) { - $result[$childObjectCategory->getId()] = $this + $result[] = $this ->prepareCategoryData($childObjectCategory, $languageIndex, false); } @@ -292,7 +299,7 @@ private function prepareObjectsDataOfCategory(Entity\ObjectCategory $objectCateg { $result = []; foreach ($objectCategory->getObjects() as $object) { - $result[$object->getUuid()] = $this->prepareObjectData($object, $languageIndex, false); + $result[] = $this->prepareObjectData($object, $languageIndex, false); } return $result; @@ -319,7 +326,7 @@ private function prepareInstancesData( $languageIndex = $anr->getLanguage(); /** @var Entity\Instance $instance */ foreach ($this->instanceTable->findRootInstancesByAnrAndOrderByPosition($anr) as $instance) { - $result[$instance->getId()] = $this->prepareInstanceData( + $result[] = $this->prepareInstanceData( $instance, $languageIndex, $includeObjectDataInTheResult, @@ -362,7 +369,7 @@ private function prepareSoaScaleCommentsData(Entity\Anr $anr): array /** @var Entity\SoaScaleComment $soaScaleComment */ foreach ($this->soaScaleCommentTable->findByAnrOrderByIndex($anr) as $soaScaleComment) { if (!$soaScaleComment->isHidden()) { - $result[$soaScaleComment->getId()] = [ + $result[] = [ 'scaleIndex' => $soaScaleComment->getScaleIndex(), 'isHidden' => $soaScaleComment->isHidden(), 'colour' => $soaScaleComment->getColour(), @@ -500,8 +507,7 @@ private function prepareGdprRecordsData(Entity\Anr $anr): array $result = []; $filename = ''; foreach ($this->recordTable->findByAnr($anr) as $record) { - $recordId = $record->getId(); - $result[$recordId] = $this->anrRecordService->generateExportArray($recordId, $filename); + $result[] = $this->anrRecordService->generateExportArray($record->getId(), $filename); } return $result; diff --git a/src/Export/Service/InstanceExportService.php b/src/Export/Service/InstanceExportService.php index 55b80586..09eb3137 100644 --- a/src/Export/Service/InstanceExportService.php +++ b/src/Export/Service/InstanceExportService.php @@ -59,8 +59,8 @@ public function export(Entity\Anr $anr, array $exportParams): array private function prepareExportData(Entity\Instance $instance, array $exportParams): array { $withEval = !empty($exportParams['assessments']); - $withControls = !empty($exportParams['controls']); - $withRecommendations = !empty($exportParams['recommendations']); + $withControls = $withEval && !empty($exportParams['controls']); + $withRecommendations = $withEval && !empty($exportParams['recommendations']); /** @var Entity\Anr $anr */ $anr = $instance->getAnr(); $languageIndex = $anr->getLanguage(); @@ -69,6 +69,8 @@ private function prepareExportData(Entity\Instance $instance, array $exportParam 'type' => 'instance', 'monarc_version' => $this->configService->getAppVersion()['appVersion'], 'export_datetime' => (new \DateTime())->format('Y-m-d H:i:s'), + 'languageCode' => $anr->getLanguageCode(), + 'languageIndex' => $anr->getLanguage(), 'with_eval' => $withEval, 'with_controls' => $withControls, 'with_recommendations' => $withRecommendations, diff --git a/src/Export/Service/Traits/InformationInstanceRiskExportTrait.php b/src/Export/Service/Traits/InformationInstanceRiskExportTrait.php index 3ebf314f..787677e0 100644 --- a/src/Export/Service/Traits/InformationInstanceRiskExportTrait.php +++ b/src/Export/Service/Traits/InformationInstanceRiskExportTrait.php @@ -37,13 +37,14 @@ private function prepareInformationInstanceRiskData( if ($withRecommendations) { foreach ($instanceRisk->getRecommendationRisks() as $recommendationRisk) { $recommendation = $recommendationRisk->getRecommendation(); - $recommendationsData[$recommendation->getUuid()] = array_merge( + $recommendationsData[] = array_merge( $this->prepareRecommendationData($recommendation), ['commentAfter' => $recommendationRisk->getCommentAfter()]); } } return [ + 'id' => $instanceRisk->getId(), 'informationRisk' => $informationRiskData, 'threat' => $this->prepareThreatData($threat, $languageIndex, $withEval), 'vulnerability' => $this->prepareVulnerabilityData($vulnerability, $languageIndex), @@ -55,8 +56,8 @@ private function prepareInformationInstanceRiskData( 'vulnerabilityRate' => $withEval ? $instanceRisk->getVulnerabilityRate() : -1, 'kindOfMeasure' => $withEval ? $instanceRisk->getKindOfMeasure() : InstanceRiskSuperClass::KIND_NOT_SET, 'reductionAmount' => $withEval ? $instanceRisk->getReductionAmount() : 0, - 'comment' => $withEval && $withControls ? $instanceRisk->getComment() : '', - 'commentAfter' => $withEval && $withControls ? $instanceRisk->getCommentAfter() : '', + 'comment' => $withControls ? $instanceRisk->getComment() : '', + 'commentAfter' => $withControls ? $instanceRisk->getCommentAfter() : '', 'cacheMaxRisk' => $withEval ? $instanceRisk->getCacheMaxRisk() : -1, 'cacheTargetedRisk' => $withEval ? $instanceRisk->getCacheTargetedRisk() : -1, 'context' => $withEval ? $instanceRisk->getContext() : '', diff --git a/src/Export/Service/Traits/InformationRiskExportTrait.php b/src/Export/Service/Traits/InformationRiskExportTrait.php index 70f6ecc5..fa39c9bb 100644 --- a/src/Export/Service/Traits/InformationRiskExportTrait.php +++ b/src/Export/Service/Traits/InformationRiskExportTrait.php @@ -40,13 +40,13 @@ trait InformationRiskExportTrait $measuresData = []; if ($withControls) { foreach ($amv->getMeasures() as $measure) { - $measuresData[$measure->getUuid()] = $this->prepareMeasureData($measure, $languageIndex); + $measuresData[] = $this->prepareMeasureData($measure, $languageIndex); } } return [ 'uuid' => $amv->getUuid(), - 'asset' => $this->prepareAssetData($asset, $languageIndex, false), + 'asset' => $this->prepareAssetData($asset, $languageIndex), 'threat' => $this->prepareThreatData($threat, $languageIndex, $withEval), 'vulnerability' => $this->prepareVulnerabilityData($vulnerability, $languageIndex), 'measures' => $measuresData, diff --git a/src/Export/Service/Traits/InstanceConsequenceExportTrait.php b/src/Export/Service/Traits/InstanceConsequenceExportTrait.php index a1c4c047..942ed9be 100644 --- a/src/Export/Service/Traits/InstanceConsequenceExportTrait.php +++ b/src/Export/Service/Traits/InstanceConsequenceExportTrait.php @@ -15,6 +15,7 @@ trait InstanceConsequenceExportTrait use ScaleImpactTypeExportTrait; #[ArrayShape([ + 'id' => "int", 'confidentiality' => "int", 'integrity' => "int", 'availability' => "int", @@ -28,6 +29,7 @@ trait InstanceConsequenceExportTrait $scaleImpactType = $instanceConsequence->getScaleImpactType(); return [ + 'id' => $instanceConsequence->getId(), 'confidentiality' => $instanceConsequence->getConfidentiality(), 'integrity' => $instanceConsequence->getIntegrity(), 'availability' => $instanceConsequence->getAvailability(), diff --git a/src/Export/Service/Traits/InstanceExportTrait.php b/src/Export/Service/Traits/InstanceExportTrait.php index 43e5fd5e..34e9b7c4 100644 --- a/src/Export/Service/Traits/InstanceExportTrait.php +++ b/src/Export/Service/Traits/InstanceExportTrait.php @@ -44,7 +44,7 @@ private function prepareInstanceData( 'confidentialityInherited' => $withEval ? (int)$instance->isConfidentialityInherited() : 1, 'integrityInherited' => $withEval ? (int)$instance->isIntegrityInherited() : 1, 'availabilityInherited' => $withEval ? (int)$instance->isAvailabilityInherited() : 1, - 'asset' => $this->prepareAssetData($asset, $languageIndex, false), + 'asset' => $this->prepareAssetData($asset, $languageIndex), /* For Anr and Instance export instanceRisks are added to the instance, so not needed in asset. */ 'object' => $includeCompleteObjectData ? $this->prepareObjectData($object, $languageIndex, false) @@ -82,7 +82,7 @@ private function prepareInstanceMetadataData(Entity\Instance $instance): array { $result = []; foreach ($instance->getInstanceMetadata() as $instanceMetadata) { - $result[$instanceMetadata->getId()] = [ + $result[] = [ 'anrInstanceMetadataField' => [ 'id' => $instanceMetadata->getAnrInstanceMetadataField()->getId(), 'label' => $instanceMetadata->getAnrInstanceMetadataField()->getLabel(), @@ -106,7 +106,7 @@ private function prepareChildrenInstancesData( $result = []; /** @var Entity\Instance $childInstance */ foreach ($instance->getChildren() as $childInstance) { - $result[$childInstance->getId()] = $this->prepareInstanceData( + $result[] = $this->prepareInstanceData( $childInstance, $languageIndex, $includeCompleteObjectData, @@ -131,7 +131,7 @@ private function prepareInformationInstanceRisksData( $result = []; /** @var Entity\InstanceRisk $operationalInstanceRisk */ foreach ($instance->getInstanceRisks() as $instanceRisk) { - $result[$instanceRisk->getId()] = $this->prepareInformationInstanceRiskData( + $result[] = $this->prepareInformationInstanceRiskData( $instanceRisk, $languageIndex, $includeCompleteInformationRisksData, @@ -154,7 +154,7 @@ private function prepareOperationalInstanceRisksData( $result = []; /** @var Entity\InstanceRiskOp $operationalInstanceRisk */ foreach ($instance->getOperationalInstanceRisks() as $operationalInstanceRisk) { - $result[$operationalInstanceRisk->getId()] = $this->prepareOperationalInstanceRiskData( + $result[] = $this->prepareOperationalInstanceRiskData( $operationalInstanceRisk, $languageIndex, $withEval, @@ -171,7 +171,7 @@ private function prepareInstanceConsequencesData(Entity\Instance $instance, int $result = []; /** @var Entity\InstanceConsequence $instanceConsequence */ foreach ($instance->getInstanceConsequences() as $instanceConsequence) { - $result[$instanceConsequence->getId()] = $this->prepareInstanceConsequenceData( + $result[] = $this->prepareInstanceConsequenceData( $instanceConsequence, $languageIndex ); diff --git a/src/Export/Service/Traits/MeasureExportTrait.php b/src/Export/Service/Traits/MeasureExportTrait.php index f9c2658b..9920e31d 100644 --- a/src/Export/Service/Traits/MeasureExportTrait.php +++ b/src/Export/Service/Traits/MeasureExportTrait.php @@ -18,8 +18,11 @@ trait MeasureExportTrait 'label' => "string", 'referential' => "array", 'category' => "array|null" - ])] private function prepareMeasureData(Entity\Measure $measure, int $languageIndex, bool $includeLinks = false): array - { + ])] private function prepareMeasureData( + Entity\Measure $measure, + int $languageIndex, + bool $includeLinks = false + ): array { $result = [ 'uuid' => $measure->getUuid(), 'code' => $measure->getCode(), @@ -28,19 +31,17 @@ trait MeasureExportTrait 'uuid' => $measure->getReferential()->getUuid(), 'label' => $measure->getReferential()->getLabel($languageIndex) ], - 'category' => $measure->getCategory() !== null ? [ - 'id' => $measure->getCategory()->getId(), - 'status' => $measure->getCategory()->getStatus(), + 'category' => $measure->getCategory() === null ? null : [ 'label' => $measure->getCategory()->getLabel($languageIndex), - ] : null, + ], ]; if ($includeLinks) { foreach ($measure->getLinkedMeasures() as $linkedMeasure) { - $result['linkedMeasures'][$linkedMeasure->getUuid()] = $this->prepareMeasureData( - $linkedMeasure, - $languageIndex - ); + $result['linkedMeasures'][] = [ + 'uuid' => $linkedMeasure->getUuid(), + 'referential' => ['uuid' => $linkedMeasure->getReferential()->getUuid()], + ]; } } diff --git a/src/Export/Service/Traits/ObjectExportTrait.php b/src/Export/Service/Traits/ObjectExportTrait.php index 3ca17c2a..cc3764d4 100644 --- a/src/Export/Service/Traits/ObjectExportTrait.php +++ b/src/Export/Service/Traits/ObjectExportTrait.php @@ -29,7 +29,7 @@ private function prepareObjectData( if ($addAmvsToAssetData) { $assetData['informationRisks'] = []; foreach ($asset->getAmvs() as $amv) { - $assetData['informationRisks'][$amv->getUuid()] = $this->prepareInformationRiskData($amv); + $assetData['informationRisks'][] = $this->prepareInformationRiskData($amv); } } @@ -56,20 +56,15 @@ private function prepareObjectData( private function prepareCategoryAndParentsData(Entity\ObjectCategory $objectCategory): array { - $objectCategoryData[$objectCategory->getId()] = [ + /** @var ?Entity\ObjectCategory $parentCategory */ + $parentCategory = $objectCategory->getParent(); + + return [ + 'id' => $objectCategory->getId(), 'label' => $objectCategory->getLabel($objectCategory->getAnr()->getLanguage()), 'position' => $objectCategory->getPosition(), - 'parent' => null, + 'parent' => $parentCategory !== null ? $this->prepareCategoryAndParentsData($parentCategory) : null, ]; - if ($objectCategory->getParent() !== null) { - /** @var Entity\ObjectCategory $parentCategory */ - $parentCategory = $objectCategory->getParent(); - $objectCategoryData[$objectCategory->getId()]['parent'] = $this->prepareCategoryAndParentsData( - $parentCategory - ); - } - - return $objectCategoryData; } private function prepareChildrenObjectsData( @@ -81,7 +76,7 @@ private function prepareChildrenObjectsData( foreach ($object->getChildrenLinks() as $childLink) { /** @var Entity\MonarcObject $childObject */ $childObject = $childLink->getChild(); - $result[$childObject->getUuid()] = $this + $result[] = $this ->prepareObjectData($childObject, $languageIndex, $addAmvsToAssetData); } @@ -93,7 +88,7 @@ private function prepareRolfRisksData(Entity\RolfTag $rolfTag): array $rolfRisksData = []; $languageIndex = $rolfTag->getAnr()->getLanguage(); foreach ($rolfTag->getRisks() as $rolfRisk) { - $rolfRisksData[$rolfRisk->getId()] = $this->prepareOperationalRiskData($rolfRisk, $languageIndex); + $rolfRisksData[] = $this->prepareOperationalRiskData($rolfRisk, $languageIndex); } return $rolfRisksData; diff --git a/src/Export/Service/Traits/OperationalInstanceRiskExportTrait.php b/src/Export/Service/Traits/OperationalInstanceRiskExportTrait.php index 2c1e88df..e5b53c1e 100644 --- a/src/Export/Service/Traits/OperationalInstanceRiskExportTrait.php +++ b/src/Export/Service/Traits/OperationalInstanceRiskExportTrait.php @@ -27,7 +27,7 @@ private function prepareOperationalInstanceRiskData( if ($withRecommendations) { foreach ($operationalInstanceRisk->getRecommendationRisks() as $recommendationRisk) { $recommendation = $recommendationRisk->getRecommendation(); - $recommendationsData[$recommendation->getUuid()] = array_merge( + $recommendationsData[] = array_merge( $this->prepareRecommendationData($recommendation), ['commentAfter' => $recommendationRisk->getCommentAfter()] ); @@ -47,6 +47,7 @@ private function prepareOperationalInstanceRiskData( } return [ + 'id' => $operationalInstanceRisk->getId(), 'operationalRisk' => $operationalRisk !== null ? $this->prepareOperationalRiskData($operationalRisk, $languageIndex, $withControls) : null, @@ -61,7 +62,7 @@ private function prepareOperationalInstanceRiskData( 'kindOfMeasure' => $withEval ? $operationalInstanceRisk->getKindOfMeasure() : InstanceRiskOpSuperClass::KIND_NOT_SET, - 'comment' => $withEval && $withControls ? $operationalInstanceRisk->getComment() : '', + 'comment' => $withControls ? $operationalInstanceRisk->getComment() : '', 'mitigation' => $withEval ? $operationalInstanceRisk->getMitigation() : '', 'specific' => $operationalInstanceRisk->getSpecific(), 'context' => $withEval ? $operationalInstanceRisk->getContext() : '', diff --git a/src/Export/Service/Traits/OperationalRiskExportTrait.php b/src/Export/Service/Traits/OperationalRiskExportTrait.php index b0c079e0..174941e7 100644 --- a/src/Export/Service/Traits/OperationalRiskExportTrait.php +++ b/src/Export/Service/Traits/OperationalRiskExportTrait.php @@ -19,6 +19,7 @@ trait OperationalRiskExportTrait 'code' => "string", 'label' => "string", 'description' => "string", + 'rolfTags' => "array", 'measures' => "array" ])] private function prepareOperationalRiskData( Entity\RolfRisk $rolfRisk, @@ -28,15 +29,23 @@ trait OperationalRiskExportTrait $measuresData = []; if ($withControls) { foreach ($rolfRisk->getMeasures() as $measure) { - $measuresData[$measure->getUuid()] = $this->prepareMeasureData($measure, $languageIndex); + $measuresData[] = $this->prepareMeasureData($measure, $languageIndex); } } + $rolfTagsData = []; + foreach ($rolfRisk->getTags() as $rolfTag) { + $rolfTagsData[] = [ + 'code' => $rolfTag->getCode(), + 'label' => $rolfTag->getLabel($languageIndex), + ]; + } return [ 'id' => $rolfRisk->getId(), 'code' => $rolfRisk->getCode(), 'label' => $rolfRisk->getLabel($languageIndex), 'description' => $rolfRisk->getDescription($languageIndex), + 'rolfTags' => $rolfTagsData, 'measures' => $measuresData, ]; } diff --git a/src/Export/Service/Traits/OperationalRiskScaleExportTrait.php b/src/Export/Service/Traits/OperationalRiskScaleExportTrait.php index 49ccaeda..4c1f8945 100644 --- a/src/Export/Service/Traits/OperationalRiskScaleExportTrait.php +++ b/src/Export/Service/Traits/OperationalRiskScaleExportTrait.php @@ -25,12 +25,13 @@ trait OperationalRiskScaleExportTrait foreach ($operationalRiskScale->getOperationalRiskScaleTypes() as $scaleType) { $scaleTypeComments = []; foreach ($scaleType->getOperationalRiskScaleComments() as $scaleTypeComment) { - $scaleTypeComments[$scaleTypeComment->getId()] = $this->prepareOperationalRiskScaleCommentData( + $scaleTypeComments[] = $this->prepareOperationalRiskScaleCommentData( $scaleTypeComment ); } - $scaleTypes[$scaleType->getId()] = [ + $scaleTypes[] = [ + 'id' => $scaleType->getId(), 'label' => $scaleType->getLabel(), 'isHidden' => $scaleType->isHidden(), 'operationalRiskScaleComments' => $scaleTypeComments, @@ -58,6 +59,7 @@ trait OperationalRiskScaleExportTrait private function prepareOperationalRiskScaleCommentData(Entity\OperationalRiskScaleComment $scaleComment): array { return [ + 'id' => $scaleComment->getId(), 'scaleIndex' => $scaleComment->getScaleIndex(), 'scaleValue' => $scaleComment->getScaleValue(), 'isHidden' => $scaleComment->isHidden(), diff --git a/src/Export/Service/Traits/RecommendationExportTrait.php b/src/Export/Service/Traits/RecommendationExportTrait.php index 581ebfaa..4a62fc41 100644 --- a/src/Export/Service/Traits/RecommendationExportTrait.php +++ b/src/Export/Service/Traits/RecommendationExportTrait.php @@ -11,14 +11,12 @@ trait RecommendationExportTrait { - private function prepareRecommendationData(Entity\Recommendation $recommendation): array - { - return [ + private function prepareRecommendationData( + Entity\Recommendation $recommendation, + bool $includeRecommendationSetData = true + ): array { + $result = [ 'uuid' => $recommendation->getUuid(), - 'recommendationSet' => [ - 'uuid' => $recommendation->getRecommendationSet()->getUuid(), - 'lable' => $recommendation->getRecommendationSet()->getLabel(), - ], 'code' => $recommendation->getCode(), 'description' => $recommendation->getDescription(), 'importance' => $recommendation->getImportance(), @@ -26,7 +24,15 @@ private function prepareRecommendationData(Entity\Recommendation $recommendation 'status' => $recommendation->getStatus(), 'responsible' => $recommendation->getResponsible(), 'duedate' => $recommendation->getDueDate()?->format('Y-m-d'), - 'counterTreated' => $recommendation->getCode() + 'counterTreated' => $recommendation->getCode(), ]; + if ($includeRecommendationSetData) { + $result['recommendationSet'] = [ + 'uuid' => $recommendation->getRecommendationSet()->getUuid(), + 'label' => $recommendation->getRecommendationSet()->getLabel(), + ]; + } + + return $result; } } diff --git a/src/Export/Service/Traits/ScaleExportTrait.php b/src/Export/Service/Traits/ScaleExportTrait.php index 3878614a..e2ba4268 100644 --- a/src/Export/Service/Traits/ScaleExportTrait.php +++ b/src/Export/Service/Traits/ScaleExportTrait.php @@ -19,13 +19,27 @@ trait ScaleExportTrait 'max' => "int", 'type' => "int", 'scaleImpactTypes' => "array", + 'scaleComments' => "array", ])] private function prepareScaleData(Entity\Scale $scale, int $languageIndex): array { + /* Prepare comments that are not linked to scaleTypes and directly linked to the scale. */ + $scaleCommentsData = []; + foreach ($scale->getScaleComments() as $scaleComment) { + if ($scaleComment->getScaleImpactType() === null) { + $scaleCommentsData[] = [ + 'scaleIndex' => $scaleComment->getScaleIndex(), + 'scaleValue' => $scaleComment->getScaleValue(), + 'comment' => $scaleComment->getComment($languageIndex), + ]; + } + } + return [ 'min' => $scale->getMin(), 'max' => $scale->getMax(), 'type' => $scale->getType(), 'scaleImpactTypes' => $this->prepareScaleImpactTypesData($scale, $languageIndex), + 'scaleComments' => $scaleCommentsData, ]; } @@ -33,8 +47,7 @@ private function prepareScaleImpactTypesData(Entity\Scale $scale, int $languageI { $result = []; foreach ($scale->getScaleImpactTypes() as $scaleImpactType) { - $result[$scaleImpactType->getId()] = $this - ->prepareScaleImpactTypeAndCommentsData($scaleImpactType, $languageIndex, true, false); + $result[] = $this->prepareScaleImpactTypeAndCommentsData($scaleImpactType, $languageIndex, true, false); } return $result; diff --git a/src/Export/Service/Traits/ScaleImpactTypeExportTrait.php b/src/Export/Service/Traits/ScaleImpactTypeExportTrait.php index e3cc4f12..2b98eae5 100644 --- a/src/Export/Service/Traits/ScaleImpactTypeExportTrait.php +++ b/src/Export/Service/Traits/ScaleImpactTypeExportTrait.php @@ -29,7 +29,7 @@ trait ScaleImpactTypeExportTrait $scaleComments = []; if ($includeComments) { foreach ($scaleImpactType->getScaleComments() as $scaleComment) { - $scaleComments[$scaleComment->getId()] = [ + $scaleComments[] = [ 'scaleIndex' => $scaleComment->getScaleIndex(), 'scaleValue' => $scaleComment->getScaleValue(), 'comment' => $scaleComment->getComment($languageIndex), diff --git a/src/Import/Helper/ImportCacheHelper.php b/src/Import/Helper/ImportCacheHelper.php index 44fb45ec..e519ff29 100644 --- a/src/Import/Helper/ImportCacheHelper.php +++ b/src/Import/Helper/ImportCacheHelper.php @@ -7,43 +7,25 @@ namespace Monarc\FrontOffice\Import\Helper; -use Monarc\FrontOffice\Entity; -use Monarc\FrontOffice\Table; - class ImportCacheHelper { private array $arrayCache = []; - public function __construct(private Table\ThemeTable $themeTable, private Table\SoaCategoryTable $soaCategoryTable) + public function isCacheKeySet(string $cacheKey): bool { + return isset($this->arrayCache[$cacheKey]); } - public function prepareThemesCacheData(Entity\Anr $anr): void + public function isItemInArrayCache(string $cacheKey, $itemKey): bool { - if (!isset($this->arrayCache['themes_by_labels'])) { - /** @var Entity\Theme $theme */ - foreach ($this->themeTable->findByAnr($anr) as $theme) { - $this->addItemToArrayCache('themes_by_labels', $theme, $theme->getLabel($anr->getLanguage())); - } - } + return isset($this->arrayCache[$cacheKey][$itemKey]); } - public function prepareSoaCategoriesCacheData(Entity\Anr $anr): void - { - if (!isset($this->arrayCache['soa_categories_by_ref_and_label'])) { - /** @var Entity\SoaCategory $soaCategory */ - foreach ($this->soaCategoryTable->findByAnr($anr) as $soaCategory) { - $this->addItemToArrayCache( - 'soa_categories_by_ref_and_label', - $soaCategory, - $soaCategory->getReferential()->getUuid() . '_' . $soaCategory->getLabel($anr->getLanguage()) - ); - } - } - } - - public function addItemToArrayCache(string $cacheKey, $value, $itemKey = null): void - { + public function addItemToArrayCache( + string $cacheKey, + $value, + $itemKey = null + ): void { if ($itemKey === null) { $this->arrayCache[$cacheKey][] = $value; } else { @@ -52,7 +34,7 @@ public function addItemToArrayCache(string $cacheKey, $value, $itemKey = null): } /** - * @return mixed + * @return array|null|mixed */ public function getItemFromArrayCache(string $cacheKey, $itemKey = null) { diff --git a/src/Import/Processor/AssetImportProcessor.php b/src/Import/Processor/AssetImportProcessor.php new file mode 100644 index 00000000..1325282e --- /dev/null +++ b/src/Import/Processor/AssetImportProcessor.php @@ -0,0 +1,80 @@ +prepareAssetUuidsAndCodesCache($anr); + foreach ($assetsData as $assetData) { + $this->processAssetData($anr, $assetData); + } + } + + public function processAssetData(Entity\Anr $anr, array $assetData): Entity\Asset + { + $asset = $this->getAssetFromCacheOrDb($anr, $assetData['uuid']); + if ($asset !== null) { + return $asset; + } + + /* The code should be unique. */ + if ($this->importCacheHelper->isItemInArrayCache('assets_codes', $assetData['code'])) { + $assetData['code'] .= '-' . time(); + } + + /* In the new data structure there is only "label" field set. */ + if (isset($assetData['label'])) { + $assetData['label' . $anr->getLanguage()] = $assetData['label']; + } + if (isset($assetData['description'])) { + $assetData['description' . $anr->getLanguage()] = $assetData['description']; + } + + $asset = $this->anrAssetService->create($anr, $assetData, false); + $this->importCacheHelper->addItemToArrayCache('assets', $asset, $asset->getUuid()); + + return $asset; + } + + public function getAssetFromCacheOrDb(Entity\Anr $anr, string $uuid): ?Entity\Asset + { + $asset = $this->importCacheHelper->getItemFromArrayCache('assets', $uuid); + /* The current anr asserts' UUIDs are preloaded, so can be validated first. */ + if ($asset === null && $this->importCacheHelper->isItemInArrayCache('assets_uuids', $uuid)) { + /** @var ?Entity\Asset $asset */ + $asset = $this->assetTable->findByUuidAndAnr($uuid, $anr, false); + } + + return $asset; + } + + public function prepareAssetUuidsAndCodesCache(Entity\Anr $anr): void + { + if (!$this->importCacheHelper->isCacheKeySet('assets_uuids')) { + foreach ($this->assetTable->findUuidsAndCodesByAnr($anr) as $data) { + $this->importCacheHelper + ->addItemToArrayCache('assets_uuids', (string)$data['uuid'], (string)$data['uuid']); + $this->importCacheHelper->addItemToArrayCache('assets_codes', $data['code'], $data['code']); + } + } + } +} diff --git a/src/Import/Processor/ReferentialImportProcessor.php b/src/Import/Processor/ReferentialImportProcessor.php new file mode 100644 index 00000000..52a4d98b --- /dev/null +++ b/src/Import/Processor/ReferentialImportProcessor.php @@ -0,0 +1,221 @@ +prepareReferentialUuidsAndMeasuresUuidsAndCodesCache($anr); + $this->prepareSoaCategoriesCache($anr); + foreach ($referentialsData as $referentialData) { + $this->processReferentialData($anr, $referentialData); + } + } + + public function processReferentialData(Entity\Anr $anr, array $referentialData): Entity\Referential + { + $referential = $this->importCacheHelper->getItemFromArrayCache('referentials', $referentialData['uuid']); + if ($referential !== null) { + return $referential; + } + + /* The current anr referential' UUIDs are preloaded, so can be validated first. */ + if ($this->importCacheHelper->isCacheKeySet('referential_' . $referential['uuid'] . '_measures_uuids')) { + /** @var Entity\Referential $referential */ + $referential = $this->referentialTable->findByUuidAndAnr($referentialData['uuid'], $anr, false); + } + + if ($referential === null) { + /* In the new data structure there is only "label" field set. */ + if (isset($referentialData['label'])) { + $referentialData['label' . $anr->getLanguage()] = $referentialData['label']; + } + + $referential = $this->anrReferentialService->create($anr, $referentialData, false); + $this->importCacheHelper->addItemToArrayCache('referentials', $referential, $referential->getUuid()); + } + + if (!empty($referentialData['measures'])) { + $this->processMeasuresData($anr, $referential, $referentialData['measures']); + } + + return $referential; + } + + public function processMeasuresData( + Entity\Anr $anr, + Entity\Referential $referential, + array $measuresData, + bool $prepareCache = false + ): void { + if ($prepareCache) { + $this->prepareReferentialUuidsAndMeasuresUuidsAndCodesCache($anr); + $this->prepareSoaCategoriesCache($anr); + } + + foreach ($measuresData as $measureData) { + $this->processMeasureData($anr, $referential, $measureData); + } + } + + public function processSoaCategoryData( + Entity\Anr $anr, + Entity\Referential $referential, + array $measureData + ): ?Entity\SoaCategory { + $soaCategory = null; + if (!empty($measureData['category'])) { + /* Support the previous structure format. */ + $soaCategoryLabel = $measureData['category']['label'] ?? $measureData['category']; + $soaCategory = $this->importCacheHelper->getItemFromArrayCache( + 'referential_' . $referential->getUuid() . '_soa_categories_by_labels', + $soaCategoryLabel + ); + if ($soaCategory === null) { + $soaCategory = $this->soaCategoryService->create($anr, [ + 'referential' => $referential, + 'label' . $anr->getLanguage() => $soaCategoryLabel, + ], false); + $this->importCacheHelper->addItemToArrayCache( + 'referential_' . $referential->getUuid() . '_soa_categories_by_labels', + $soaCategory, + $soaCategoryLabel + ); + } + } + + return $soaCategory; + } + + private function processMeasureData( + Entity\Anr $anr, + Entity\Referential $referential, + array $measureData + ): Entity\Measure { + $measure = $this->importCacheHelper->getItemFromArrayCache('measures', $measureData['uuid']); + if ($measure !== null) { + return $measure; + } + + /* The current anr measures' UUIDs are preloaded, so can be validated first. */ + if ($this->importCacheHelper->isItemInArrayCache( + 'referential_' . $referential->getUuid() . '_measures_uuids', + $measureData['uuid'] + )) { + /** @var Entity\Measure $measure */ + $measure = $this->measureTable->findByUuidAndAnr($measureData['uuid'], $anr, false); + if ($measure !== null) { + return $measure; + } + } + + /* The code should be unique. */ + if ($this->importCacheHelper->isItemInArrayCache( + 'referential_' . $referential->getUuid() . '_measures_codes', + $measureData['code'] + )) { + $measureData['code'] .= '-' . time(); + } + + /* In the new data structure there is only "label" field set. */ + if (isset($measureData['label'])) { + $measureData['label' . $anr->getLanguage()] = $measureData['label']; + } + + $soaCategory = $this->processSoaCategoryData($anr, $referential, $measureData); + + $measure = $this->anrMeasureService->createMeasureObject($anr, $referential, $soaCategory, $measureData, false); + $this->importCacheHelper->addItemToArrayCache('measures', $measure, $measure->getUuid()); + + $this->processLinkedMeasures($measure, $measureData); + + return $measure; + } + + private function processLinkedMeasures(Entity\Measure $measure, array $measureData): void + { + if (!empty($measureData['linkedMeasures'])) { + foreach ($measureData['linkedMeasures'] as $linkedMeasureData) { + $linkedMeasure = $this->importCacheHelper + ->getItemFromArrayCache('measures', $linkedMeasureData['uuid']); + if ($linkedMeasure === null) { + if ($this->importCacheHelper->isItemInArrayCache( + 'referential_' . $linkedMeasureData['referential']['uuid'] . '_measures_uuids', + $linkedMeasureData['uuid'] + )) { + /** @var Entity\Measure $linkedMeasure */ + $linkedMeasure = $this->measureTable->findByUuidAndAnr( + $linkedMeasureData['uuid'], + $measure->getAnr(), + false + ); + } + } + if ($linkedMeasure !== null) { + $measure->addLinkedMeasure($linkedMeasure); + $this->measureTable->save($linkedMeasure, false); + } + } + } + } + + private function prepareReferentialUuidsAndMeasuresUuidsAndCodesCache(Entity\Anr $anr): void + { + if (!$this->importCacheHelper->isCacheKeySet('referential_cache')) { + $this->importCacheHelper->addItemToArrayCache('referential_cache', true); + foreach ($this->referentialTable->findReferentialsUuidsWithMeasuresUuidsAndCodesByAnr($anr) as $data) { + $this->importCacheHelper->addItemToArrayCache( + 'referential_' . $data['uuid'] . '_measures_uuids', + (string)$data['measure_uuid'], + (string)$data['measure_uuid'] + ); + $this->importCacheHelper->addItemToArrayCache( + 'referential_' . $data['uuid'] . '_measures_codes', + $data['measure_code'], + $data['measure_code'] + ); + } + } + } + + private function prepareSoaCategoriesCache(Entity\Anr $anr): void + { + if (!$this->importCacheHelper->isCacheKeySet('soa_categories_cache')) { + $this->importCacheHelper->addItemToArrayCache('soa_categories_cache', true); + /** @var Entity\SoaCategory $soaCategory */ + foreach ($this->soaCategoryTable->findByAnr($anr) as $soaCategory) { + $this->importCacheHelper->addItemToArrayCache( + 'referential_' . $soaCategory->getReferential()->getUuid() . '_soa_categories_by_labels', + $soaCategory, + $soaCategory->getLabel($anr->getLanguage()) + ); + } + } + } +} diff --git a/src/Import/Processor/ThreatImportProcessor.php b/src/Import/Processor/ThreatImportProcessor.php new file mode 100644 index 00000000..d59c5987 --- /dev/null +++ b/src/Import/Processor/ThreatImportProcessor.php @@ -0,0 +1,120 @@ +prepareThreatUuidsAndCodesCache($anr); + $this->prepareThemesCache($anr); + + foreach ($threatsData as $threatData) { + $this->processThreatData($anr, $threatData, $themesData); + } + } + + public function processThreatData(Entity\Anr $anr, array $threatData, array $themesData): Entity\Threat + { + $threat = $this->getThreatFromCacheOrDb($anr, $threatData['uuid']); + if ($threat !== null) { + return $threat; + } + + /* In the old structure themes are exported separately, convert to the new format. */ + $labelKey = 'label' . $anr->getLanguage(); + if (!empty($themesData) + && !empty($threatData['theme']) + && isset($themesData[$threatData['theme']][$labelKey]) + ) { + $threatData['theme'] = ['label' => $themesData[$threatData['theme']][$labelKey]]; + } + + if ($this->importCacheHelper->isItemInArrayCache('threats_codes', $threatData['code'])) { + $threatData['code'] .= '-' . time(); + } + $threatData['theme'] = !empty($threatData['theme']) + ? $this->processThemeData($anr, $threatData['theme']) + : null; + + /* In the new data structure there is only "label" field set. */ + if (isset($threatData['label'])) { + $threatData['label' . $anr->getLanguage()] = $threatData['label']; + } + if (isset($threatData['description'])) { + $threatData['description' . $anr->getLanguage()] = $threatData['description']; + } + + $threat = $this->anrThreatService->create($anr, $threatData, false); + $this->importCacheHelper->addItemToArrayCache('threats', $threat, $threat->getUuid()); + + return $threat; + } + + public function getThreatFromCacheOrDb(Entity\Anr $anr, string $uuid): ?Entity\Threat + { + $threat = $this->importCacheHelper->getItemFromArrayCache('threats', $uuid); + /* The current anr threats' UUIDs are preloaded, so can be validated first. */ + if ($threat === null && $this->importCacheHelper->isItemInArrayCache('threats_uuids', $uuid)) { + /** @var ?Entity\Threat $threat */ + $threat = $this->threatTable->findByUuidAndAnr($uuid, $anr, false); + } + + return $threat; + } + + public function prepareThreatUuidsAndCodesCache(Entity\Anr $anr): void + { + if (!$this->importCacheHelper->isCacheKeySet('threats_uuids')) { + foreach ($this->threatTable->findUuidsAndCodesByAnr($anr) as $data) { + $this->importCacheHelper + ->addItemToArrayCache('threats_uuids', (string)$data['uuid'], (string)$data['uuid']); + $this->importCacheHelper->addItemToArrayCache('threats_codes', $data['code'], $data['code']); + } + } + } + + public function prepareThemesCache(Entity\Anr $anr): void + { + if (!$this->importCacheHelper->isCacheKeySet('themes_by_labels')) { + /** @var Entity\Theme $theme */ + foreach ($this->themeTable->findByAnr($anr) as $theme) { + $this->importCacheHelper + ->addItemToArrayCache('themes_by_labels', $theme, $theme->getLabel($anr->getLanguage())); + } + } + } + + private function processThemeData(Entity\Anr $anr, array $themeData): Entity\Theme + { + $theme = $this->importCacheHelper->getItemFromArrayCache('themes_by_labels', $themeData['label']); + if ($theme === null) { + $themeData['label' . $anr->getLanguage()] = $theme['label']; + $theme = $this->anrThemeService->create($anr, $themeData, false); + $this->importCacheHelper->addItemToArrayCache('themes_by_labels', $theme, $themeData['label']); + } + + return $theme; + } +} diff --git a/src/Import/Processor/VulnerabilityImportProcessor.php b/src/Import/Processor/VulnerabilityImportProcessor.php new file mode 100644 index 00000000..e72434e6 --- /dev/null +++ b/src/Import/Processor/VulnerabilityImportProcessor.php @@ -0,0 +1,81 @@ +prepareVulnerabilityUuidsAndCodesCache($anr); + foreach ($vulnerabilitiesData as $vulnerabilityData) { + $this->processVulnerabilityData($anr, $vulnerabilityData); + } + } + + public function processVulnerabilityData(Entity\Anr $anr, array $vulnerabilityData): Entity\Vulnerability + { + $vulnerability = $this->getVulnerabilityFromCacheOrDb($anr, $vulnerabilityData['uuid']); + if ($vulnerability !== null) { + return $vulnerability; + } + + /* The code should be unique. */ + if ($this->importCacheHelper->isItemInArrayCache('vulnerabilities_codes', $vulnerabilityData['code'])) { + $vulnerabilityData['code'] .= '-' . time(); + } + + /* In the new data structure there is only "label" field set. */ + if (isset($vulnerabilityData['label'])) { + $vulnerabilityData['label' . $anr->getLanguage()] = $vulnerabilityData['label']; + } + if (isset($vulnerabilityData['description'])) { + $vulnerabilityData['description' . $anr->getLanguage()] = $vulnerabilityData['description']; + } + + $vulnerability = $this->anrVulnerabilityService->create($anr, $vulnerabilityData, false); + $this->importCacheHelper->addItemToArrayCache('vulnerabilities', $vulnerability, $vulnerability->getUuid()); + + return $vulnerability; + } + + public function getVulnerabilityFromCacheOrDb(Entity\Anr $anr, string $uuid): ?Entity\Vulnerability + { + $vulnerability = $this->importCacheHelper->getItemFromArrayCache('vulnerabilities', $uuid); + /* The current anr vulnerabilities' UUIDs are preloaded, so can be validated first. */ + if ($vulnerability === null && $this->importCacheHelper->isItemInArrayCache('vulnerabilities_uuids', $uuid)) { + /** @var ?Entity\Vulnerability $vulnerability */ + $vulnerability = $this->vulnerabilityTable->findByUuidAndAnr($uuid, $anr, false); + } + + return $vulnerability; + } + + public function prepareVulnerabilityUuidsAndCodesCache(Entity\Anr $anr): void + { + if (!$this->importCacheHelper->isCacheKeySet('vulnerabilities_uuids')) { + foreach ($this->vulnerabilityTable->findUuidsAndCodesByAnr($anr) as $data) { + $this->importCacheHelper + ->addItemToArrayCache('vulnerabilities_uuids', (string)$data['uuid'], (string)$data['uuid']); + $this->importCacheHelper->addItemToArrayCache('vulnerabilities_codes', $data['code'], $data['code']); + } + } + } +} diff --git a/src/Service/AnrInstanceRiskService.php b/src/Service/AnrInstanceRiskService.php index f908924c..2efc581f 100644 --- a/src/Service/AnrInstanceRiskService.php +++ b/src/Service/AnrInstanceRiskService.php @@ -459,12 +459,16 @@ private function duplicateRecommendationRisks( Entity\InstanceRisk $fromInstanceRisk, Entity\InstanceRisk $newInstanceRisk ): void { + /** @var Entity\Anr $anr */ + $anr = $newInstanceRisk->getAnr(); + /** @var Entity\Instance $instance */ + $instance = $newInstanceRisk->getInstance(); foreach ($fromInstanceRisk->getRecommendationRisks() as $recommendationRiskToDuplicate) { $newRecommendationRisk = (new Entity\RecommendationRisk()) - ->setAnr($newInstanceRisk->getAnr()) + ->setAnr($anr) ->setCommentAfter($recommendationRiskToDuplicate->getCommentAfter()) ->setRecommendation($recommendationRiskToDuplicate->getRecommendation()) - ->setInstance($newInstanceRisk->getInstance()) + ->setInstance($instance) ->setGlobalObject($recommendationRiskToDuplicate->getGlobalObject()) ->setAsset($recommendationRiskToDuplicate->getAsset()) ->setThreat($recommendationRiskToDuplicate->getThreat()) diff --git a/src/Service/AnrMeasureMeasureService.php b/src/Service/AnrMeasureLinkService.php similarity index 68% rename from src/Service/AnrMeasureMeasureService.php rename to src/Service/AnrMeasureLinkService.php index 06459700..0cb986c0 100644 --- a/src/Service/AnrMeasureMeasureService.php +++ b/src/Service/AnrMeasureLinkService.php @@ -11,29 +11,28 @@ use Monarc\FrontOffice\Entity; use Monarc\FrontOffice\Table; -class AnrMeasureMeasureService +class AnrMeasureLinkService { - public function __construct( - private Table\MeasureMeasureTable $measureMeasureTable, - private Table\MeasureTable $measureTable - ) { + public function __construct(private Table\MeasureTable $measureTable) { } public function getList(Entity\Anr $anr): array { $result = []; - /** @var Entity\MeasureMeasure $measureMeasure */ - foreach ($this->measureMeasureTable->findByAnr($anr) as $measureMeasure) { - $result[] = [ - 'masterMeasure' => array_merge([ - 'uuid' => $measureMeasure->getMasterMeasure()->getUuid(), - 'code' => $measureMeasure->getMasterMeasure()->getCode(), - ], $measureMeasure->getMasterMeasure()->getLabels()), - 'linkedMeasure' => array_merge([ - 'uuid' => $measureMeasure->getLinkedMeasure()->getUuid(), - 'code' => $measureMeasure->getLinkedMeasure()->getCode(), - ], $measureMeasure->getLinkedMeasure()->getLabels()), - ]; + /** @var Entity\Measure $masterMeasure */ + foreach ($this->measureTable->findByAnr($anr) as $masterMeasure) { + foreach ($masterMeasure->getLinkedMeasures() as $linkedMeasure) { + $result[] = [ + 'masterMeasure' => array_merge([ + 'uuid' => $masterMeasure->getUuid(), + 'code' => $masterMeasure->getCode(), + ], $masterMeasure->getLabels()), + 'linkedMeasure' => array_merge([ + 'uuid' => $linkedMeasure->getUuid(), + 'code' => $linkedMeasure->getCode(), + ], $linkedMeasure->getLabels()), + ]; + } } return $result; @@ -65,7 +64,7 @@ public function createList(Entity\Anr $anr, array $data): array foreach ($data as $rowData) { $createdIds[] = $this->create($anr, $rowData, false)->getUuid(); } - $this->measureMeasureTable->flush(); + $this->measureTable->flush(); return $createdIds; } diff --git a/src/Service/AnrMeasureService.php b/src/Service/AnrMeasureService.php index c56ac772..bef5a994 100755 --- a/src/Service/AnrMeasureService.php +++ b/src/Service/AnrMeasureService.php @@ -60,6 +60,16 @@ public function create(Entity\Anr $anr, array $data, bool $saveInDb = true): Ent /** @var Entity\SoaCategory $soaCategory */ $soaCategory = $this->soaCategoryTable->findByIdAndAnr($data['categoryId'], $anr); + return $this->createMeasureObject($anr, $referential, $soaCategory, $data, $saveInDb); + } + + public function createMeasureObject( + Entity\Anr $anr, + Entity\Referential $referential, + ?Entity\SoaCategory $soaCategory, + array $data, + bool $saveInDb = true + ): Entity\Measure { /** @var Entity\Measure $measure */ $measure = (new Entity\Measure()) ->setAnr($anr) @@ -141,8 +151,10 @@ private function prepareMeasureDataResult(Entity\Measure $measure, bool $include { $linkedMeasures = []; if ($includeLinks) { + /** @var Entity\Measure $linkedMeasure */ foreach ($measure->getLinkedMeasures() as $linkedMeasure) { $linkedMeasures[] = array_merge([ + 'id' => $linkedMeasure->getId(), 'uuid' => $linkedMeasure->getUuid(), 'code' => $linkedMeasure->getCode(), ], $linkedMeasure->getLabels()); @@ -150,6 +162,7 @@ private function prepareMeasureDataResult(Entity\Measure $measure, bool $include } return array_merge([ + 'id' => $measure->getId(), 'uuid' => $measure->getUuid(), 'referential' => array_merge([ 'uuid' => $measure->getReferential()->getUuid(), diff --git a/src/Service/AnrModelService.php b/src/Service/AnrModelService.php index 310b2637..d6d43f14 100644 --- a/src/Service/AnrModelService.php +++ b/src/Service/AnrModelService.php @@ -53,9 +53,9 @@ public function getModelsListOfClient(): array */ public function getAvailableLanguages(int $modelId): array { - $languages = array_keys($this->configService->getLanguageCodes()); + $languageIndexes = [1, 2, 3, 4]; $result = []; - foreach ($languages as $languageIndex) { + foreach ($languageIndexes as $languageIndex) { $result[$languageIndex] = true; } @@ -96,7 +96,7 @@ public function getAvailableLanguages(int $modelId): array } /* Generic threats and themes validation. */ foreach ($this->coreThreatTable->findByMode(CoreEntity\ThreatSuperClass::MODE_GENERIC) as $threat) { - foreach ($languages as $languageIndex) { + foreach ($languageIndexes as $languageIndex) { if (empty($threat->getLabel($languageIndex)) || ($threat->getTheme() !== null && empty($threat->getTheme()->getLabel($languageIndex)) @@ -117,7 +117,7 @@ public function getAvailableLanguages(int $modelId): array $this->validateEntityLanguages($specificAsset, $result); } foreach ($model->getThreats() as $specificThreat) { - foreach ($languages as $languageIndex) { + foreach ($languageIndexes as $languageIndex) { if (empty($specificThreat->getLabel($languageIndex)) || ($specificThreat->getTheme() !== null && empty($specificThreat->getTheme()->getLabel($languageIndex)) @@ -135,7 +135,7 @@ public function getAvailableLanguages(int $modelId): array /* Validates monarc objects. */ /** @var CoreEntity\MonarcObject $monarcObject */ foreach ($model->getAnr() ? $model->getAnr()->getObjects() : [] as $monarcObject) { - foreach ($languages as $languageIndex) { + foreach ($languageIndexes as $languageIndex) { if (empty($monarcObject->getLabel($languageIndex)) || empty($monarcObject->getName($languageIndex)) || ($monarcObject->getCategory() !== null diff --git a/src/Service/AnrObjectService.php b/src/Service/AnrObjectService.php index 12fae493..ae9d0ea8 100755 --- a/src/Service/AnrObjectService.php +++ b/src/Service/AnrObjectService.php @@ -13,7 +13,6 @@ use Monarc\Core\Service\ConnectedUserService; use Monarc\Core\Service\Traits\PositionUpdateTrait; use Monarc\FrontOffice\Entity; -use Monarc\FrontOffice\Model\Table as DeprecatedTable; use Monarc\FrontOffice\Table; class AnrObjectService @@ -28,7 +27,7 @@ public function __construct( private Table\AssetTable $assetTable, private Table\ObjectCategoryTable $objectCategoryTable, private Table\ObjectObjectTable $objectObjectTable, - private DeprecatedTable\RolfTagTable $rolfTagTable, + private Table\RolfTagTable $rolfTagTable, private Table\InstanceRiskOpTable $instanceRiskOpTable, private AnrInstanceRiskOpService $anrInstanceRiskOpService, ConnectedUserService $connectedUserService diff --git a/src/Service/AnrService.php b/src/Service/AnrService.php index ae668996..87f8ea91 100755 --- a/src/Service/AnrService.php +++ b/src/Service/AnrService.php @@ -137,7 +137,7 @@ public function getAnrData(Entity\Anr $anr): array $userAnr = $this->userAnrTable->findByAnrAndUser($realAnrInUse, $this->connectedUser); if ($realAnrInUse->getId() !== $this->connectedUser->getCurrentAnr()?->getId()) { - $this->setCurrentAnrToConnectedUser($realAnrInUse); + $this->setCurrentAnrToConnectedUser($realAnrInUse, true); } return $this->getPreparedAnrData($anr, $userAnr, true); @@ -588,9 +588,9 @@ private function updateReferentialsFromSource( return $createdMeasuresUuidsToObjects; } - private function setCurrentAnrToConnectedUser(Entity\Anr $anr): void + private function setCurrentAnrToConnectedUser(Entity\Anr $anr, bool $saveInDb = false): void { - $this->userTable->save($this->connectedUser->setCurrentAnr($anr)); + $this->userTable->save($this->connectedUser->setCurrentAnr($anr), $saveInDb); } private function duplicateScales( @@ -690,7 +690,9 @@ private function duplicateOperationalRiskScales( foreach ($sourceOperationalRiskScale->getOperationalRiskScaleTypes() as $operationalRiskScaleType) { if ($isSourceCommon) { /** @var CoreEntity\OperationalRiskScaleType $operationalRiskScaleType */ - $label = $sourceTranslations[$operationalRiskScaleType->getLabelTranslationKey()] ?? ''; + $label = isset($sourceTranslations[$operationalRiskScaleType->getLabelTranslationKey()]) + ? $sourceTranslations[$operationalRiskScaleType->getLabelTranslationKey()]->getValue() + : ''; } else { /** @var Entity\OperationalRiskScaleType $operationalRiskScaleType */ $label = $operationalRiskScaleType->getLabel(); @@ -738,6 +740,9 @@ private function duplicateOperationalRiskScales( return $operationalScaleTypesOldIdsToNewObjects; } + /** + * @param CoreEntity\Translation[] $sourceTranslations + */ private function duplicateOperationalRiskScaleComments( Entity\Anr $newAnr, Entity\OperationalRiskScale $newOperationalRiskScale, @@ -746,7 +751,9 @@ private function duplicateOperationalRiskScaleComments( array $sourceTranslations ): void { if ($sourceOperationalRiskScaleComment instanceof CoreEntity\OperationalRiskScaleComment) { - $comment = $sourceTranslations[$sourceOperationalRiskScaleComment->getLabelTranslationKey()] ?? ''; + $comment = isset($sourceTranslations[$sourceOperationalRiskScaleComment->getLabelTranslationKey()]) + ? $sourceTranslations[$sourceOperationalRiskScaleComment->getLabelTranslationKey()]->getValue() + : ''; } else { /** @var Entity\OperationalRiskScaleComment $sourceOperationalRiskScaleComment */ $comment = $sourceOperationalRiskScaleComment->getComment(); @@ -1066,7 +1073,9 @@ private function duplicateSoasAndSoaScaleComments( foreach ($soaScaleCommentTable->findByAnrOrderByIndex($sourceAnr) as $sourceSoaScaleComment) { if ($isSourceCommon) { /** @var CoreEntity\SoaScaleComment $sourceSoaScaleComment */ - $comment = $commonTranslations[$sourceSoaScaleComment->getLabelTranslationKey()] ?? ''; + $comment = isset($commonTranslations[$sourceSoaScaleComment->getLabelTranslationKey()]) + ? $commonTranslations[$sourceSoaScaleComment->getLabelTranslationKey()]->getValue() + : ''; } else { /** @var Entity\SoaScaleComment $sourceSoaScaleComment */ $comment = $sourceSoaScaleComment->getComment(); @@ -1170,14 +1179,6 @@ private function duplicateObjectsCompositions( ->setPosition($sourceChildLinkObject->getPosition()) ->setCreator($this->connectedUser->getEmail()); $this->objectObjectTable->save($newObjectObject, false); - - if ($sourceChildLinkObject->getChild()->hasChildren()) { - $this->duplicateObjectsCompositions( - $newAnr, - $sourceChildLinkObject->getChild(), - $monarcObjectsUuidsToNewObjects - ); - } } } diff --git a/src/Service/InstanceRiskOwnerService.php b/src/Service/InstanceRiskOwnerService.php index 025dd76e..15c7fc2f 100644 --- a/src/Service/InstanceRiskOwnerService.php +++ b/src/Service/InstanceRiskOwnerService.php @@ -40,11 +40,8 @@ public function create(Anr $anr, string $ownerName, bool $saveIdDb = false): Ins return $instanceRiskOwner; } - public function getOrCreateInstanceRiskOwner( - Anr $sourceAnr, - Anr $anr, - string $ownerName - ): InstanceRiskOwner { + public function getOrCreateInstanceRiskOwner(Anr $sourceAnr, Anr $anr, string $ownerName): InstanceRiskOwner + { if (!isset($this->cachedData['instanceRiskOwners'][$ownerName])) { $instanceRiskOwner = $this->instanceRiskOwnerTable->findByAnrAndName($sourceAnr, $ownerName); if ($instanceRiskOwner === null) { @@ -61,18 +58,10 @@ public function processRiskOwnerNameAndAssign(string $ownerName, InstanceRisk|In { if (empty($ownerName)) { $instanceRisk->setInstanceRiskOwner(null); - return; - } - - /** @var Anr $anr */ - $anr = $instanceRisk->getAnr(); - $instanceRiskOwner = $this->instanceRiskOwnerTable->findByAnrAndName($anr, $ownerName); - if ($instanceRiskOwner === null) { - $instanceRiskOwner = $this->create($anr, $ownerName); - $instanceRisk->setInstanceRiskOwner($instanceRiskOwner); - } elseif ($instanceRisk->getInstanceRiskOwner() === null - || $instanceRisk->getInstanceRiskOwner()->getId() !== $instanceRiskOwner->getId() - ) { + } else { + /** @var Anr $anr */ + $anr = $instanceRisk->getAnr(); + $instanceRiskOwner = $this->getOrCreateInstanceRiskOwner($anr, $anr, $ownerName); $instanceRisk->setInstanceRiskOwner($instanceRiskOwner); } } diff --git a/src/Stats/Service/StatsAnrService.php b/src/Stats/Service/StatsAnrService.php index bff49582..86933841 100644 --- a/src/Stats/Service/StatsAnrService.php +++ b/src/Stats/Service/StatsAnrService.php @@ -20,7 +20,7 @@ use Monarc\FrontOffice\Entity\User; use Monarc\FrontOffice\Entity\UserRole; use Monarc\FrontOffice\Model\Table\SoaTable; -use Monarc\FrontOffice\Model\Table\ReferentialTable; +use Monarc\FrontOffice\Table\ReferentialTable; use Monarc\FrontOffice\Table\ScaleTable; use Monarc\FrontOffice\Table\AnrTable; use Monarc\FrontOffice\Table\InstanceRiskOpTable; diff --git a/src/Table/AssetTable.php b/src/Table/AssetTable.php index 22834838..0a540275 100755 --- a/src/Table/AssetTable.php +++ b/src/Table/AssetTable.php @@ -11,6 +11,7 @@ use Monarc\Core\Table\AbstractTable; use Monarc\Core\Table\Interfaces\UniqueCodeTableInterface; use Monarc\Core\Table\Traits\CodeExistenceValidationTableTrait; +use Monarc\FrontOffice\Entity\Anr; use Monarc\FrontOffice\Entity\Asset; class AssetTable extends AbstractTable implements UniqueCodeTableInterface @@ -21,4 +22,14 @@ public function __construct(EntityManager $entityManager, string $entityName = A { parent::__construct($entityManager, $entityName); } + + public function findUuidsAndCodesByAnr(Anr $anr): array + { + return $this->getRepository()->createQueryBuilder('a') + ->select('a.uuid', 'a.code') + ->where('a.anr = :anr') + ->setParameter('anr', $anr) + ->getQuery() + ->getArrayResult(); + } } diff --git a/src/Table/MeasureMeasureTable.php b/src/Table/MeasureMeasureTable.php deleted file mode 100644 index 330ddbb3..00000000 --- a/src/Table/MeasureMeasureTable.php +++ /dev/null @@ -1,39 +0,0 @@ -getRepository()->createQueryBuilder('mm') - ->where('mm.anr = :anr') - ->andWhere('mm.masterMeasure = :masterMeasure') - ->andWhere('mm.linkedMeasure = :linkedMeasure') - ->setParameter('anr', $anr) - ->setParameter('masterMeasure', $masterMeasureUuid) - ->setParameter('linkedMeasure', $linkedMeasureUuid) - ->setMaxResults(1) - ->getQuery() - ->getOneOrNullResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) !== null; - } -} diff --git a/src/Table/ReferentialTable.php b/src/Table/ReferentialTable.php index 54e01a72..e23d4c44 100644 --- a/src/Table/ReferentialTable.php +++ b/src/Table/ReferentialTable.php @@ -9,6 +9,7 @@ use Doctrine\ORM\EntityManager; use Monarc\Core\Table\AbstractTable; +use Monarc\FrontOffice\Entity\Anr; use Monarc\FrontOffice\Entity\Referential; class ReferentialTable extends AbstractTable @@ -17,4 +18,15 @@ public function __construct(EntityManager $entityManager, string $entityName = R { parent::__construct($entityManager, $entityName); } + + public function findReferentialsUuidsWithMeasuresUuidsAndCodesByAnr(Anr $anr): array + { + return $this->getRepository()->createQueryBuilder('r') + ->innerJoin('r.measures', 'm') + ->select('r.uuid, m.uuid as measure_uuid, m.code as measure_code') + ->where('r.anr = :anr') + ->setParameter('anr', $anr) + ->getQuery() + ->getArrayResult(); + } } diff --git a/src/Table/ThreatTable.php b/src/Table/ThreatTable.php index a25d7885..a22e990c 100755 --- a/src/Table/ThreatTable.php +++ b/src/Table/ThreatTable.php @@ -34,4 +34,14 @@ public function isEvaluationStarted(Anr $anr): bool ->getQuery() ->getOneOrNullResult(AbstractQuery::HYDRATE_SIMPLEOBJECT) !== null; } + + public function findUuidsAndCodesByAnr(Anr $anr): array + { + return $this->getRepository()->createQueryBuilder('t') + ->select('t.uuid', 't.code') + ->where('t.anr = :anr') + ->setParameter('anr', $anr) + ->getQuery() + ->getArrayResult(); + } } diff --git a/src/Table/VulnerabilityTable.php b/src/Table/VulnerabilityTable.php index 71228788..bdb691f3 100755 --- a/src/Table/VulnerabilityTable.php +++ b/src/Table/VulnerabilityTable.php @@ -11,6 +11,7 @@ use Monarc\Core\Table\AbstractTable; use Monarc\Core\Table\Interfaces\UniqueCodeTableInterface; use Monarc\Core\Table\Traits\CodeExistenceValidationTableTrait; +use Monarc\FrontOffice\Entity\Anr; use Monarc\FrontOffice\Entity\Vulnerability; class VulnerabilityTable extends AbstractTable implements UniqueCodeTableInterface @@ -21,4 +22,14 @@ public function __construct(EntityManager $entityManager, string $entityName = V { parent::__construct($entityManager, $entityName); } + + public function findUuidsAndCodesByAnr(Anr $anr): array + { + return $this->getRepository()->createQueryBuilder('v') + ->select('v.uuid', 'v.code') + ->where('v.anr = :anr') + ->setParameter('anr', $anr) + ->getQuery() + ->getArrayResult(); + } }