Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mindarc task from Hanwei Huang #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,35 @@ On completion, you should be able to provide an archive (<your_name>\_\<date>.ta
- media (directory with sample images inside)

Feel free to provide an archive with these deliverables, or if you prefer, fork this branch on github and push your changes as a feature branch using the same naming convention as required for the archive.


#Doc
Code example
```
//run poptable
$poptable = PopTable::getInstance()->run();
echo $poptable;
//run migrate
$migrate = PopTable::getInstance()->run();
echo $migrate

```

###wrong code table
| Name | Description |
| :---: | :---: |
| 4x | |
| 4001 | db connection failed |
| 4002 | initial table failed|
| 4003 | fail to build sql|
| 4004 | fail to insert data|
| 4005 | no data read from original table|
| 4006 | fail to read data from file|

| 2001 | success|


#upload image
1. In order to avoid images replaced by the same name image,
the file name saved by this rule:
time_filename.jpg
95 changes: 95 additions & 0 deletions exercise_dump.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# ************************************************************
# Sequel Pro SQL dump
# Version 4541
#
# http://www.sequelpro.com/
# https://github.com/sequelpro/sequelpro
#
# Host: 127.0.0.1 (MySQL 5.7.17)
# Database: mindarc_assessment
# Generation Time: 2019-02-15 14:20:50 +0000
# ************************************************************


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;


# Dump of table migrated_data
# ------------------------------------------------------------

DROP TABLE IF EXISTS `migrated_data`;

CREATE TABLE `migrated_data` (
`product_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`sku` varchar(50) NOT NULL DEFAULT '',
`name` varchar(255) NOT NULL DEFAULT '',
`image_url` varchar(255) DEFAULT '',
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `migrated_data` WRITE;
/*!40000 ALTER TABLE `migrated_data` DISABLE KEYS */;

INSERT INTO `migrated_data` (`product_id`, `sku`, `name`, `image_url`)
VALUES
(1,'men_red_shirt','Mens Red Shirt',''),
(2,'women_red_blouse','Womens Red Blouse','1550240237_4.jpeg'),
(3,'men_blue_shorts','Mens Blue Shorts',''),
(4,'women_blue_skirt','Womens Blue Skirt',''),
(5,'women_rainbow_singlet','Singlet in Rainbow Colours',''),
(6,'women_sun_one','Aviator Sunglasses',''),
(7,'women_gold_neck','Gold Necklace Chain',''),
(8,'women_iph_case','Iphone Case pink',''),
(9,'men_sam_case','Samsung Case Skulls',''),
(10,'men_black_shirt','AC/DC Shirt','');

/*!40000 ALTER TABLE `migrated_data` ENABLE KEYS */;
UNLOCK TABLES;


# Dump of table original_data
# ------------------------------------------------------------

DROP TABLE IF EXISTS `original_data`;

CREATE TABLE `original_data` (
`product_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_code` varchar(50) NOT NULL DEFAULT '',
`product_label` varchar(255) NOT NULL DEFAULT '',
`gender` varchar(255) DEFAULT '',
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

LOCK TABLES `original_data` WRITE;
/*!40000 ALTER TABLE `original_data` DISABLE KEYS */;

INSERT INTO `original_data` (`product_id`, `product_code`, `product_label`, `gender`)
VALUES
(1,'red_shirt','Mens Red Shirt','m'),
(2,'red_blouse','Womens Red Blouse','f'),
(3,'blue_shorts','Mens Blue Shorts','m'),
(4,'blue_skirt','Womens Blue Skirt','f'),
(5,'rainbow_singlet','Singlet in Rainbow Colours','v'),
(6,'sun_one','Aviator Sunglasses','f'),
(7,'gold_neck','Gold Necklace Chain',''),
(8,'iph_case','Iphone Case pink',' F'),
(9,'sam_case','Samsung Case Skulls','M'),
(10,'black_shirt','AC/DC Shirt','m');

/*!40000 ALTER TABLE `original_data` ENABLE KEYS */;
UNLOCK TABLES;



/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
100 changes: 100 additions & 0 deletions image-uploader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php
//run if $_FILES exist
if(!empty($_FILES)){
include __DIR__.'/pop-table.php';
$up = new UploadFile();
$result = $up -> handleUploadFile($_FILES, $_POST);
echo $result;

}

/**
* Class UploadFile for handle upload
*
*/
Class UploadFile{

private $columns = ['image_url'];
private $table = 'migrated_data';

public function handleUploadFile($files, $post){
$file = $files["upload-file"];
$imgType = array("png","jpg","jpeg");

if ($file["error"] == 0) {
$typeArr = explode("/", $file["type"]);
if($typeArr[0] != "image"){
return json_encode([
'error' => 'wrong image type',
]);
}
if(!in_array($typeArr[1], $imgType)){
return json_encode([
'error' => 'wrong image suffix',
]);
}
if(strlen($file['name'])>200){
return json_encode([
'error' => 'image name too long',
]);
}
if(!isset($post['id']) || empty($post['id'])){
return json_encode([
'error' => 'product id can not find',
]);
}
//filter and save files
$file_name = filter_var($file['name'], FILTER_SANITIZE_STRING);
$file_name = time().'_'.$file_name;
$img_name = "media/".$file_name;

$data = [
'filename' => $file_name,
'id' => $post['id'],
];
$re = DB::getInstance()->updateImagePathToDatabase($data, $this->columns, $this->table);
if($re === 'miss') return json_encode(['message' => 'product does not exist',]);
if($re === 'fail') return json_encode(['message' => 'update image url fail',]);
//save to
$bol = move_uploaded_file($file["tmp_name"], $img_name);
if($bol){
return json_encode([
'message' => 'success',
]);
} else {
return json_encode([
'error' => 'fail to upload',
]);
};

}else{
return json_encode([
"error" => "no files selected"
]);
}
}

}


?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>

<body>

<form method="post" action="/image-uploader.php" enctype="multipart/form-data">
<label>upload a file</label>
<input type="file" name="upload-file"><br>
<label>product id</label>
<input type="text" name="id"><br>
<input type="submit" value="upload">
</form>
</body>



</html>
Binary file added media/1.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added media/2.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added media/3.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added media/4.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
137 changes: 137 additions & 0 deletions migrate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php
include __DIR__.'/pop-table.php';

Class Migrate{

private $link;

//save instance
private static $instance;

private $original_table = 'original_data';
private $migrated_table = 'migrated_data';
private $original_columns = [
'product_code',
'product_label',
'gender',
];

private $transfer_columns = [
'sku',
'name',
];

private function __clone(){}

private function __construct()
{
$this->link = DB::getInstance()->getLink();
}

/**
* @return mixed
*/
public static function getInstance(){
if(!self::$instance instanceof self){
self::$instance = new Migrate();
}
return self::$instance;
}

/**
* @param bool $init
* @return string
* main function here
*/
public function run($init=true){
//1.get connection
$connection = $this->link;
if(empty($connection))
return json_encode([
'message' => 'db connection failed',
'code' => '4001'
]);


//2.read data from db
$data = $this->readDataFromDb(
$this->original_columns,$this->original_table,$connection);
if(empty($data)) {
return json_encode([
'message' => 'fail to read data from original table',
'code'=>'4006',
]);
}

//3.clear migrate db
if($init === true){
$re = DB::getInstance()->clearTable($this->migrated_table);
if(!$re) return json_encode([
'message' => 'initial table failed',
'code' => '4002'
]);
}
//4.build sql
$sql = DB::getInstance()->buildInsertSql($this->transfer_columns, $data, $this->migrated_table);
if($sql === false) {
return json_encode([
'message' => 'fail to build sql',
'code' => '4003',
]);
}
//5.save data in db, run the sql
return (mysqli_query($connection,$sql))?
json_encode([
'message'=> 'success',
'code' => '2001'
])
:
json_encode([
'message' => 'fail to insert data',
'code'=> '4004',
]);
}


/**
* @return array
* read data from original table
*/
private function readDataFromDb($columns, $table, $link){
//build sql
$cols = implode(",",$columns);
$sql = "SELECT $cols FROM $table";
//build return data
$return_array = [];
$result = mysqli_query($link,$sql);

if(mysqli_num_rows($result) > 0){
$i = 0;//index
while($row = mysqli_fetch_assoc($result)){
$gender = $row['gender'];
$filter_gender = $this->filterGender($gender);
$return_array[$i]['sku'] =$filter_gender.'_'.$row['product_code'];
$return_array[$i]['name'] = $row['product_label'];
$i++;
}
}

return $return_array;
}

/**
* @param $gender
* @return string
* process gender
*/
private function filterGender($gender){
if(empty($gender)) return 'women';
switch (strtoupper($gender)){
case 'F': return "women";
case 'M': return "men";
default: return "women";
}
}
}

Migrate::getInstance()->run();
Loading