| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <?php
- namespace App\Http\Controllers;
- use App\Models\Product;
- use Illuminate\Http\Request;
- use Illuminate\Support\Str;
- class ProductController extends Controller
- {
- public function index(Request $request){
- $data['products'] = Product::query()->paginate(20);
- $data['series'] = Product::query()->select('series')->distinct()->OrderBy('series')->get();
- return view('products.index', $data);
- }
- public function upload(Request $request){
- $xls = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($request->file('file'));
- $xls->setReadDataOnly(true);
- $sheet = $xls->load($request->file('file'));
- // read xls to array
- $goods = $sheet->setActiveSheetIndex(0)->toArray();
- unset($sheet, $xls);
- $series = '';
- $i = 1;
- $created = 0;
- $updated = 0;
- $no_image = [];
- foreach ($goods as $good){
- // check first line and skip it
- if($good[0] === '№п/п' && $good['3'] === 'Наименование') continue;
- // check the line is name of series
- if($good[0] == NULL && $good[1] == NULL && $good[2] == NULL && is_string($good[3])){
- $series = $good[3];
- continue;
- }
- $tmp = explode("\n", $good[3]);
- if(!isset($tmp[1])){
- $good[3] = preg_replace('!\s+!', ' ', $good[3]);
- $tmp = explode(' ', $good[3], 2);
- }
- $data = [
- // 'article' => $tmp[0],
- 'series' => $series,
- 'name' => (isset($tmp[1])) ? $tmp[1] : 'error',
- 'name_for_form' => $good[2],
- 'product_group' => $good[1],
- 'price' => $good[5],
- 'characteristics' => $good[4],
- 'tech_description' => $good[7],
- 'tech_description_short' => $good[8],
- 'image_path' => $this->find_image($tmp[0]),
- ];
- $a= Product::query()->updateOrCreate(['article' => $tmp[0]], $data);
- if($a->wasRecentlyCreated) $created++; else $updated++;
- //echo $i++ . '. Серия: ' . $series . ', артикул: ' . $tmp[0] . '<br>';
- $i++;
- if($data['image_path'] == '') $no_image[] = $tmp[0];
- }
- return view('products.import_result', ['count' => $i, 'updated' => $updated, 'created' => $created, 'no_image' => $no_image]);
- }
- private $allfiles; // rememer files list
- private function find_image($article){
- $path_to_files = './' . env('IMAGES_PATH', '---') . '/';
- if(!isset($this->allfiles) || empty($this->allfiles)){
- $this->allfiles = scandir($path_to_files);
- }
- foreach ($this->allfiles as $filename){
- if((mb_strpos($filename, $article) !== false) || (
- mb_strpos(Str::lower($filename), Str::slug($article)) !== false
- ))
- return $filename;
- }
- return '';
- }
- }
|