src/Controller/ProductController.php line 340

Open in your IDE?
  1. <?php 
  2. namespace App\Controller;
  3. use App\Entity\AttributeItems;
  4. use App\Entity\Attributes;
  5. use App\Entity\Products;
  6. use App\Entity\Category;
  7. use App\Entity\MeasurmentUnit;
  8. use App\Entity\SiteProductsMedia;
  9. use App\Entity\MediaObject;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\HttpKernel\Attribute\AsController;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use App\Repository\ProductsRepository;
  17. use App\Repository\SiteProductsRepository;
  18. use App\Repository\ProductBalanceInStorageRepository;
  19. use App\Repository\MediaObjectsRepository;
  20. use Symfony\Component\HttpFoundation\StreamedResponse;
  21. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  22. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  23. use PhpOffice\PhpSpreadsheet\IOFactory;
  24. use App\Service\Translit;
  25. use Intervention\Image\ImageManager;
  26. use Symfony\Component\HttpKernel\KernelInterface
  27. use App\Service\ImageResize;
  28. #[AsController]
  29. class ProductController
  30. {
  31.     private $ProductsRepository;
  32.     private $entityManager;
  33.     private $kernel;
  34.     public function __construct(EntityManagerInterface $entityManagerProductsRepository $ProductsRepositoryKernelInterface $kernel  )
  35.     {
  36.         $this->entityManager $entityManager;
  37.         $this->ProductsRepository $ProductsRepository;
  38.         $this->kernel $kernel;
  39.     }
  40.     #[Route(
  41.         name'product_filter'
  42.         path'/api/products/filter',
  43.         methods: ['GET'],
  44.     )]
  45.     public function __invoke(Request $request): Response
  46.     {
  47.         $_get $request->query->all();
  48.         $query =$_get['search']; // Отримуємо параметр "query" з URL.
  49.         $t $_get['type']; // Отримуємо параметр "query" з URL.
  50.         if($t == '1'){
  51.             $data explode(' '$query );
  52.             $products $this->ProductsRepository->searchByNameSpecefycal($data$query);
  53.         }else{
  54.             $products $this->ProductsRepository->searchByNameOrBarcode($query);
  55.         }
  56.         if (empty($products)) {
  57.             return new JsonResponse([]);
  58.         }
  59.         return new JsonResponse($products200);
  60.     }
  61.     #[Route(
  62.         name'set_show_products'
  63.         path'/set-show-products',
  64.     )]
  65.     public function set_show_products(ProductBalanceInStorageRepository $ProductBalanceInStorageRepositoryRequest $request): Response
  66.     {
  67.         die;
  68.         $productsBlance $ProductBalanceInStorageRepository->findAll();
  69.         if($productsBlance){
  70.             echo count($productsBlance) . "<br>";
  71.         }
  72.         $sumBalance = [];
  73.         foreach($productsBlance as $pb){
  74.             $id $pb->getProduct()->getId();
  75.             if(!isset($sumBalance[$id]))
  76.                 $sumBalance[$id] = ['sum' => 0'product' => $pb->getProduct()];
  77.                 $sumBalance[$id]['sum'] += $pb->getCount();
  78.         }
  79.         $c 0;
  80.         foreach($sumBalance as $sb){
  81.             
  82.             if($sb['sum'] >= 300){
  83.                $c++; 
  84.                $sb['product']->setShow(true);
  85.             }else{
  86.                 $sb['product']->setShow(false);
  87.             }
  88.             $this->entityManager->persist$sb['product'] );
  89.         }
  90.         $this->entityManager->flush();
  91.         echo count($sumBalance) . "<br>";
  92.         echo $c;
  93.         
  94.         die;
  95.     }
  96.     #[Route(
  97.         name'set_site_product_img'
  98.         path'/set-site-product-img',
  99.     )]
  100.     public function set_site_product_img(SiteProductsRepository $SiteProductsRepositoryRequest $request): Response
  101.     {
  102.         $productsSite $SiteProductsRepository->findAll();
  103.         foreach ( $productsSite as $ps){
  104.             $isMedia false;
  105.             // echo '<pre>';
  106.             // echo count($ps->getSiteProductsMedia());
  107.             //print_r($ps->getSiteProductsMedia()); 
  108.             // die;
  109.             if(count($ps->getSiteProductsMedia()) == 0){
  110.                 if($ps->getProducts() != null){
  111.                     foreach($ps->getProducts() as $p){
  112.                         if( !$isMedia AND $p->getMedia() != null AND count($p->getMedia()) > 0){
  113.                             
  114.                             foreach($p->getMedia() as $m){
  115.                                 $spm = new SiteProductsMedia();
  116.                                 $spm->setSiteProduct($ps);
  117.                                 $spm->setMedia($m);
  118.                                 $spm->setMain($m->isMain());
  119.                                 $this->entityManager->persist($spm);
  120.                                 // $this->entityManager->flush();
  121.                                 if($p->getMainMedia() != null){
  122.                                     if($p->getMainMedia()->getId() == $m->getId()){
  123.                                         $ps->setMainSiteProductMedia($spm);
  124.                                         $this->entityManager->persist($spm);
  125.                                     }
  126.                                 }
  127.                                 $isMedia true;
  128.                                 // $this->entityManager->flush();
  129.                             }
  130.                         }
  131.                     }
  132.                         
  133.                 }
  134.                 // var_dump($ps->getMainSiteProductMedia());
  135.             }
  136.         }
  137.         $this->entityManager->flush();
  138.         die;
  139.     }
  140.     #[Route(
  141.         name'get_product'
  142.         path'/get-product',
  143.     )]
  144.     public function get_product(SiteProductsRepository $SiteProductsRepositoryRequest $request): Response
  145.     {
  146.         die;
  147.         $find $this->entityManager->getRepository(Products::class)->findAll();
  148.         foreach($find as $p){
  149.             if(empty($p->getPriceIncome()))
  150.                 continue;
  151.             $arr = [
  152.                 'gurt_1' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.05), 2),
  153.                 'gurt_2' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.07), 2),
  154.                 'gurt_3' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.09), 2),
  155.                 'gurt_4' => round($p->getPriceIncome() + ($p->getPriceIncome() * 0.1), 2),
  156.             ];
  157.             echo $p->getPriceIncome(). '---'.json_encode($arr).'<br>';
  158.             $p->setPriceCategory($arr);
  159.             $this->entityManager->persist($p);
  160.         }
  161.         $this->entityManager->flush();
  162.         // echo count( $find);
  163.         die;
  164.     }
  165.     #[Route(
  166.         name'export_form'
  167.         path'/api/export_csv',
  168.         methods: ['GET']
  169.     )]
  170.     public function export_csvEntityManagerInterface $entityManagerRequest $request): StreamedResponse
  171.     {
  172.             $products $entityManager->getRepository(Products::class)->findAll();
  173.             $attributes $entityManager->getRepository(Attributes::class)->findAll();
  174.             // echo count($products); die;
  175.             if( $products ){
  176.                 $header = [
  177.                     'name',
  178.                     'site_name',
  179.                     'article',
  180.                     'code',
  181.                     'all_category',
  182.                     'last_category',
  183.                     // 'attributes',
  184.                 ];
  185.                 $arrAttr = [];
  186.                 foreach($attributes as $attr){
  187.                     $arrAttr[$attr->getId()] = '';
  188.                     $header[] = $attr->getName();
  189.                 }
  190.                
  191.                 $response = new StreamedResponse(function () use ($arrAttr$header$products) {
  192.                     $csv fopen('php://output''w+');
  193.                     fprintf($csv"\xEF\xBB\xBF");
  194.                     fputcsv($csv$header';');
  195.                     foreach($products as $prod){
  196.                         if(count($prod->getCategory()) > OR count($prod->getAttributeItems()) > 0){
  197.                             $prodAttr $arrAttr;
  198.                             $arr = [];
  199.                             $arr[] = $prod->getName();
  200.                             $siteName '';
  201.                             if($prod->getSiteProduct())
  202.                                 $siteName $prod->getSiteProduct()->getName();
  203.                             $arr[] = $siteName;
  204.                             $arr[] = $prod->getArticle();
  205.                             $arr[] = $prod->getCode1c();
  206.                             
  207.                             $category '';
  208.                             foreach($prod->getCategory() as $cat){
  209.                                 // file_put_contents('Category.log', strpos($category, $cat->getName()) . "\n", FILE_APPEND);
  210.                                 // if($cat->isMain()){
  211.                                 
  212.                                 // }
  213.                                 if($cat->getParent()){
  214.                                     
  215.                                     if($cat->getParent()->getParent()){
  216.                                         $p $cat->getParent()->getParent();
  217.                                         // if($p->isMain()){
  218.                                             if(!str_contains($category$p->getName()."|"))
  219.                                                 $category .= $p->getName()."|";
  220.                                         // }
  221.                                     }
  222.                                     // if($cat->getParent()->isMain()){
  223.                                         if(!str_contains($category$cat->getParent()->getName()."|"))
  224.                                             $category .= $cat->getParent()->getName()."|";
  225.                                     // }
  226.                                 }
  227.                                 if(!str_contains($category$cat->getName()."|"))
  228.                                         $category .= $cat->getName()."|";
  229.                             }
  230.                             $arr[] = $category;
  231.                             $lastCategory '';
  232.                             foreach($prod->getCategory() as $cat){
  233.                                 // if(count($prod->getCategory()) > 0)
  234.                                 $lastCategory .= $cat->getName(). " | ";
  235.                             }
  236.                             $arr[] = $lastCategory;
  237.                             if(count($prod->getAttributeItems()) > 0){
  238.                                 foreach($prod->getAttributeItems() as $attrItem){
  239.                                     if($attrItem->getAttribute() !=null)
  240.                                         $prodAttr[$attrItem->getAttribute()->getId()] = $attrItem->getName();
  241.                                 }
  242.                                 foreach($prodAttr as $v){
  243.                                 
  244.                                     $arr[] = $v;
  245.                                 }
  246.                             }
  247.                             
  248.                             fputcsv($csv$arr';');
  249.                         }
  250.                     }
  251.  
  252.                     fclose($csv);
  253.                 });
  254.                 
  255.                 $response->headers->set('Content-Type''application/csv');
  256.                 $response->headers->set('Content-Encoding''UTF-8');
  257.                 $response->headers->set('Content-Disposition''attachment; filename="file.csv"');
  258.                 $response->headers->set('Cache-Control''no-store');
  259.             }
  260.         
  261.         return $response;
  262.     }
  263.     #[Route(
  264.         name'setMainImage'
  265.         path'/set-main-mage',
  266.     )]
  267.     public function setMainImage(Request $request): Response
  268.     {
  269.         // die;
  270.         $find $this->entityManager->getRepository(Products::class)->findAll();
  271.         $i 0;
  272.         foreach($find as $product){
  273.             if(count($product->getMedia()) > && $product->getMainMedia() == null){
  274.                 $i++;
  275.                 // $product->setMainMedia($product->getMedia()[0]);
  276.                 // $this->entityManager->persist($product);
  277.             }
  278.             if($product->getSiteProduct() != null){
  279.                 // $product->setName($product->getSiteProduct()->getName());
  280.                 // $this->entityManager->persist($product);
  281.             }
  282.         }
  283.         $this->entityManager->flush();
  284.         echo $i;
  285.         // echo count( $find);
  286.         die;
  287.     }
  288.     #[Route(
  289.         name'getPrices'
  290.         path'/get-prices',
  291.     )]
  292.     public function getPricesEntityManagerInterface $entityManagerRequest $request): Response
  293.     {
  294.         // die;
  295.         $category = [];
  296.         // echo '<pre>';
  297.         // print_r($request->query->all());
  298.         // die;
  299.         $category $request->query->get('category');
  300.         $products $entityManager->getRepository(Products::class)->findBy(['show' => true]);
  301.         // if(!empty( $category_id)){
  302.         //     $query = $entityManager->getRepository(Category::class)->find($category_id);
  303.         //     $categories[] = $query;
  304.         // }else{
  305.         $categories $entityManager->getRepository(Category::class)->findBy([], ['sort' => 'ASC']);
  306.         // }
  307.         $catArr = [];
  308.         foreach($categories as $cat){
  309.             if( !empty($category) ){
  310.                 if(in_array$cat->getId(), $category) ){
  311.                     $catArr[$cat->getId()] = [
  312.                         'name' => $cat->getName(),
  313.                         'products' => []
  314.                     ];
  315.                 }
  316.             }else{
  317.                 $catArr[$cat->getId()] = [
  318.                     'name' => $cat->getName(),
  319.                     'products' => []
  320.                 ];
  321.             }
  322.                 
  323.         }
  324.         foreach($products as $prod){
  325.             foreach($prod->getCategory() as $prodCat){
  326.                 if(isset($catArr[$prodCat->getId()]))
  327.                     $catArr[$prodCat->getId()]['products'][] = $prod;
  328.             }
  329.         }
  330.         $spreadsheet = new Spreadsheet();
  331.         // Get active sheet - it is also possible to retrieve a specific sheet
  332.         $sheet $spreadsheet->getActiveSheet();
  333.     
  334.         // Set cell name and merge cells
  335.         // $sheet->setCellValue('A1', 'Крамар ціни');
  336.         $sheet->getRowDimension(1)->setRowHeight(90);
  337.         $sheet->getColumnDimension('A')->setWidth(50);
  338.         $sheet->getColumnDimension('B')->setWidth(10);
  339.         $sheet->getColumnDimension('C')->setWidth(30);
  340.         $sheet->getColumnDimension('D')->setWidth(50);
  341.         $sheet->getColumnDimension('E')->setWidth(60);
  342.         $sheet->getColumnDimension('G')->setWidth(60);
  343.         // Set cell alignment and font weight
  344.         $styleArray = [
  345.             'alignment' => [
  346.                 'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
  347.                 'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
  348.             ],
  349.             'font' => [
  350.                 'bold' => true,
  351.             ],
  352.         ];
  353.         $sheet->getStyle('B1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  354.         $sheet->getStyle('C1')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  355.         $sheet->getStyle('A:A')->applyFromArray($styleArray)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  356.         $sheet->mergeCells('A1:B1');
  357.         // Add image to worksheet
  358.         $imgPath 'logo.png';
  359.         $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  360.         $drawing->setPath($imgPath);
  361.         $drawing->setCoordinates('A1'); // Set coordinates
  362.         $drawing->setWidth(200); // Set width
  363.         $drawing->setHeight(100); // Set height
  364.         $drawing->setWorksheet($sheet);
  365.         
  366.         $sheet->setCellValue('C1''https://felso.com.ua');
  367.         // $sheet->setCellValue('C1', '');
  368.         
  369.         $sheet->mergeCells('A2:G2');
  370.         $sheet->mergeCells('A3:G3');
  371.         $sheet->setCellValue('A2''Адреса компанії: м.Львів, вул.Манастирського 2 ');
  372.         $sheet->setCellValue('A3''Номер телефону   +38 (068) 844-11-44 +38 (073) 844-11-44');
  373.         // $sheet->setCellValue('D3', 'При замовленні від 0 до 100 кг. однієї позиції')->getStyle('D3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  374.         // $sheet->setCellValue('E3', 'При замовленні від 100 до 500 кг. однієї позиції')->getStyle('E3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  375.         // $sheet->setCellValue('F3', 'При замовленні від 500 до 1 тонни однієї позиції')->getStyle('F3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  376.         // $sheet->setCellValue('G3', 'При замовленні від 1 тонни')->getStyle('G3')->applyFromArray($styleArray)->getAlignment()->setWrapText(true);
  377.     
  378.         // Set column names
  379.         $columnNames = [
  380.             'Назва',
  381.             'Артикул',
  382.             '',
  383.             'характеристики',
  384.             'комплектація',
  385.             'Ціна',
  386.             'Посилання',
  387.             // 'Гурт 2',
  388.             // 'Гурт 1',
  389.             // 'VIP',
  390.         ];
  391.         $columnLetter 'A';
  392.         foreach ($columnNames as $columnName) {
  393.             // Allow to access AA column if needed and more
  394.             $sheet->setCellValue($columnLetter.'4'$columnName)->getStyle($columnLetter.'4')->applyFromArray($styleArray);
  395.             $columnLetter++;
  396.         }
  397.         $row 5;
  398.         foreach($catArr as $key => $category){
  399.             $sheet->setCellValue("A{$row}"$category['name'])->mergeCells("A{$row}:G{$row}");
  400.             $sheet->getStyle("A{$row}")->applyFromArray($styleArray);
  401.             $row++;
  402.             if(count($category['products']) > 0)
  403.                 foreach ($category['products'] as $product) {
  404.                     /** Характеристики */
  405.                     $params '';
  406.                     foreach($product->getAttributeItems() as $attributeItems){
  407.                         $params .= $attributeItems->getAttribute()->getName() . ' - ' $attributeItems->getName() . "\n";
  408.                     }
  409.                     /** Комплектація */
  410.                     $productComplact '';
  411.                     foreach($product->getProductInfos() as $productInfos){
  412.                         $productComplact .= $productInfos->getName() . "\n";
  413.                     }
  414.                     $columnLetter++;
  415.                     
  416.                     $sheet->getRowDimension($row)->setRowHeight(100*0.75); // переведення 100px в пункти
  417.                     $sheet->setCellValue('A'.$row$product->getName());
  418.                     $sheet->getStyle('A' $row)->getAlignment()->setWrapText(true);
  419.                     $sheet->setCellValue('B'.$row$product->getArticle());
  420.                     $sheet->getStyle('B' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  421.                     // $sheet->setCellValue('C'.$row, $product->getPrice());
  422.                     /** Характеристики */
  423.                     $sheet->setCellValue('D'.$rowstrip_tags($params) );
  424.                     $sheet->getStyle('D' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  425.                     
  426.                     $sheet->setCellValue('E'.$row$productComplact);
  427.                     $sheet->getStyle('E' $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  428.                     $sheet->setCellValue('F'.$row$product->getPrice());
  429.                     $sheet->setCellValue('G'.$row'https://felso.com.ua/product/' $product->getId());
  430.                     // $sheet->getStyle('C' . $row)->getAlignment()->setWrapText(true); // Вмикає перенесення тексту
  431.                     // $sheet->getRowDimension($row)->setRowHeight(-1); // Автоматична висота рядка
  432.                     if($product->getMainMedia() != null){
  433.                         
  434.                         // Отримуємо рік і місяць із дати завантаження
  435.                         $uploadDate $product->getMainMedia()->getUploadTimestamp();
  436.                         $year $uploadDate->format('Y');
  437.                         $month $uploadDate->format('m');
  438.                     
  439.                         // Формуємо повний шлях до зображення
  440.                         $imgPath $_SERVER["DOCUMENT_ROOT"] . '/media/' $year '/' $month '/90_px_' $product->getMainMedia()->filePath;
  441.                         if(file_exists($imgPath)){
  442.                         // $ = 'logo.png';
  443.                             $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
  444.                             $drawing->setPath($imgPath);
  445.                             $drawing->setCoordinates('C'.$row); // Set coordinates
  446.                             $drawing->setWidth(150); // Set width
  447.                             $drawing->setHeight(100); // Set height
  448.                             $drawing->setWorksheet($sheet);
  449.                         }
  450.                     
  451.                     }
  452.                     $row++;
  453.                 }
  454.         }
  455.         
  456.         $writer = new Xlsx($spreadsheet);
  457.         $fileName 'products_' date('YmdHis') . '.xlsx';
  458.         $writer->save($fileName);
  459.         // Вивантаження файлу
  460.         // Set the content-type:
  461.         header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  462.         header('Content-Length: ' filesize($fileName));
  463.         readfile($fileName); // send file
  464.         unlink($fileName); // delete file
  465.         return new Response();
  466.     }
  467.     #[Route(
  468.         name'addAttrCategory'
  469.         path'/add-attr-category',
  470.     )]
  471.     public function addAttrCategoryEntityManagerInterface $entityManager ){
  472.         $products $entityManager->getRepository(Products::class)->findBy(['show' => true]);
  473.         foreach( $products as $product ){
  474.             if(count($product->getAttributeItems())  > ){
  475.                 foreach($product->getAttributeItems() as $attrItem){
  476.                     $attibute $attrItem->getAttribute();
  477.                     foreach($product->getCategory() as $category){
  478.                         $attrItem->addCategory($category);
  479.                         $attibute->addCategory($category);
  480.                         $entityManager->persist($attrItem);
  481.                         $entityManager->persist($attibute);
  482.                     }
  483.                 }
  484.             }
  485.             
  486.         }
  487.         $entityManager->flush();
  488.         echo 1111;
  489.         die;
  490.     }   
  491.     #[Route(
  492.         name'getDublicate'
  493.         path'/get-dublicate',
  494.     )]
  495.     public function getDublicateEntityManagerInterface $entityManagerRequest $request): Response
  496.     {
  497.         set_time_limit(0);
  498.         $duplicates $entityManager->createQueryBuilder()
  499.         ->select('p.article')
  500.         ->from(Products::class, 'p')
  501.         ->where('p.deleted = FALSE')
  502.         ->groupBy('p.article')
  503.         ->having('COUNT(p.article) > 1')
  504.         ->getQuery()
  505.         ->getResult();
  506.         $i  0;
  507.         foreach ($duplicates as $duplicate) {
  508.             // echo $duplicate['article'] . "<br>";
  509.             $products $entityManager->getRepository(Products::class)
  510.                 ->findBy(['article' => $duplicate['article'], 'deleted' => false]);
  511.             
  512.             // Keep the first product and remove the rest
  513.             $deleted true;
  514.             $isDeleted false;
  515.             foreach ($products as $product) {
  516.                 echo $product->getArticle();
  517.                 if(count($product->getOrderProducts()) > 0){
  518.                     $deleted false;
  519.                     echo ' - - false';
  520.                 }elseif(count$product->getCategory()) > OR count$product->getAttributeItems()) > 0){
  521.                     $deleted false;
  522.                     echo '- false';
  523.                 }else{
  524.                     $deleted true;
  525.                     echo ' - true';
  526.                 }
  527.                 if($deleted AND !$isDeleted){
  528.                     $i++;
  529.                     $isDeleted true;
  530.                     $product->setDeleted(true);
  531.                     $product->setDescription('delete dublicate product ' date('Y-m-d H:i:s'));
  532.                     $entityManager->persist$product );
  533.                 }
  534.                 
  535.                 
  536.                 echo '<br>';
  537.             }
  538.             if($i === 200){
  539.                 $entityManager->flush();
  540.                 $i=0;
  541.             }
  542.         }
  543.         $entityManager->flush();
  544.         die;
  545.     }
  546.     #[Route(
  547.         name'importProductFromExcel'
  548.         path'/product/import-from-excel',
  549.     )]
  550.     function importProductFromExcel(EntityManagerInterface $entityManagerTranslit $translit){
  551.         echo '<pre>';
  552.         $inputFileName 'products.xlsx';
  553.         $spreadsheet IOFactory::load($inputFileName);
  554.         $sheet $spreadsheet->getActiveSheet();
  555.         $i 0;
  556.         $category = [];
  557.         $attributes = [];
  558.         $products = [];  
  559.         // $url = $sheet->getDrawingCollection();
  560.         // $sheet->getCell('C1')->getValue()
  561.         // echo '<pre>';
  562.         // print_r($url);
  563.         // var_dump($url); die;
  564.         // die;
  565.         foreach ($sheet->getRowIterator() as $row) {
  566.             $cellIterator $row->getCellIterator();
  567.             $cellIterator->setIterateOnlyExistingCells(FALSE);
  568.             $data = [];
  569.             foreach ($cellIterator as $cell) {
  570.             //     echo '<pre>';   
  571.             // print_r($cell->getWorksheet()->getDrawingCollection());
  572.                 $value $cell->getValue();
  573.                 // $drawing = $cell->getWorksheet()->getDrawingCollection();
  574.                 // $hyperlink = $cell->getHyperlink();
  575.                 // if ($hyperlink) {
  576.                 //     $value = $hyperlink->getUrl();
  577.                 // }
  578.                 $data[] = $value;
  579.             }
  580.             // Assuming your Excel file has columns: id, name, price
  581.             // echo '<pre>';
  582.             if($i==0){
  583.                 foreach($data as $k => $d){
  584.                     if($k >= AND !empty($d)){
  585.                         $n str_replace(':'''$d);
  586.                         $attributes[$k] = [
  587.                             'name' => trim($n),
  588.                             'slug' => $translit->convert(trim($n)),
  589.                             'items' => []
  590.                         ];
  591.                     }
  592.                 }
  593.                 // print_r($data);
  594.                 $i++;
  595.                 continue;
  596.             }
  597.             
  598.             foreach($data as $k => $d){
  599.                 if($k >= AND !empty($d)){
  600.                     $attributes[$k]['items'][$translit->convert(trim($d))] = trim($d);
  601.                 }
  602.             }
  603.             if(!empty($data[3]))
  604.                 $category$translit->convert(trim$data[4] )) ] = trim$data[4] );
  605.       
  606.             $products[$i]['data'] = $data;
  607.            
  608.             $i++;
  609.         }
  610.         // print_r($category);
  611.         // print_r($attributes);
  612.         // die;
  613.         // die;
  614.         $findCategory $entityManager->getRepository(Category::class)->findAll();
  615.         $findAttributes $entityManager->getRepository(Attributes::class)->findAll();
  616.         foreach($category as $slug =>  $c){
  617.             $find false;
  618.             foreach($findCategory as $fCat){
  619.                 if($fCat->getName() == $c){
  620.                     $find true;
  621.                 }
  622.             }
  623.             if(!$find){
  624.                 $entityCat = new Category();
  625.                 $entityCat->setName($c);
  626.                 $entityCat->setSlug($slug);
  627.                 $entityCat->setMain(true);
  628.                 $entityCat->setType('category');
  629.                 $entityManager->persist$entityCat );
  630.                 
  631.             }
  632.         }
  633.         // echo '<pre>';
  634.         // print_r($attributes); die;
  635.         foreach($attributes as $name => $attrs){
  636.             $attr false;
  637.             $entityAttr '';
  638.             foreach($findAttributes as $fAttr){
  639.                 if($fAttr->getName() == $attrs['name']){
  640.                     $entityAttr $fAttr;
  641.                     $attr true;
  642.                     foreach($attrs['items'] as $i => $a){
  643.                         foreach($fAttr->getAttributeItems() as $f_a_i){
  644.                             if($f_a_i->getName() == $a){
  645.                                 unset($attrs['items'][$i]);
  646.                             }
  647.                         }
  648.                     }
  649.                 }
  650.             }
  651.              
  652.             if(!$attr){
  653.                 $entityAttr = new Attributes();
  654.                 $entityAttr->setName($attrs['name']);
  655.                 $entityAttr->setSlug($attrs['slug']);
  656.                 $entityManager->persist$entityAttr );
  657.             }
  658.             if(count($attrs['items']) > 0){
  659.                 foreach($attrs['items'] as $i => $a){
  660.                     $entityAttrItem = new AttributeItems();
  661.                     $entityAttrItem->setName($a);
  662.                     $entityAttrItem->setSlug($i);
  663.                     $entityAttrItem->setAttribute($entityAttr);
  664.                     $entityManager->persist$entityAttrItem );
  665.                 }
  666.             }
  667.             
  668.         }
  669.         // die;
  670.         $entityManager->flush();
  671.         // die;
  672.         $findCategory $entityManager->getRepository(Category::class)->findAll();
  673.         $findAttributes $entityManager->getRepository(Attributes::class)->findAll();
  674.         $findAttributesItems $entityManager->getRepository(AttributeItems::class)->findAll();
  675.         $findProducts $entityManager->getRepository(Products::class)->findAll();
  676.         $measurmentUnit $entityManager->getRepository(MeasurmentUnit::class)->findOneBy(['name' => 'Штука']);
  677.         // print_r($products); die;    
  678.         foreach($products as $product){
  679.             $search false;
  680.             $findProduct '';
  681.             foreach($findProducts  as $f_p){
  682.                 if($f_p->getArticle() == $product['data'][1]){
  683.                     $search true;
  684.                     $findProduct $f_p;
  685.                 }
  686.             }
  687.             $price floatval(trim(str_replace('грн''' $product['data'][2])));
  688.             if(!$search and !empty($product['data'][0])){
  689.                 $newProduct = new Products();
  690.                 $newProduct->setName($product['data'][0]);
  691.                 $newProduct->setArticle($product['data'][1]);
  692.                 $newProduct->setPrice($price);
  693.                 $newProduct->setShow(true);
  694.                 $findProduct->setBalance(1);
  695.                 // $newProduct->setPackingType($product['data'][7] . ' | ' . $product['data'][7]);
  696.                 $newProduct->getMeasurementUnit($measurmentUnit);
  697.                 foreach($product['data'] as $k => $d){
  698.                     if($k >= AND !empty($d)){
  699.                         foreach($findAttributesItems as $ati){
  700.                             if($ati->getName() == trim($d)){
  701.                                 $newProduct->addAttributeItem($ati);
  702.                             }
  703.                         }
  704.                     }
  705.                     if($k == AND !empty($d)){
  706.                         foreach ($findCategory as $f_c){
  707.                             if($f_c->getName() == trim($d)){
  708.                                 $newProduct->addCategory($f_c);
  709.                             }
  710.                         }
  711.                     }
  712.                 }
  713.                 $entityManager->persist$newProduct );
  714.             }else{
  715.                 echo $findProduct->getName() . "<br>";
  716.                 $findProduct->setPrice($price);
  717.                 $findProduct->setShow(true);
  718.                 $findProduct->setBalance(1);
  719.                 foreach($product['data'] as $k => $d){
  720.                     $searvhAttr false;
  721.                     if($k >= AND !empty($d)){
  722.                         foreach( $findProduct->getAttributeItems() as $productAttrItem){
  723.                             if( $productAttrItem->getName() ==  $d){
  724.                                 $searvhAttr true;
  725.                             }
  726.                         }
  727.                         if(!$searvhAttr){
  728.                             foreach($findAttributesItems as $ati){
  729.                                 if($ati->getName() == trim($d)){
  730.                                     $findProduct->addAttributeItem($ati);
  731.                                 }
  732.                             }
  733.                             $entityManager->persist$findProduct );
  734.                         }
  735.                     }
  736.                 }
  737.                 // if(empty( $findProduct->getCategory() )){
  738.                     foreach($product['data'] as $k => $d){
  739.                         if($k == AND !empty($d)){
  740.                             foreach ($findCategory as $f_c){
  741.                                 if($f_c->getName() == trim($d)){
  742.                                     echo  $f_c->getName(). "<br>";
  743.                                     $findProduct->addCategory($f_c);
  744.                                 }
  745.                             }
  746.                         }
  747.                     }
  748.                 // }
  749.                 
  750.                 $entityManager->persist$findProduct );
  751.                 
  752.             }
  753.         }
  754.         $entityManager->flush();
  755.         // $findProducts = $entityManager->getRepository(Products::class)->findAll();
  756.         // foreach ($sheet->getDrawingCollection() as $in =>  $drawing) {
  757.         //         // print_r($drawing->getCoordinates());
  758.         //         $c = str_replace('E', '', $drawing->getCoordinates() );
  759.         //         // print_r($sheet->getCell( "B$c" )->getValue());
  760.         //         // echo "<br>";
  761.         //         foreach($findProducts  as $f_p){
  762.         //             if($f_p->getArticle() == $sheet->getCell( "B$c" )->getValue()){
  763.         //                 $zipReader = fopen($drawing->getPath(),'r');
  764.         //                 $imageContents = '';
  765.         //                 while (!feof($zipReader)) {
  766.         //                     $imageContents .= fread($zipReader,1024);
  767.         //                 }
  768.         //                 fclose($zipReader);
  769.         //                 $extension = $drawing->getExtension();
  770.         //                 $imageBase64 = base64_encode($imageContents);
  771.         //                 $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' .  $f_p->getId();
  772.         //                 $imageFile = new \CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
  773.         //                 echo  $url; echo '<br>';
  774.         //                 // Set up the cURL request
  775.         //         // Ініціалізуємо cURL-сесію
  776.         //                 $ch = curl_init();
  777.         //                 // Встановлюємо параметри запиту
  778.         //                 curl_setopt($ch, CURLOPT_URL, $url);
  779.         //                 curl_setopt($ch, CURLOPT_POST, 1);
  780.         //                 curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
  781.         //                 // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  782.         //                 // Execute the cURL request
  783.         //               // Виконуємо запит
  784.         //                 $response = curl_exec($ch);
  785.         //                 // $json = json_decode($response);
  786.         //                 // Перевіряємо наявність помилок
  787.         //                 if (curl_errno($ch)) {
  788.         //                     echo 'Error:' . curl_error($ch);
  789.         //                 }
  790.         //                 // Закриваємо cURL-сесію
  791.         //                 curl_close($ch);
  792.         //                 die;
  793.             
  794.         //             }
  795.         //         }
  796.        
  797.             
  798.         //         // $zipReader = fopen($drawing->getPath(),'r');
  799.         //         // $imageContents = '';
  800.         
  801.         //         // while (!feof($zipReader)) {
  802.         //         //     $imageContents .= fread($zipReader,1024);
  803.         //         // }
  804.         //         // fclose($zipReader);
  805.         //         // $extension = $drawing->getExtension();
  806.         //         // $imageBase64 = base64_encode($imageContents);
  807.         //         // $url = 'https://api-felso-brand.inneti.net/api/media_objects?product=' .  $entity->getId();
  808.         //         // $imageFile = new CURLFile($imageBase64, 'image/' . $extension, 'image.' . $extension);
  809.         //         // // Set up the cURL request
  810.         //         // $ch = curl_init();
  811.         //         // curl_setopt($ch, CURLOPT_URL, $url);
  812.         //         // curl_setopt($ch, CURLOPT_POST, 1);
  813.         //         // curl_setopt($ch, CURLOPT_POSTFIELDS, ['image' => $imageFile]);
  814.         //         // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  815.             
  816.         //         // // Execute the cURL request
  817.         //         // $response = curl_exec($ch);
  818.             
  819.         //         // // Close cURL resource
  820.         //         // curl_close($ch);
  821.             
  822.         //     // }
  823.         //     // $myFileName = '00_Image_'.++$i.'.'.$extension;
  824.         //     // file_put_contents($myFileName,$imageContents);
  825.         // }
  826.         // $entityManager->flush();
  827.             echo 111;
  828.         die;
  829.         // return $this->redirectToRoute('app_homepage');
  830.     }
  831.     public function imgCurl($entity$imgUrl$type='img'){
  832.                 // continue;
  833.                 // $img = file_get_contents($imgUrl);
  834.                 $url 'https://api-felso.inneti.net/api/media_objects';
  835.                 if( $type == 'img' )
  836.                     $url .= '?product=' .  $entity->getId();
  837.                 // echo " $url<br><br>";
  838.                 // Файл, який ви хочете відправити
  839.                 $file_path $imgUrl;
  840.                 // Ініціалізуємо cURL-сесію
  841.                 $ch curl_init();
  842.                 // Встановлюємо параметри запиту
  843.                 curl_setopt($chCURLOPT_URL$url);
  844.                 curl_setopt($chCURLOPT_POST1);
  845.                 curl_setopt($chCURLOPT_POSTFIELDS, [
  846.                     'file' => new \CURLFile($file_path)
  847.                 ]); 
  848.                 echo '----';
  849.                 // Виконуємо запит
  850.                 $response curl_exec($ch);
  851.                 echo '|||';
  852.                 // $json = json_decode($response);
  853.                 // Перевіряємо наявність помилок
  854.                 if (curl_errno($ch)) {
  855.                     echo '2Error:' curl_error($ch); die;
  856.                 }
  857.                 // Закриваємо cURL-сесію
  858.                 curl_close($ch);
  859.                 return $response;
  860.     }
  861.     public function newImg($findProducts,  $pathProductsDir$pathNew, ){
  862.         echo $findProducts->getName() . "+++<br>"
  863.         $uploadTimestamp = new  \DateTime();
  864.         $mediaObject = new MediaObject();
  865.         // $mediaObject->file = $uploadedFile;
  866.         $mediaObject->uploadTimestamp $uploadTimestamp;
  867.         $mediaObject->filePath $findProducts->getId().$pathProductsDir;
  868.         $mediaObject->setName('product_img');
  869.         $mediaObject->setProduct($findProducts);
  870.         $this->entityManager->persist$mediaObject );
  871.         $this->entityManager->flush();
  872.         $year date('Y');
  873.         $month date('m');
  874.         $documentRoot $this->kernel->getProjectDir() . '/public/media';
  875.         $path $documentRoot "/$year/$month/";
  876.         $sizes = [902307001200];
  877.         $manager = new ImageManager(
  878.             new \Intervention\Image\Drivers\Gd\Driver() 
  879.         );
  880.         foreach($sizes as $s){
  881.             $image $manager->read($pathNew);
  882.             $image->scale(width$s);
  883.             $newName "{$s}_px_" .  $findProducts->getId().$pathProductsDir;
  884.             $image->save($path $newName );
  885.             $newMedia = new MediaObject();
  886.             $newMedia->filePath $newName;
  887.             $newMedia->setName("resize-$s");
  888.             $newMedia->setSize($s);
  889.             $newMedia->setResizeImgParent($mediaObject);
  890.             $this->entityManager->persist($newMedia);
  891.             $this->entityManager->flush();
  892.         
  893.         }
  894.         $findProducts null;
  895.         return $mediaObject;
  896.     }
  897.     #[Route(
  898.         name'importProductImg'
  899.         path'/product/import-img',
  900.     )]
  901.     function importProductImg(EntityManagerInterface $entityManagerTranslit $translitMediaObjectsRepository $mediaObjectsRepository, ?\DateTimeInterface $uploadTimestamp){
  902.         echo '<pre>';
  903.         $path 'products_img';
  904.         $nextPaths scandir($path);
  905.         print_r($nextPaths);
  906.         foreach($nextPaths as $nextPath){
  907.             if($nextPath == '.' OR $nextPath == '..')
  908.                 continue;
  909.             $pathCat "$path/$nextPath";
  910.             $pathCatDirs scandir($pathCat);
  911.             
  912.             foreach($pathCatDirs as $pathCatDir){
  913.                 if($pathCatDir == '.' OR $pathCatDir == '..')
  914.                     continue;
  915.                 // if($pathCatDir == 'ID1250')
  916.                 //     die;
  917.                 // print_r($pathCatDir); die;
  918.                 file_put_contents('import-img.log'$pathCatDir "\n"FILE_APPEND);
  919.                 $pathProducts "$pathCat/$pathCatDir";
  920.                 $pathProductsDirs scandir($pathProducts);
  921.                 echo "<b>$pathCatDir</b><br>";
  922.                 $findProducts $entityManager->getRepository(Products::class)->findOneBy(['article' => $pathCatDir]);
  923.                 
  924.                 if($findProducts ){
  925.                     echo "<b>" $findProducts->getName() . "</b><br>";
  926.                     foreach($findProducts->getMedia() as $m){
  927.                         echo $m->getId() . "<br>";
  928.                         $findProducts->removeMedium($m);
  929.                     }
  930.                     $mainMedia $findProducts->getMainMedia();
  931.                     if($mainMedia){
  932.                         echo "main - " $mainMedia->getId() . "<br>";
  933.                         $mainMedia->removeMainProduct($findProducts);
  934.                         $entityManager->persist$findProducts );
  935.                     }
  936.                     $MainMediaHover $findProducts->getMainMediaHover();
  937.                     if($MainMediaHover){
  938.                         echo "hover - main - " $MainMediaHover->getId() . "<br>";
  939.                         $MainMediaHover->removeProductsHover($findProducts);
  940.                         $entityManager->persist$MainMediaHover );
  941.                     }
  942.                     $entityManager->persist$findProducts );
  943.                     $entityManager->flush();
  944.                    
  945.                 }else{
  946.                     continue;
  947.                 }
  948.                 // echo $findProducts->getName();
  949.                 echo "<br>";
  950.                 foreach($pathProductsDirs as $pathProductsDir){
  951.                     if($pathProductsDir == '.' OR $pathProductsDir == '..')
  952.                         continue;
  953.                     $pathImg =  $this->kernel->getProjectDir() . "/public/$pathProducts/$pathProductsDir";
  954.                     $pathNew $this->kernel->getProjectDir() . "/public/media/" date('Y') . "/" date('m') . "/".$findProducts->getId()."$pathProductsDir";
  955.                     echo $pathImg "---<br>";
  956.                     echo $pathNew "---<br>";
  957.                     
  958.                     if($pathProductsDir == '1_0.png'){
  959.                         if(copy($pathImg$pathNew)){
  960.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  961.                             $findProducts->setMainMedia($mediaObject);
  962.                             $entityManager->persist$findProducts );
  963.                            
  964.                         }
  965.                     }elseif($pathProductsDir == '1_1.png'){
  966.                         if(copy($pathImg$pathNew)){
  967.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  968.                             $findProducts->setMainMediaHover($mediaObject);
  969.                             $entityManager->persist$findProducts );
  970.                         }
  971.                        
  972.                     }else{
  973.                         if(copy($pathImg$pathNew)){
  974.                             $mediaObject $this->newImg($findProducts$pathProductsDir$pathNew);
  975.                             // $findProducts->setMainMediaHover($mediaObject);
  976.                             $entityManager->persist$findProducts );
  977.                         } 
  978.                     }
  979.                         
  980.                 }
  981.                 $entityManager->flush();
  982.                 $entityManager->clear();
  983.                 $findProducts '';
  984.                 // die;
  985.             }
  986.             
  987.         }
  988.         // print_r($nextPaths);
  989.         die;
  990.         
  991.     }
  992.     #[Route('/products/export-xml'name'export_xml')]
  993.     public function exportXml(EntityManagerInterface $entityManagerRequest $request): Response
  994.     {
  995.         $_get $request->query->all();
  996.         $categoryId = isset($_get['category']) && !empty($_get['category']) ? $_get['category'] : null;
  997.         // echo '<pre>';
  998.         // var_dump($categoryId);
  999.         // die;
  1000.         $categories $entityManager->getRepository(Category::class)->findAll();
  1001.      
  1002.         $products $entityManager->getRepository(Products::class)->findAll();
  1003.         $xml = new \SimpleXMLElement('<yml_catalog/>');
  1004.         $xml->addAttribute('date'date('Y-m-d H:i'));
  1005.         $shop $xml->addChild('shop');
  1006.         $shop->addChild('name''2PR');
  1007.         $shop->addChild('company''2PR');
  1008.         $shop->addChild('url''https://felso.inneti.net/');
  1009.         $shop->addChild('phone''068-844-11-44');
  1010.         $shop->addChild('platform''Store');
  1011.         $shop->addChild('version''2.1.0.1');
  1012.         // $currencies = $shop->addChild('currencies');
  1013.         // $currencies->addChild('currency')->addAttribute('id', 'UAH')->addAttribute('rate', '1');
  1014.         // Додаємо категорії
  1015.         $categoriesXml $shop->addChild('categories');
  1016.         foreach ($categories as $category) {
  1017.             if($categoryId !== null AND !in_array($category->getId(), $categoryId)){
  1018.                 continue;
  1019.             }
  1020.             $categoryXml $categoriesXml->addChild('category'$category->getName());
  1021.             $categoryXml->addAttribute('id'$category->getId());
  1022.             if ($category->getParent()) {
  1023.                 $categoryXml->addAttribute('parentId'$category->getParent()->getId());
  1024.             }
  1025.         }
  1026.                 // Додаємо продукти
  1027.                 $offers $shop->addChild('offers');
  1028.                 foreach ($products as $product) {
  1029.                     if($categoryId !== null){
  1030.                         $search false;
  1031.                         foreach($product->getCategory() as $cat){
  1032.                             if( in_array($cat->getId() , $categoryId) )
  1033.                                 $search true;
  1034.                         }
  1035.                         if(!$search)
  1036.                             continue;
  1037.                     }
  1038.                     $cat '';
  1039.                     if($product->getCategory() != null AND count($product->getCategory()) > 0)
  1040.                         $cat =  $product->getCategory()[0]->getId();
  1041.                     $img '';
  1042.                     if($product->getMainMedia() != null){
  1043.                         
  1044.                             // Отримуємо рік і місяць із дати завантаження
  1045.                             $uploadDate $product->getMainMedia()->getUploadTimestamp();
  1046.                             $year $uploadDate->format('Y');
  1047.                             $month $uploadDate->format('m');
  1048.                         
  1049.                             // Формуємо повний шлях до зображення
  1050.                             $img 'https://api-felso-brand.inneti.net/media/' $year '/' $month '/' $product->getMainMedia()->filePath;
  1051.                         
  1052.                     }
  1053.                         // $img = 
  1054.                     $offer $offers->addChild('offer');
  1055.                     $offer->addAttribute('id'$product->getId());
  1056.                     $offer->addAttribute('available'$product->isShow() ? 'true' 'false');
  1057.                     $offer->addChild('url''https://felso.inneti.net/product/' $product->getId());
  1058.                     $offer->addChild('price'$product->getPrice());
  1059.                     $offer->addChild('currencyId''UAH');
  1060.                     $offer->addChild('categoryId',  $cat );
  1061.                     $offer->addChild('picture'$img);
  1062.                     // $offer->addChild('vendor', $product->getVendor());
  1063.                     $offer->addChild('vendorCode'$product->getArticle());
  1064.                     $offer->addChild('name'$product->getName());
  1065.                     $offer->addChild('description'htmlspecialchars($product->getDescription()));
  1066.                 }
  1067.         
  1068.                 // Конвертація у XML
  1069.                 $response = new Response($xml->asXML());
  1070.                 $response->headers->set('Content-Type''application/xml');
  1071.         
  1072.                 return $response;
  1073.     }
  1074. }