/** * Method to get an array of products from a remote URI. * * @param $uri string * @return ProductList */ public function fetchProducts($uri) { // init our product list $products = new ProductList(); // get main product URL $url = $this->fetchUrl($uri); // setup domcrawler $crawler = new Crawler($url->getResponseContents()); $elements = $crawler->filter("#productLister div.productInfo h3 a"); /** @var \DOMElement $element */ foreach ($elements as $element) { $products->addProduct($this->getProductFromUrl($this->fetchUrl($element->getAttribute('href')))); } // and return! return $products; }
/** * Json JsonSeralise method. */ public function testJsonSerialize() { // product 1 $p1Title = 'Product 1 Title'; $p1Description = 'Product 1 Description'; $p1UnitPrice = '1.80'; $p1Uri = 'http://product1.com'; $p1Request = new Request('GET', $p1Uri); $p1Size = 97961231; $p1Response = new Response(200, ['Content-Length' => $p1Size]); $p1Url = new Url($p1Request, $p1Response); $p1 = new Product($p1Title, $p1Description, $p1UnitPrice, $p1Url); // product 2 $p2Title = 'Product 2 Title'; $p2Description = 'Product 2 Description'; $p2UnitPrice = '2.20'; $p2Uri = 'http://product2.com'; $p2Request = new Request('GET', $p2Uri); $p2Size = 123871203712; $p2Response = new Response(200, ['Content-Length' => $p2Size]); $p2Url = new Url($p2Request, $p2Response); $p2 = new Product($p2Title, $p2Description, $p2UnitPrice, $p2Url); // json $expectedJson = json_encode((object) ['results' => [(object) ['title' => $p1Title, 'size' => number_format($p1Size / 1000, 2, '.', '') . 'KB', 'unit_price' => $p1UnitPrice, 'description' => $p1Description], (object) ['title' => $p2Title, 'size' => number_format($p2Size / 1000, 2, '.', '') . 'KB', 'unit_price' => $p2UnitPrice, 'description' => $p2Description]], 'total' => '4.00']); $sut = new ProductList(); $sut->addProduct($p1); $sut->addProduct($p2); $this->assertEquals($expectedJson, json_encode($sut)); }