<commit_before><?php
/**
 * Created by PhpStorm.
 * User: anthony
 * Date: 02/06/16
 * Time: 19:56
 */

namespace Dropshippers\APIBundle\Services;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Dropshippers\APIBundle\Entity\LocalPsProduct;
use Dropshippers\APIBundle\Entity\Shop;
use Dropshippers\APIBundle\Entity\LocalProductImage;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

class Prestashop16Service
{
    private $doctrine;

    public function __construct(Registry $doctrine)
    {
        //injecting doctrine at service construction
        $this->doctrine = $doctrine;
    }

    public function registerLocalProduct(Request $request, Shop $shop)
    {
        //initiate variables and services
        $em                 = $this->doctrine->getManager();
        $json               = json_decode($request->getContent());
        $productRepository  = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $imageRepository    = $this->doctrine->getRepository("DropshippersAPIBundle:LocalProductImage");
        $categoryRepository = $this->doctrine->getRepository('DropshippersAPIBundle:Category');

        //loop on json products
        foreach ($json as $product){
            //check if product already exists
            $entity = $productRepository->findOneBy(array("productId" => $product->id_product, "shop" => $shop));

            //if no product was found, create a new product, for no duplication
            if (!$entity) {
                $entity     = new LocalPsProduct();
                $entity->setCreatedAt(new \DateTime());
            }

            //feed the fields
            $entity->setProductId($product->id_product);
            $entity->setName($product->name);
            $entity->setActive($product->active);
            $entity->setPrice($product->price);
            $entity->setReference($product->reference);
            $entity->setEcotax($product->ecotax);
            $entity->setWeight($product->weight);
            $entity->setQuantity($product->quantity);
            $entity->setDescriptionHtml($product->description);
            $entity->setAvailableOrder($product->available_for_order);
            $entity->setUpdatedAt(new \DateTime());
            $entity->setShop($shop);
            $entity->setShopOrigin($shop);
            $entity->setDropshippersRef($this->generateRandomRef($shop->getName()));

            //if image link is set, create new image
            if (isset($product->image_link)){
                $image = $imageRepository->findOneBy(array('link' => $product->image_link));
                if (!$image){
                    $image  = new LocalProductImage();
                    $image->setCreatedAt(new \DateTime());
                    $entity->addImage($image);
                    $image->setLocalProduct($entity);
                    $image->setType("link");
                }
                $image->setUpdatedAt(new \DateTime());
                $image->setLink($product->image_link);
            }

            //set categories
            if (isset($product->categories)){
                foreach($product->categories as $category){
                    $categoryObj = $categoryRepository->find($category);
                    if ($categoryObj){
                        $entity->addCategory($categoryObj);
                    }
                }
            }

            //persist entity
            $em->persist($entity);
            $em->flush();
        }

        return TRUE;
    }

    public function getShopLocalProducts($shop)
    {
        //initiate variables
        $tab = array();
        $productRepository  = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $entities           = $productRepository->findBy(array("shop" => $shop));

        //sort entities in array to separate external and internal products
        foreach($entities as $entity){
            if ($shop->getId() != $entity->getShopOrigin()->getId()){
                $tab["external"][] = $entity;
            } else {
                $tab["local"][] = $entity;
            }
        }
        return $tab;
    }

    public function getCheckProductPresence(Shop $shop, $id)
    {
        //initiate variables
        $productRepository  = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $entity             = $productRepository->findOneBy(array("productId" => $id, "shop" => $shop));

        //return true if entity exists
        if ($entity){
            return True;
        } else {
            return False;
        }
    }
    
    public function getSharedProducts($shop)
    {
        //initiate variables
        $tab = array();
        $productRepository = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");

        //get products shared by the shop
        $products = $productRepository->findBy(array("shopOrigin" => $shop));

        //feed array with products
        foreach ($products as $product){

            //check if the shop own the product
            if (($product->getShopOrigin()->getId()) != ($product->getShop()->getId())){
                $temp = array();
                $temp["product"]["dropshippersRef"] = $product->getDropshippersRef();
                $temp["product"]["id_local"] = $product->getProductId();
                $temp["product"]["quantity"] = $product->getQuantity();
                $temp["shop"]["name"] = $product->getShop()->getName();
                $temp["shop"]["address"] = $product->getShop()->getAddress();
                $temp["shop"]["zipcode"] = $product->getShop()->getAddressZipcode();
                $temp["shop"]["city"] = $product->getShop()->getCity();
                $tab["shared_products"][] = $temp;
            }
        }
        return $tab;
    }

    //generate random ref
    private function generateRandomRef($shopName)
    {
        $dropRef = strtoupper(substr($shopName, 0, 3)) . $this->generateRandomString(5) . "-" . $this->generateRandomString(15);
        $repository = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $flag = 1;
        while ($flag){
            $product = $repository->findOneBy(array("dropshippersRef" => $dropRef));
            if (!$product){
                $flag = 0;
            } else {
                $dropRef = strtoupper(substr($shopName, 0, 3)) . $this->generateRandomString(5) . "-" . $this->generateRandomString(15);
            }
        }
        return $dropRef;
    }

    //help to generate random ref
    private function generateRandomString($length = 10) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    // Takes a module and assigns a notification link to it
    public function registerNotificationLink($moduleId, $notificationLink)
    {
        $entityManager = $this->doctrine->getManager();
        $modulesRepository = $this->doctrine->getRepository('DropshippersAPIBundle:Module');
        $module = $modulesRepository->findOneById($moduleId);
        $module->setNotificationLink($notificationLink);
        $entityManager->persist($module);
        $entityManager->flush();
    }
}
<commit_msg>test fix<commit_after><?php
/**
 * Created by PhpStorm.
 * User: anthony
 * Date: 02/06/16
 * Time: 19:56
 */

namespace Dropshippers\APIBundle\Services;

use Doctrine\Bundle\DoctrineBundle\Registry;
use Dropshippers\APIBundle\Entity\LocalPsProduct;
use Dropshippers\APIBundle\Entity\Shop;
use Dropshippers\APIBundle\Entity\LocalProductImage;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

class Prestashop16Service
{
    private $doctrine;

    public function __construct(Registry $doctrine)
    {
        //injecting doctrine at service construction
        $this->doctrine = $doctrine;
    }

    public function registerLocalProduct(Request $request, Shop $shop)
    {
        //initiate variables and services
        $em                 = $this->doctrine->getManager();
        $json               = json_decode($request->getContent());
        $productRepository  = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $imageRepository    = $this->doctrine->getRepository("DropshippersAPIBundle:LocalProductImage");
        $categoryRepository = $this->doctrine->getRepository('DropshippersAPIBundle:Category');

        //loop on json products
        foreach ($json as $product){
            //check if product already exists
            $entity = $productRepository->findOneBy(array("productId" => $product->id_product, "shop" => $shop));

            //if no product was found, create a new product, for no duplication
            if (!$entity) {
                $entity     = new LocalPsProduct();
                $entity->setCreatedAt(new \DateTime());
            } else {
                $existingCategories = $entity->getCategories();
                foreach ($existingCategories as $category){
                    $entity->removeCategory($category);
                }
                $em->persist($entity);
                $em->flush();
            }

            //feed the fields
            $entity->setProductId($product->id_product);
            $entity->setName($product->name);
            $entity->setActive($product->active);
            $entity->setPrice($product->price);
            $entity->setReference($product->reference);
            $entity->setEcotax($product->ecotax);
            $entity->setWeight($product->weight);
            $entity->setQuantity($product->quantity);
            $entity->setDescriptionHtml($product->description);
            $entity->setAvailableOrder($product->available_for_order);
            $entity->setUpdatedAt(new \DateTime());
            $entity->setShop($shop);
            $entity->setShopOrigin($shop);
            $entity->setDropshippersRef($this->generateRandomRef($shop->getName()));

            //if image link is set, create new image
            if (isset($product->image_link)){
                $image = $imageRepository->findOneBy(array('link' => $product->image_link));
                if (!$image){
                    $image  = new LocalProductImage();
                    $image->setCreatedAt(new \DateTime());
                    $entity->addImage($image);
                    $image->setLocalProduct($entity);
                    $image->setType("link");
                }
                $image->setUpdatedAt(new \DateTime());
                $image->setLink($product->image_link);
            }

            //set categories
            if (isset($product->categories)){
                foreach($product->categories as $category){
                    $categoryObj = $categoryRepository->find($category);
                    if ($categoryObj){
                        $entity->addCategory($categoryObj);
                    }
                }
            }

            //persist entity
            $em->persist($entity);
            $em->flush();
        }

        return TRUE;
    }

    public function getShopLocalProducts($shop)
    {
        //initiate variables
        $tab = array();
        $productRepository  = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $entities           = $productRepository->findBy(array("shop" => $shop));

        //sort entities in array to separate external and internal products
        foreach($entities as $entity){
            if ($shop->getId() != $entity->getShopOrigin()->getId()){
                $tab["external"][] = $entity;
            } else {
                $tab["local"][] = $entity;
            }
        }
        return $tab;
    }

    public function getCheckProductPresence(Shop $shop, $id)
    {
        //initiate variables
        $productRepository  = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $entity             = $productRepository->findOneBy(array("productId" => $id, "shop" => $shop));

        //return true if entity exists
        if ($entity){
            return True;
        } else {
            return False;
        }
    }
    
    public function getSharedProducts($shop)
    {
        //initiate variables
        $tab = array();
        $productRepository = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");

        //get products shared by the shop
        $products = $productRepository->findBy(array("shopOrigin" => $shop));

        //feed array with products
        foreach ($products as $product){

            //check if the shop own the product
            if (($product->getShopOrigin()->getId()) != ($product->getShop()->getId())){
                $temp = array();
                $temp["product"]["dropshippersRef"] = $product->getDropshippersRef();
                $temp["product"]["id_local"] = $product->getProductId();
                $temp["product"]["quantity"] = $product->getQuantity();
                $temp["shop"]["name"] = $product->getShop()->getName();
                $temp["shop"]["address"] = $product->getShop()->getAddress();
                $temp["shop"]["zipcode"] = $product->getShop()->getAddressZipcode();
                $temp["shop"]["city"] = $product->getShop()->getCity();
                $tab["shared_products"][] = $temp;
            }
        }
        return $tab;
    }

    //generate random ref
    private function generateRandomRef($shopName)
    {
        $dropRef = strtoupper(substr($shopName, 0, 3)) . $this->generateRandomString(5) . "-" . $this->generateRandomString(15);
        $repository = $this->doctrine->getRepository("DropshippersAPIBundle:LocalPsProduct");
        $flag = 1;
        while ($flag){
            $product = $repository->findOneBy(array("dropshippersRef" => $dropRef));
            if (!$product){
                $flag = 0;
            } else {
                $dropRef = strtoupper(substr($shopName, 0, 3)) . $this->generateRandomString(5) . "-" . $this->generateRandomString(15);
            }
        }
        return $dropRef;
    }

    //help to generate random ref
    private function generateRandomString($length = 10) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    // Takes a module and assigns a notification link to it
    public function registerNotificationLink($moduleId, $notificationLink)
    {
        $entityManager = $this->doctrine->getManager();
        $modulesRepository = $this->doctrine->getRepository('DropshippersAPIBundle:Module');
        $module = $modulesRepository->findOneById($moduleId);
        $module->setNotificationLink($notificationLink);
        $entityManager->persist($module);
        $entityManager->flush();
    }
}

{'fraction_non_alphanumeric': 0.1404330017554125, 'fraction_numerical': 0.005071191730056563, 'mean_word_length': 2.2126148705096074, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 217, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3869892', 'n_tokens_mistral': 4147, 'n_tokens_neox': 3980, 'n_words': 731}