html() public method

Returns the first node of the list as HTML.
public html ( ) : string
return string The node html
Ejemplo n.º 1
0
 /**
  * @param Crawler $node
  *
  * @return array
  */
 protected function parse(Crawler $node)
 {
     $title = explode(' - ', $node->html());
     // Get the changes
     $nodes = $node->nextAll()->filterXPath('h3[preceding-sibling::h2[1][.="' . $node->html() . '"]]');
     $changes = (new ChangesRetriever($nodes))->retrieve();
     return ['name' => $title[0], 'date' => isset($title[1]) ? $title[1] : null, 'changes' => $changes];
 }
Ejemplo n.º 2
0
 public function setLaundryState(&$laundryPlace)
 {
     $user = '******';
     $pass = '******';
     try {
         $client = new Client($laundryPlace['url']);
         $request = $client->get('/LaundryState', [], ['auth' => [$user, $pass, 'Digest'], 'timeout' => 1.5, 'connect_timeout' => 1.5]);
         $response = $request->send();
         $body = $response->getBody();
         libxml_use_internal_errors(true);
         $crawler = new Crawler();
         $crawler->addContent($body);
         foreach ($crawler->filter('img') as $img) {
             $resource = $img->getAttribute('src');
             $img->setAttribute('src', 'http://129.241.126.11/' . trim($resource, '/'));
         }
         $crawler->addHtmlContent('<h1>foobar</h1>');
         //'<link href="http://129.241.126.11/pic/public_n.css" type="text/css">');
         $laundryPlace['html'] = $crawler->html();
         libxml_use_internal_errors(false);
         preg_match_all('/bgColor=Green/', $body, $greenMatches);
         preg_match_all('/bgColor=Red/', $body, $redMatches);
         $laundryPlace['busy'] = count($redMatches[0]);
         $laundryPlace['available'] = count($greenMatches[0]);
     } catch (\Exception $e) {
         $laundryPlace['available'] = self::NETWORK_ERROR;
         $laundryPlace['busy'] = self::NETWORK_ERROR;
         $laundryPlace['html'] = self::NETWORK_ERROR;
     }
 }
Ejemplo n.º 3
0
 /**
  * @param Crawler $crawler
  * @return mixed
  */
 private function getEventArrayFromResponse(Crawler $crawler)
 {
     $html = $crawler->html();
     $parts = explode(DefaultController::RESPONSE_BOUNDARY, $html);
     $event = unserialize($parts[1]);
     return $event;
 }
 public function onRenderAdminProductCategoryEditBefore(FilterResponseEvent $event)
 {
     $app = $this->app;
     $request = $event->getRequest();
     $response = $event->getResponse();
     $id = $request->attributes->get('id');
     // DomCrawlerにHTMLを食わせる
     $html = $response->getContent();
     $crawler = new Crawler($html);
     $CategoryContent = $app['category_content.repository.category_content']->find($id);
     if (is_null($CategoryContent)) {
         $CategoryContent = new \Plugin\CategoryContent\Entity\CategoryContent();
     }
     $form = $app['form.factory']->createBuilder('admin_category')->getForm();
     $form->get('content')->setData($CategoryContent->getContent());
     $form->handleRequest($request);
     $twig = $app->renderView('CategoryContent/Resource/template/Admin/category.twig', array('form' => $form->createView()));
     $oldCrawler = $crawler->filter('form')->first();
     // DomCrawlerからHTMLを吐き出す
     $html = $crawler->html();
     $oldHtml = '';
     $newHtml = '';
     if (count($oldCrawler) > 0) {
         $oldHtml = $oldCrawler->html();
         $newHtml = $oldHtml . $twig;
     }
     $html = str_replace($oldHtml, $newHtml, $html);
     $response->setContent($html);
     $event->setResponse($response);
 }
Ejemplo n.º 5
0
 /**
  * @param Crawler $block
  * @return array|null
  */
 public function getPrices(Crawler $block)
 {
     $results = preg_match_all('/(\\d+(\\.\\d{1,}|,\\d{1,})?) *(€|Eur|eur|EUR)/i', $block->html(), $matches);
     if ($results == 0) {
         return null;
     }
     return $matches[0];
 }
Ejemplo n.º 6
0
 /**
  * parse itemscope itemprop and hydrate given card
  * 
  * scope come from itemref, set isItemRef to true
  * 
  * @param Crawler $node
  * @param iCard $card
  * @param boolean $isItemref
  */
 public function getScopeContent(Crawler $node, CardInterface $card, $isItemref = false)
 {
     $content = $node->html();
     $cr = new Crawler($content);
     $cr->filter('[itemprop]')->each(function ($node) use($card, $isItemref) {
         $this->setCardProperty($node, $card, $isItemref);
     });
 }
Ejemplo n.º 7
0
 /**
  * @param Crawler $node
  *
  * @return array
  */
 protected function parse(Crawler $node)
 {
     $key = strtolower($node->html());
     if (!$key) {
         return;
     }
     $lines = (new LineRetriever($node->nextAll()->first()->filter('li')))->retrieve();
     return ['section' => $key, 'changes' => $lines];
 }
Ejemplo n.º 8
0
 /**
  * Check if the source or text is found within the element in the given crawler.
  *
  * @param  \Symfony\Component\DomCrawler\Crawler|string  $crawler
  * @return bool
  */
 public function matches($crawler)
 {
     $elements = $this->crawler($crawler)->filter($this->element);
     $pattern = $this->getEscapedPattern($this->text);
     foreach ($elements as $element) {
         $element = new Crawler($element);
         if (preg_match("/{$pattern}/i", $element->html())) {
             return true;
         }
     }
     return false;
 }
 /**
  * @param string $html
  *
  * @return string
  */
 protected function calculatePageSizeInKb(Crawler $crawler)
 {
     try {
         $html = $crawler->html();
     } catch (\InvalidArgumentException $e) {
         return self::NOT_AVAILABLE;
     }
     $size = mb_strlen($html) / 1024;
     if (is_numeric($size)) {
         $floatSize = (double) $size;
         return round($floatSize, 2) . 'kb';
     }
 }
 public function proxyImage(Twig_Environment $twig, $content)
 {
     if ($this->getEnabled() === false) {
         return $content;
     }
     $crawler = new Crawler($content);
     foreach ($crawler->filter('img') as $image) {
         $hashedImageUrl = hash_hmac(self::$hashingAlgorithm, self::$salt . $image->getAttribute('src'), self::$secret);
         $hexedImageUrl = bin2hex($image->getAttribute('src'));
         $proxiedImageUrl = self::$serverAddress . "/" . $hashedImageUrl . "/" . $hexedImageUrl;
         $image->setAttribute('src', $proxiedImageUrl);
     }
     return $crawler->html();
 }
Ejemplo n.º 11
0
 public function replaceImages(Flyer $flyer)
 {
     $flyer_html = $flyer->getHtml();
     $crawler = new Crawler();
     $crawler->addHtmlContent($flyer_html);
     foreach ($crawler->filter('img') as $domElement) {
         $attr_src = $domElement->getAttribute('src');
         if (!$this->validateURL($attr_src)) {
             $result = $this->utilsBusiness->upladImage($attr_src, 'flyers');
             $domElement->setAttribute('src', $result['url']);
         }
     }
     $flyer->setHtml($crawler->html());
     $this->saveData($flyer);
     return $flyer;
 }
Ejemplo n.º 12
0
 public function showRecommendProduct(FilterResponseEvent $event)
 {
     $app = $this->app;
     $id = $app['request']->attributes->get('id');
     $Product = $app['eccube.repository.product']->find($id);
     $RecommendProducts = $app['eccube.plugin.recommend.repository.recommend_product']->findAll();
     if (count($RecommendProducts) > 0) {
         $twig = $app->renderView('Recommend/View/recommend_product.twig', array('RecommendProducts' => $RecommendProducts));
         $response = $event->getResponse();
         $html = $response->getContent();
         $crawler = new Crawler($html);
         $oldElement = $crawler->filter('#main');
         $oldHtml = $oldElement->html();
         $newHtml = $oldHtml . $twig;
         $html = $crawler->html();
         $html = str_replace($oldHtml, $newHtml, $html);
         $response->setContent($html);
         $event->setResponse($response);
     }
 }
 /**
  * EC-CUBEの受注マスター画面のHTMLを取得し、帳票関連項目を書き込む
  *
  * @param unknown $request
  * @param unknown $response
  * @param unknown $id
  * @return mixed
  */
 private function getHtml($request, $response, $id)
 {
     // 検索結果一覧の下部に帳票出力を追加する
     // 受注管理-受注マスターのHTMLを取得し、DOM化
     $crawler = new Crawler($response->getContent());
     // [orm id="dropdown-form"]の最終項目に追加(レイアウトに依存(時間無いのでベタ))
     $html = $crawler->html();
     $parts = $this->app->renderView('OrderPdf/View/admin/order_pdf_menu.twig');
     try {
         // ※商品編集画面 idなりclassなりがきちんとつかないとDOMをいじるのは難しい
         // また、[その他]メニューの中に入れ込もうとしたがJQUERYのイベントが動作するので不可
         // = = = = = = = = =
         // その他メニューに追加するバージョン
         $form = $crawler->filter('#dropmenu .dropdown-menu')->last()->html();
         $newForm = $form . $parts;
         $html = str_replace($form, $newForm, $html);
     } catch (\InvalidArgumentException $e) {
         // no-op
     }
     return html_entity_decode($html);
 }
Ejemplo n.º 14
0
 /**
  * フロント:商品詳細画面に商品レビューを表示します.
  * @param FilterResponseEvent $event
  */
 public function onRenderProductsDetailBefore(FilterResponseEvent $event)
 {
     // カート内でも呼ばれるためGETに限定
     if ($event->getRequest()->getMethod() === 'GET') {
         $app = $this->app;
         $limit = $app['config']['review_regist_max'];
         $id = $app['request']->attributes->get('id');
         $Product = $app['eccube.repository.product']->find($id);
         $Disp = $app['eccube.repository.master.disp']->find(\Eccube\Entity\Master\Disp::DISPLAY_SHOW);
         $ProductReviews = $app['eccube.plugin.product_review.repository.product_review']->findBy(array('Product' => $Product, 'Status' => $Disp), array('create_date' => 'DESC'), $limit === null ? 5 : $limit);
         $twig = $app->renderView('ProductReview/Resource/template/default/product_review.twig', array('id' => $id, 'ProductReviews' => $ProductReviews));
         $response = $event->getResponse();
         $html = $response->getContent();
         $crawler = new Crawler($html);
         $oldElement = $crawler->filter('#item_detail_area .item_detail');
         $oldHtml = $oldElement->html();
         $newHtml = $oldHtml . $twig;
         $html = $crawler->html();
         $html = str_replace($oldHtml, $newHtml, $html);
         $response->setContent($html);
         $event->setResponse($response);
     }
 }
Ejemplo n.º 15
0
 public function addContentOnProductEdit(FilterResponseEvent $event)
 {
     $app = $this->app;
     $request = $event->getRequest();
     $response = $event->getResponse();
     $id = $request->attributes->get('id');
     $html = $response->getContent();
     $crawler = new Crawler($html);
     $form = $app['form.factory']->createBuilder('admin_product')->getForm();
     if ($id) {
         $Product = $app['eccube.repository.product']->find($id);
     } else {
         $Product = new \Eccube\Entity\Product();
     }
     $RelatedProducts = $app['eccube.plugin.repository.related_product']->findBy(array('Product' => $Product));
     $loop = 5 - count($RelatedProducts);
     for ($i = 0; $i < $loop; $i++) {
         $RelatedProduct = new \Plugin\RelatedProduct\Entity\RelatedProduct();
         $RelatedProduct->setProductId($id)->setProduct($Product);
         $RelatedProducts[] = $RelatedProduct;
     }
     $form->get('related_collection')->setData($RelatedProducts);
     $form->handleRequest($request);
     // 商品検索フォーム
     $searchForm = $app['form.factory']->createBuilder('admin_search_product')->getForm();
     $twig = $app->renderView('RelatedProduct/Resource/template/Admin/related_product.twig', array('form' => $form->createView()));
     $modal = $app->renderView('RelatedProduct/Resource/template/Admin/modal.twig', array('searchForm' => $searchForm->createView()));
     $oldElement = $crawler->filter('.accordion')->last();
     if ($oldElement->count() > 0) {
         $oldHtml = $oldElement->html();
         $newHtml = $oldHtml . $twig;
         $html = $crawler->html() . $modal;
         $html = str_replace($oldHtml, $newHtml, $html);
         $response->setContent($html);
         $event->setResponse($response);
     }
 }
Ejemplo n.º 16
0
 /**
  * Metodo para realizar a consulta
  *
  * @param  string $cnpj CNPJ
  * @param  string $captcha CAPTCHA
  * @param  string $stringCookie COOKIE
  * @throws Exception
  * @return array  Dados da empresa
  */
 public static function consulta($cnpj, $captcha, $stringCookie)
 {
     $result = array();
     $arrayCookie = explode(';', $stringCookie);
     if (!Utils::isCnpj($cnpj)) {
         throw new Exception('O CNPJ informado não é válido');
     }
     $client = new Client();
     $client->setHeader('Host', 'www.receita.fazenda.gov.br');
     $client->setHeader('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0');
     $client->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9, */* ;q=0.8');
     $client->setHeader('Accept-Language', 'pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3');
     $client->setHeader('Accept-Encoding', 'gzip, deflate');
     $client->setHeader('Referer', 'http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/valida.asp');
     $client->setHeader('Cookie', $arrayCookie[0]);
     $client->setHeader('Connection', 'keep-alive');
     $param = array('origem' => 'comprovante', 'cnpj' => Utils::unmask($cnpj), 'txtTexto_captcha_serpro_gov_br' => $captcha, 'submit1' => 'Consultar', 'search_type' => 'cnpj');
     $crawler = $client->request('POST', 'http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/valida.asp', $param);
     if ($crawler->filter('body > table:nth-child(3) > tr:nth-child(2) > td > b > font')->count() > 0) {
         throw new Exception('Erro ao consultar. O CNPJ informado não existe no cadastro.', 99);
     }
     $td = $crawler->filter('body > table:nth-child(3) > tr > td');
     foreach ($td->filter('td') as $td) {
         $td = new Crawler($td);
         if ($td->filter('font:nth-child(1)')->count() > 0) {
             $key = trim(preg_replace('/\\s+/', ' ', $td->filter('font:nth-child(1)')->html()));
             switch ($key) {
                 case 'NOME EMPRESARIAL':
                     $key = 'razao_social';
                     break;
                 case 'TÍTULO DO ESTABELECIMENTO (NOME DE FANTASIA)':
                     $key = 'nome_fantasia';
                     break;
                 case 'CÓDIGO E DESCRIÇÃO DA ATIVIDADE ECONÔMICA PRINCIPAL':
                     $key = 'cnae_principal';
                     break;
                 case 'CÓDIGO E DESCRIÇÃO DAS ATIVIDADES ECONÔMICAS SECUNDÁRIAS':
                     $key = 'cnaes_secundario';
                     break;
                 case 'CÓDIGO E DESCRIÇÃO DA NATUREZA JURÍDICA':
                     $key = 'natureza_juridica';
                     break;
                 case 'LOGRADOURO':
                     $key = 'logradouro';
                     break;
                 case 'NÚMERO':
                     $key = 'numero';
                     break;
                 case 'COMPLEMENTO':
                     $key = 'complemento';
                     break;
                 case 'CEP':
                     $key = 'cep';
                     break;
                 case 'BAIRRO/DISTRITO':
                     $key = 'bairro';
                     break;
                 case 'MUNICÍPIO':
                     $key = 'cidade';
                     break;
                 case 'UF':
                     $key = 'uf';
                     break;
                 case 'SITUAÇÃO CADASTRAL':
                     $key = 'situacao_cadastral';
                     break;
                 case 'DATA DA SITUAÇÃO CADASTRAL':
                     $key = 'situacao_cadastral_data';
                     break;
                 case 'MOTIVO DE SITUAÇÃO CADASTRAL':
                     $key = 'motivo_situacao_cadastral';
                     break;
                 case 'SITUAÇÃO ESPECIAL':
                     $key = 'situacao_especial';
                     break;
                 case 'DATA DA SITUAÇÃO ESPECIAL':
                     $key = 'situacao_especial_data';
                     break;
                 case 'TELEFONE':
                     $key = 'telefone';
                     break;
                 case 'ENDEREÇO ELETRÔNICO':
                     $key = 'email';
                     break;
                 case 'ENTE FEDERATIVO RESPONSÁVEL (EFR)':
                     $key = 'ente_federativo_responsavel';
                     break;
                 default:
                     $key = null;
                     break;
             }
             if (!is_null($key)) {
                 $bs = $td->filter('font > b');
                 foreach ($bs as $b) {
                     $b = new Crawler($b);
                     $str = trim(preg_replace('/\\s+/', ' ', $b->html()));
                     $attach = htmlspecialchars_decode($str);
                     if ($bs->count() == 1) {
                         $result[$key] = $attach;
                     } else {
                         $result[$key][] = $attach;
                     }
                 }
             }
         }
     }
     return $result;
 }
Ejemplo n.º 17
0
 public function onRenderProductsDetailBefore(FilterResponseEvent $event)
 {
     $app = $this->app;
     $request = $event->getRequest();
     $response = $event->getResponse();
     $id = $request->attributes->get('id');
     $ProductMaker = null;
     if ($id) {
         // 商品メーカーマスタから設定されているなメーカー情報を取得
         $ProductMaker = $this->app['eccube.plugin.maker.repository.product_maker']->find($id);
     }
     // HTMLを取得し、DOM化
     $crawler = new Crawler($response->getContent());
     $html = $crawler->html();
     if ($ProductMaker) {
         $parts = $this->app->renderView('Maker/View/default/maker.twig', array('maker_name' => $ProductMaker->getMaker()->getName(), 'maker_url' => $ProductMaker->getMakerUrl()));
         try {
             // ※商品コードの下に追加
             $parts_item_code = $crawler->filter('.item_code')->html();
             $new_html = $parts_item_code . $parts;
             $html = str_replace($parts_item_code, $new_html, $html);
         } catch (\InvalidArgumentException $e) {
             // no-op
         }
     }
     $response->setContent($html);
     $event->setResponse($response);
 }
Ejemplo n.º 18
0
 /**
  * @param \Symfony\Component\DomCrawler\Crawler $node
  * @param $pattern $text
  */
 public function seeNodePattern($node, $pattern)
 {
     $this->assertEquals(1, preg_match($pattern, $node->html()));
 }
            throw new Exception('Please enter a CSS selector');
        }
        $crawler = new Crawler();
        $crawler->addHtmlContent($userHtml);
        $crawlerHtml = $crawler->html();
        // to use later in view
        $result = $crawler->filter($userSelector);
        $resultCount = count($result);
        if ($resultCount > 0) {
            $resultText = $result->text();
        } else {
            // tidy version of it
            $tidyHtml = tidy_parse_string($userHtml);
            $tidyCrawler = new Crawler();
            $tidyCrawler->addHtmlContent($tidyHtml);
            $tidyCrawlerHtml = $tidyCrawler->html();
            // to use later in view
            $result = $tidyCrawler->filter($userSelector);
            $resultCount = count($result);
            if ($resultCount > 0) {
                $resultText = $result->text();
            }
        }
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
// view function to html escape
function escape($string)
{
    return htmlspecialchars($string, ENT_QUOTES, 'utf-8');
Ejemplo n.º 20
0
 /**
  * @param string  $field
  * @param Crawler $node
  *
  * @return string
  */
 protected function extractHtml($field, Crawler $node)
 {
     return $node->html();
 }
Ejemplo n.º 21
0
 /**
  * Decorates nodes that contains another nodes by attributes and class
  *
  * Nodes selected by selector will be decorated if contain nodes by another selector.
  *
  * Cases of use like cases of use the :has pseudo-selector
  *
  * @see https://drafts.csswg.org/selectors-4/#has-pseudo Selector Level 4
  *
  * @param string $html       Html for processing
  * @param string $selector   CSS-selector for children nodes
  * @param array  $attributes Attributes that will be set
  * @param string $class      Class that will be appended
  *
  * @return string
  */
 public static function decorateParent($html, $selector, $attributes = [], $class = '')
 {
     $crawler = new Crawler();
     $crawler->addHtmlContent($html, 'UTF-8');
     foreach ($crawler->filter($selector) as $node) {
         $parent = $node->parentNode;
         foreach ($attributes as $name => $value) {
             $parent->setAttribute($name, $value);
         }
         if ($parent->hasAttribute('class')) {
             $parent->setAttribute('class', $parent->getAttribute('class') . ' ' . $class);
         } else {
             $parent->setAttribute('class', $class);
         }
     }
     return $crawler->html();
 }
Ejemplo n.º 22
0
 public function removeGarbage($html_content, $project_id, $filename, $zones = array("meta", "script", "style", "br", "hr", "link", "img", "noindex", "doctype", "base"))
 {
     $project = Project::find($project_id);
     $raw_content = $html_content;
     try {
         $content = $this->removeWhiteSpaces($raw_content);
         $content = preg_replace("/<!--LiveInternet counter-->(.*?)<!--\\/LiveInternet-->/is", '', $content);
         $content = preg_replace("/<script\\b[^>]*>(.*?)<\\/script>/is", "", $content);
         $crawler = new Crawler($content);
         // $doc = new \DOMDocument();
         // libxml_use_internal_errors(true);
         // $doc->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8') );
         // libxml_clear_errors();
         // libxml_use_internal_errors(false);
         // $xpath = new \DOMXpath($doc);
         foreach ($zones as $zone) {
             // $elements = $xpath->query("*/".$zone);
             // $elements = $xpath->query("*/".$zone);
             // if (!is_null($elements)) {
             // 	  foreach ($elements as $element) {
             // 	    $element->parentNode->removeChild($element);
             // 	  }
             // 	}
             $crawler->filter($zone)->each(function (Crawler $crawler) {
                 foreach ($crawler as $node) {
                     $tmp_html = $node->ownerDocument->saveHTML($node);
                     // file_put_contents('test_kokt.txt', $tmp_html."\n", FILE_APPEND);
                     $node->parentNode->removeChild($node);
                 }
             });
         }
         // $cleaned_content = $doc->saveHTML();
         $cleaned_content = $crawler->html();
         $cleaned_content = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . $cleaned_content;
         $wo_garbage_path = storage_path("tmp/" . $project->dir . "/html_wo_garbage/");
         $wo_garbage_file = $wo_garbage_path . $filename;
         file_put_contents($wo_garbage_file, $cleaned_content);
     } catch (\Exception $e) {
         if (file_exists(storage_path("tmp/" . $project->dir . "/html/" . $filename))) {
             unlink(storage_path("tmp/" . $project->dir . "/html/" . $filename));
         }
         $mes = $e->getMessage();
         $cleaned_content = "Warning ERROR: Can not remove garbage " . $mes . "\n";
         // $cleaned_content = "Warning ERROR: Can not remove garbage ".$mes."\n".$content;
         // file_put_contents("/var/www/test.txt", print_r($cleaned_content,true), FILE_APPEND);
     }
     return $cleaned_content;
 }
Ejemplo n.º 23
0
 /**
  * Builds final pdf
  *
  * @return mPDF
  * @throws \Exception
  */
 private function build()
 {
     if (empty($this->documentTitle)) {
         throw new \Exception("Var 'documentTitle' cannot be empty.");
     }
     if ($this->ignoreStylesInHTMLDocument) {
         if (!class_exists('Symfony\\Component\\DomCrawler\\Crawler')) {
             throw new MissingServiceException("Class 'Symfony\\Component\\DomCrawler\\Crawler' not found. Try composer-require 'symfony/dom-crawler'.");
         }
         if (!class_exists('Symfony\\Component\\CssSelector\\CssSelector')) {
             throw new MissingServiceException("Class 'Symfony\\Component\\CssSelector\\CssSelector' not found. Try composer-require 'symfony/css-selector'.");
         }
     }
     if ($this->generatedFile) {
         // singleton
         return $this->generatedFile;
     }
     if ($this->source instanceof ITemplate || $this->source instanceof Template) {
         $html = $this->source->__toString();
     } else {
         $html = $this->source;
     }
     // Fix: $html can't be empty (mPDF generates Fatal error)
     if (empty($html)) {
         $html = '<html><body></body></html>';
     }
     $mpdf = $this->getMPDF();
     $mpdf->biDirectional = $this->multiLanguage;
     $mpdf->SetAuthor($this->documentAuthor);
     $mpdf->SetTitle($this->documentTitle);
     $mpdf->SetDisplayMode($this->displayZoom, $this->displayLayout);
     $mpdf->showImageErrors = true;
     // Add styles
     if (!empty($this->styles)) {
         $mpdf->WriteHTML($this->styles, 1);
     }
     // copied from mPDF -> removes comments
     $html = preg_replace('/<!--mpdf/i', '', $html);
     $html = preg_replace('/mpdf-->/i', '', $html);
     $html = preg_replace('/<\\!\\-\\-.*?\\-\\->/s', '', $html);
     // @see: http://mpdf1.com/manual/index.php?tid=121&searchstring=writeHTML
     if ($this->ignoreStylesInHTMLDocument) {
         // deletes all <style> tags
         $crawler = new Crawler($html);
         foreach ($crawler->filter('style') as $child) {
             $child->parentNode->removeChild($child);
         }
         $html = $crawler->html();
         $mode = 2;
         // If <body> tags are found, all html outside these tags are discarded, and the rest is parsed as content for the document. If no <body> tags are found, all html is parsed as content. Prior to mPDF 4.2 the default CSS was not parsed when using mode #2
     } else {
         $mode = 0;
         // Parse all: HTML + CSS
     }
     // Add content
     $mpdf->WriteHTML($html, $mode);
     $mpdf->page = count($mpdf->pages);
     //set pointer to last page to force render of all pages
     $this->onBeforeComplete($mpdf);
     $this->generatedFile = $mpdf;
     return $this->generatedFile;
 }
 /**
  * Check if the page contains text within the given element.
  *
  * @param  string  $element
  * @param  string  $text
  * @return bool
  */
 protected function hasInElement($element, $text)
 {
     $elements = $this->crawler->filter($element);
     $rawPattern = preg_quote($text, '/');
     $escapedPattern = preg_quote(e($text), '/');
     $pattern = $rawPattern == $escapedPattern ? $rawPattern : "({$rawPattern}|{$escapedPattern})";
     foreach ($elements as $element) {
         $element = new Crawler($element);
         if (preg_match("/{$pattern}/i", $element->html())) {
             return true;
         }
     }
     return false;
 }
Ejemplo n.º 25
0
 /**
  * Test get
  */
 public function testGet()
 {
     $this->buildDialogue('foo', ['bar' => 'baz'], $this->xml);
     $result = $this->browser->get('foo', ['bar' => 'baz']);
     $this->assertInstanceOf('\\Symfony\\Component\\DomCrawler\\Crawler', $result);
     // objects are not identical, but their content should match
     $expected = new Crawler($this->xml);
     $this->assertEquals($expected->html(), $result->html());
 }
Ejemplo n.º 26
0
 /**
  * @param \Symfony\Component\DomCrawler\Crawler $crawler
  * @param array $mapping
  * @return array
  */
 public function scraping($crawler, $mapping = [])
 {
     if (Utils::isBlank($mapping)) {
         return [$crawler->html()];
     }
     $ret = [];
     foreach ($mapping as $key => $value) {
         $dom = $crawler->{$value}['filter']($value['selector']);
         if (isset($value['subset']) && !Utils::isBlank($value['subset'])) {
             $ret[$key] = $dom->each(function ($node) use($value) {
                 return $this->getValue($node, $value['attr'], $value['trim']);
             });
         } else {
             $ret[$key] = $this->getValue($dom, $value['attr'], $value['trim']);
         }
     }
     return $ret;
 }
 /**
  * Check if the page contains text within the given element.
  *
  * @param  string  $element
  * @param  string  $text
  * @return bool
  */
 protected function hasInElement($element, $text)
 {
     $elements = $this->crawler()->filter($element);
     $pattern = $this->getEscapedPattern($text);
     foreach ($elements as $element) {
         $element = new Crawler($element);
         if (preg_match("/{$pattern}/i", $element->html())) {
             return true;
         }
     }
     return false;
 }
 /**
  * Populate the object with the values from the node
  *
  * @param  Crawler $node
  * @return object
  */
 public static function populate(Crawler $node)
 {
     $map = array('bytes' => mb_strlen($node->html(), '8bit'));
     return parent::fill(self::create(), $map);
 }
 public function onRenderAdminProductEditBefore(FilterResponseEvent $event)
 {
     $app = $this->app;
     $request = $event->getRequest();
     $response = $event->getResponse();
     // メーカーマスタから有効なメーカー情報を取得
     $repos = $app['eccube.plugin.mail_magazine.repository.mail_magazine'];
     $MailMagazines = $repos->findAll();
     if (is_null($MailMagazines)) {
         $MailMagazines = new \Plugin\MailMagazine\Entity\MailMagazine();
     }
     // 商品登録・編集画面のHTMLを取得し、DOM化
     $crawler = new Crawler($response->getContent());
     $form = $app['form.factory']->createBuilder('admin_product_mail_magazine')->getForm();
     $form->get('mail_magazine')->setData($MailMagazines);
     $form->handleRequest($request);
     $parts = $app->renderView('MailMagazine/View/admin/product_mail_magazine.twig', array('form' => $form->createView()));
     // form1の最終項目に追加(レイアウトに依存(時間無いのでベタ))
     $html = $crawler->html();
     $form = $crawler->filter('#form1 .accordion')->last()->html();
     $new_form = $form . $parts;
     $html = str_replace($form, $new_form, $html);
     $response->setContent($html);
     $event->setResponse($response);
 }
Ejemplo n.º 30
-1
 protected function process($content)
 {
     $parser = new Parser('yaml', 'markdown');
     $frontmatter = $parser->parse($content);
     $crawler = new Crawler();
     $crawler->addHtmlContent($frontmatter->getBody());
     $title = '';
     $crawler->filterXPath('//h1')->each(function (Crawler $crawler) use(&$title) {
         foreach ($crawler as $node) {
             if (!$title) {
                 $title = $node->nodeValue;
             }
             $node->parentNode->removeChild($node);
         }
     });
     $images = $crawler->filterXPath('//img');
     foreach ($images as $image) {
         $src = $image->getAttribute('src');
         $image->setAttribute('src', str_replace('../..', '', $src));
     }
     $body = $crawler->html();
     $intro = explode('<hr>', $body)[0];
     $body = str_replace('<hr>', '', $body);
     return ['title' => $title ?: '', 'keywords' => isset($frontmatter->head['keywords']) ? $frontmatter->head['keywords'] : '', 'description' => isset($frontmatter->head['description']) ? $frontmatter->head['description'] : mb_substr(strip_tags(trim($intro)), 0, 150), 'intro' => trim($intro), 'cover' => isset($frontmatter->head['cover']) ? $frontmatter->head['cover'] : '', 'content' => trim($body), 'tags' => isset($frontmatter->head['tags']) ? $frontmatter->head['tags'] : ''];
 }