Skip to content

Commit

Permalink
improve magento2 base url detection
Browse files Browse the repository at this point in the history
  • Loading branch information
danslo committed Sep 13, 2024
1 parent 27f3ef1 commit d720a54
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions magento2.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"

"github.com/sansecio/gocommerce/phpcfg"
)
Expand Down Expand Up @@ -69,13 +71,15 @@ func (m2 *Magento2) ParseConfig(cfgPath string) (*StoreConfig, error) {

func (m2 *Magento2) BaseURLs(docroot string) ([]string, error) {
cfgPath := filepath.Join(docroot, m2.ConfigPath())

urls, err := m2.getBaseURLsFromDatabase(cfgPath)
if err == nil {
return urls, nil
urls := []string{}
if ud, err := m2.getBaseURLsFromDatabase(cfgPath); err == nil {
urls = append(urls, ud...)
}

return m2.getBaseURLsFromConfig(cfgPath)
if uc, err := m2.getBaseURLsFromConfig(cfgPath); err == nil {
urls = append(urls, uc...)
}
slices.Sort(urls)
return slices.Compact(urls), nil
}

func (m2 *Magento2) Version(docroot string) (string, error) {
Expand All @@ -87,20 +91,24 @@ func (m2 *Magento2) Version(docroot string) (string, error) {
return getVersionFromJsonFile(docroot + "/composer.json")
}

func urlIsPlaceholder(url string) bool {
return strings.HasPrefix(url, "{{") || strings.HasSuffix(url, "}}")
}

func (m2 *Magento2) getBaseURLsFromConfig(cfgPath string) ([]string, error) {
cm, err := phpcfg.ParsePath(cfgPath)
if err != nil {
return nil, err
}

r, err := regexp.Compile(`root.system.\w+.web.secure.base_url`)
r, err := regexp.Compile(`root.system.\w+.web.(un)?secure.base_url`)
if err != nil {
return nil, err
}

urls := []string{}
for k, v := range cm {
if r.MatchString(k) {
if r.MatchString(k) && !urlIsPlaceholder(v) {
urls = append(urls, v)
}
}
Expand Down Expand Up @@ -135,7 +143,7 @@ func (m2 *Magento2) getBaseURLsFromDatabase(cfgPath string) ([]string, error) {
urls := []string{}
for rows.Next() {
var url string
if err := rows.Scan(&url); err == nil {
if err := rows.Scan(&url); err == nil && !urlIsPlaceholder(url) {
urls = append(urls, url)
}
}
Expand Down

0 comments on commit d720a54

Please sign in to comment.