Link.FYI

Pastebin

Create New My Pastes

Code (PHP) pasted on 2019-01-13, 19:39 Raw Source

  1. <?php
  2.  
  3. // Method in the ImportService, called during CSV import
  4.     private function autoAssignCategory(array $position, array $importRules) {
  5.         $categoryId = null;
  6.  
  7.         foreach ($importRules as $rule) {
  8.             if ($rule->appliesToPosition($position)) {
  9.                 $categoryId = $rule->getCategoryId();
  10.                 break;
  11.             }
  12.         }
  13.  
  14.         return $categoryId;
  15.     }
  16.  
  17.  
  18.  
  19. // ImportRule as returned by the ImportRuleService
  20.  
  21. class ImportRule {
  22.  
  23.     /** @var int */
  24.     private $categoryId;
  25.  
  26.     /** @var string */
  27.     private $categoryName;
  28.  
  29.     /** @var array */
  30.     private $rules;
  31.  
  32.  
  33.     public function __construct(int $categoryId, string $categoryName, array $rules) {
  34.         $this->categoryId = $categoryId;
  35.         $this->categoryName = $categoryName;
  36.         $this->rules = $rules;
  37.     }
  38.  
  39.     public function getCategoryId(): int {
  40.         return $this->categoryId;
  41.     }
  42.  
  43.     public function getCategoryName(): string {
  44.         return $this->categoryName;
  45.     }
  46.  
  47.     public function getRules(): array {
  48.         return $this->rules;
  49.     }
  50.  
  51.     public function setRules(array $rules) {
  52.         $this->rules = $rules;
  53.     }
  54.  
  55.     public function appliesToPosition(array $position) {
  56.         foreach ($this->rules as $rule) {
  57.             if (array_key_exists($rule->field, $position)) {
  58.                 if (property_exists($rule, 'regex') && !preg_match($rule->regex, $position[$rule->field])) {
  59.                     return false;
  60.                 } else if (property_exists($rule, 'value') && (trim($position[$rule->field]) != trim($rule->value))) {
  61.                     return false;
  62.                 }
  63.             } else {
  64.                 // Field does not exist, so we skip this rule
  65.                 return false;
  66.             }
  67.         }
  68.         return true;
  69.     }
  70.  
  71. }